context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. using Microsoft.Graphics.Canvas; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using System; using System.IO; using System.Threading.Tasks; using Windows.Graphics.Imaging; using Windows.Storage; using Windows.UI; #if WINDOWS_UWP using Windows.Graphics.DirectX; #endif namespace test.managed { [TestClass] public class CanvasBitmapTests { [TestMethod] public void MultithreadedSaveToFile() { // // This test can create a deadlock if that SaveAsync code holds on to the // ID2D1Multithread resource lock longer than necessary. // // A previous implementation waited until destruction of the IAsyncAction before calling Leave(). // In managed code this can happen on an arbitrary thread and so could result in deadlock situations // where other worker threads were waiting for a Leave on the original thread that never arrived. // var task = Task.Run(async () => { var device = new CanvasDevice(); var rt = new CanvasRenderTarget(device, 16, 16, 96); var filename = Path.Combine(ApplicationData.Current.TemporaryFolder.Path, "testfile.jpg"); await rt.SaveAsync(filename); rt.Dispose(); }); task.Wait(); } [TestMethod] public void MultithreadedSaveToStream() { // This is the stream version of the above test var task = Task.Run(async () => { var device = new CanvasDevice(); var rt = new CanvasRenderTarget(device, 16, 16, 96); var stream = new MemoryStream(); await rt.SaveAsync(stream.AsRandomAccessStream(), CanvasBitmapFileFormat.Bmp); rt.Dispose(); }); task.Wait(); } } #if WINDOWS_UWP [TestClass] public class CanvasBitmapCreateFromSoftwareBitmapTests { CanvasDevice device = new CanvasDevice(true); [TestMethod] public void CanvasBitmap_CreateFromSoftwareBitmap_Roundtrip() { var colors = new Color[] { Colors.Red, Colors.Green, Colors.Yellow, Colors.Green, Colors.Yellow, Colors.Red, Colors.Yellow, Colors.Red, Colors.Green }; float anyDpi = 10; var originalBitmap = CanvasBitmap.CreateFromColors(device, colors, 3, 3, anyDpi); var softwareBitmap = SoftwareBitmap.CreateCopyFromSurfaceAsync(originalBitmap, BitmapAlphaMode.Premultiplied).AsTask().Result; softwareBitmap.DpiX = anyDpi; softwareBitmap.DpiY = anyDpi; var roundtrippedBitmap = CanvasBitmap.CreateFromSoftwareBitmap(device, softwareBitmap); Assert.AreEqual(originalBitmap.Format, roundtrippedBitmap.Format); Assert.AreEqual(anyDpi, roundtrippedBitmap.Dpi); var roundtrippedColors = roundtrippedBitmap.GetPixelColors(); Assert.AreEqual(colors.Length, roundtrippedColors.Length); for (var i = 0; i < colors.Length; ++i) { Assert.AreEqual(colors[i], roundtrippedColors[i]); } } [TestMethod] public void CanvasBitmap_CreateFromSoftwareBitmap_PixelFormats() { foreach (BitmapPixelFormat e in Enum.GetValues(typeof(BitmapPixelFormat))) { bool hasAlpha = true; switch (e) { case BitmapPixelFormat.Gray16: case BitmapPixelFormat.Gray8: case BitmapPixelFormat.Nv12: case BitmapPixelFormat.Yuy2: hasAlpha = false; break; } if (hasAlpha) { TestCreateFromSoftwareBitmap(e, BitmapAlphaMode.Premultiplied); TestCreateFromSoftwareBitmap(e, BitmapAlphaMode.Straight); TestCreateFromSoftwareBitmap(e, BitmapAlphaMode.Ignore); } else { TestCreateFromSoftwareBitmap(e, BitmapAlphaMode.Ignore); } } } void TestCreateFromSoftwareBitmap(BitmapPixelFormat pixelFormat, BitmapAlphaMode alphaMode) { if (pixelFormat == BitmapPixelFormat.Unknown) return; int anyWidth = 3; int anyHeight = 5; var softwareBitmap = new SoftwareBitmap(pixelFormat, anyWidth, anyHeight, alphaMode); if (!IsFormatSupportedByWin2D(pixelFormat, alphaMode)) { Assert.ThrowsException<Exception>(() => { CanvasBitmap.CreateFromSoftwareBitmap(device, softwareBitmap); }); return; } var canvasBitmap = CanvasBitmap.CreateFromSoftwareBitmap(device, softwareBitmap); Assert.AreEqual(anyWidth, (int)canvasBitmap.SizeInPixels.Width); Assert.AreEqual(anyHeight, (int)canvasBitmap.SizeInPixels.Height); Assert.AreEqual(GetDirectXPixelFormatUsedForBitmapPixelFormat(pixelFormat), canvasBitmap.Format); CanvasAlphaMode expectedAlphaMode = CanvasAlphaMode.Straight; switch (alphaMode) { case BitmapAlphaMode.Ignore: expectedAlphaMode = CanvasAlphaMode.Ignore; break; case BitmapAlphaMode.Premultiplied: expectedAlphaMode = CanvasAlphaMode.Premultiplied; break; case BitmapAlphaMode.Straight: expectedAlphaMode = CanvasAlphaMode.Straight; break; } Assert.AreEqual(expectedAlphaMode, canvasBitmap.AlphaMode); } DirectXPixelFormat GetDirectXPixelFormatUsedForBitmapPixelFormat(BitmapPixelFormat format) { // // Although BitmapPixelFormat looks like it corresponds directly to DirectXPixelFormat, // it turns out that some of the types are generally intended to be used differently. Win2D // provides these conversions. // switch (format) { // The BitmapPixelFormat entry for these types use the plain UInt version. However, // these really were meant to use the UIntNormalized types so Win2D treats them as such. case BitmapPixelFormat.Rgba16: return DirectXPixelFormat.R16G16B16A16UIntNormalized; case BitmapPixelFormat.Rgba8: return DirectXPixelFormat.R8G8B8A8UIntNormalized; // The BitmapPixelFormat entry for Gray8 suggests R8Uint. However, it's intended to be // used as UIntNormalized, plus D2D only supports A8UintNormalized, so that's what is // used here. case BitmapPixelFormat.Gray8: return DirectXPixelFormat.A8UIntNormalized; // Other pixel formats are directly castable to the DirectXPixelFormat. default: return (DirectXPixelFormat)format; } } bool IsFormatSupportedByWin2D(BitmapPixelFormat format, BitmapAlphaMode alphaMode) { // Win2D only supports A8UintNormalized with straight alpha. SoftwareBitmap doesn't // support A8UintNormalized. if (alphaMode == BitmapAlphaMode.Straight) return false; switch (format) { case BitmapPixelFormat.Gray16: case BitmapPixelFormat.Nv12: case BitmapPixelFormat.Yuy2: // Direct2D doesn't support these formats return false; case BitmapPixelFormat.Gray8: if (alphaMode == BitmapAlphaMode.Ignore) return false; else return true; } return true; } } #endif }
// 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 Pointer = System.Reflection.Pointer; public class BringUpTests { const int Pass = 100; const int Fail = -1; public static int Main() { int result = Pass; if (!TestValueTypeDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestVirtualDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestInterfaceDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestStaticOpenClosedDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestMulticastDelegates()) { Console.WriteLine("Failed"); result = Fail; } if (!TestDynamicInvoke()) { Console.WriteLine("Failed"); result = Fail; } return result; } public static bool TestValueTypeDelegates() { Console.Write("Testing delegates to value types..."); { TestValueType t = new TestValueType { X = 123 }; Func<string, string> d = t.GiveX; string result = d("MyPrefix"); if (result != "MyPrefix123") return false; } { object t = new TestValueType { X = 456 }; Func<string> d = t.ToString; string result = d(); if (result != "456") return false; } { Func<int, TestValueType> d = TestValueType.MakeValueType; TestValueType result = d(789); if (result.X != 789) return false; } Console.WriteLine("OK"); return true; } public static bool TestVirtualDelegates() { Console.Write("Testing delegates to virtual methods..."); { Mid t = new Mid(); if (t.GetBaseDo()() != "Base") return false; if (t.GetDerivedDo()() != "Mid") return false; } { Mid t = new Derived(); if (t.GetBaseDo()() != "Base") return false; if (t.GetDerivedDo()() != "Derived") return false; } { // This will end up being a delegate to a sealed virtual method. ClassWithIFoo t = new ClassWithIFoo("Class"); Func<int, string> d = t.DoFoo; if (d(987) != "Class987") return false; } Console.WriteLine("OK"); return true; } public static bool TestInterfaceDelegates() { Console.Write("Testing delegates to interface methods..."); { IFoo t = new ClassWithIFoo("Class"); Func<int, string> d = t.DoFoo; if (d(987) != "Class987") return false; } { IFoo t = new StructWithIFoo("Struct"); Func<int, string> d = t.DoFoo; if (d(654) != "Struct654") return false; } Console.WriteLine("OK"); return true; } public static bool TestStaticOpenClosedDelegates() { Console.Write("Testing static open and closed delegates..."); { Func<string, string, string> d = ExtensionClass.Combine; if (d("Hello", "World") != "HelloWorld") return false; } { Func<string, string> d = "Hi".Combine; if (d("There") != "HiThere") return false; } Console.WriteLine("OK"); return true; } public static bool TestMulticastDelegates() { Console.Write("Testing multicast delegates..."); { ClassThatMutates t = new ClassThatMutates(); Action d = t.AddOne; d(); if (t.State != 1) return false; t.State = 0; d += t.AddTwo; d(); if (t.State != 3) return false; t.State = 0; d += t.AddOne; d(); if (t.State != 4) return false; } Console.WriteLine("OK"); return true; } public static bool TestDynamicInvoke() { Console.Write("Testing dynamic invoke..."); { TestValueType t = new TestValueType { X = 123 }; Func<string, string> d = t.GiveX; string result = (string)d.DynamicInvoke(new object[] { "MyPrefix" }); if (result != "MyPrefix123") return false; } { Func<int, TestValueType> d = TestValueType.MakeValueType; TestValueType result = (TestValueType)d.DynamicInvoke(new object[] { 789 }); if (result.X != 789) return false; } { IFoo t = new ClassWithIFoo("Class"); Func<int, string> d = t.DoFoo; if ((string)d.DynamicInvoke(new object[] { 987 }) != "Class987") return false; } { IFoo t = new StructWithIFoo("Struct"); Func<int, string> d = t.DoFoo; if ((string)d.DynamicInvoke(new object[] { 654 }) != "Struct654") return false; } { Func<string, string, string> d = ExtensionClass.Combine; if ((string)d.DynamicInvoke(new object[] { "Hello", "World" }) != "HelloWorld") return false; } { Func<string, string> d = "Hi".Combine; if ((string)d.DynamicInvoke(new object[] { "There" }) != "HiThere") return false; } { Mutate<int> d = ClassWithByRefs.Mutate; object[] args = new object[] { 8 }; d.DynamicInvoke(args); if ((int)args[0] != 50) return false; } { Mutate<string> d = ClassWithByRefs.Mutate; object[] args = new object[] { "Hello" }; d.DynamicInvoke(args); if ((string)args[0] != "HelloMutated") return false; } unsafe { GetAndReturnPointerDelegate d = ClassWithPointers.GetAndReturnPointer; if (Pointer.Unbox(d.DynamicInvoke(new object[] { (IntPtr)8 })) != (void*)50) return false; if (Pointer.Unbox(d.DynamicInvoke(new object[] { Pointer.Box((void*)9, typeof(void*)) })) != (void*)51) return false; } #if false // This is hitting an EH bug around throw/rethrow from a catch block (pass is not set properly) unsafe { PassPointerByRefDelegate d = ClassWithPointers.PassPointerByRef; var args = new object[] { (IntPtr)8 }; bool caught = false; try { d.DynamicInvoke(args); } catch (ArgumentException) { caught = true; } if (!caught) return false; } #endif Console.WriteLine("OK"); return true; } struct TestValueType { public int X; public string GiveX(string prefix) { return prefix + X.ToString(); } public static TestValueType MakeValueType(int value) { return new TestValueType { X = value }; } public override string ToString() { return X.ToString(); } } class Base { public virtual string Do() { return "Base"; } } class Mid : Base { public override string Do() { return "Mid"; } public Func<string> GetBaseDo() { return base.Do; } public Func<string> GetDerivedDo() { return Do; } } class Derived : Mid { public override string Do() { return "Derived"; } } interface IFoo { string DoFoo(int x); } class ClassWithIFoo : IFoo { string _prefix; public ClassWithIFoo(string prefix) { _prefix = prefix; } public string DoFoo(int x) { return _prefix + x.ToString(); } } struct StructWithIFoo : IFoo { string _prefix; public StructWithIFoo(string prefix) { _prefix = prefix; } public string DoFoo(int x) { return _prefix + x.ToString(); } } class ClassThatMutates { public int State; public void AddOne() { State++; } public void AddTwo() { State += 2; } } } static class ExtensionClass { public static string Combine(this string s1, string s2) { return s1 + s2; } } unsafe delegate byte* GetAndReturnPointerDelegate(void* ptr); unsafe delegate void PassPointerByRefDelegate(ref void* ptr); unsafe static class ClassWithPointers { public static byte* GetAndReturnPointer(void* ptr) { return (byte*)ptr + 42; } public static void PassPointerByRef(ref void* ptr) { ptr = (byte*)ptr + 42; } } delegate void Mutate<T>(ref T x); class ClassWithByRefs { public static void Mutate(ref int x) { x += 42; } public static void Mutate(ref string x) { x += "Mutated"; } }
//----------------------------------------------------------------------- // <copyright file="CommandBase.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>This is the base class from which command </summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using Csla.Server; using Csla.Properties; using Csla.Core; using Csla.Serialization.Mobile; using Csla.DataPortalClient; using System.Linq.Expressions; using Csla.Reflection; using System.Reflection; using System.Threading.Tasks; namespace Csla { /// <summary> /// This is the base class from which command /// objects will be derived. /// </summary> /// <remarks> /// <para> /// Command objects allow the execution of arbitrary server-side /// functionality. Most often, this involves the invocation of /// a stored procedure in the database, but can involve any other /// type of stateless, atomic call to the server instead. /// </para><para> /// To implement a command object, inherit from CommandBase and /// override the DataPortal_Execute method. In this method you can /// implement any server-side code as required. /// </para><para> /// To pass data to/from the server, use instance variables within /// the command object itself. The command object is instantiated on /// the client, and is passed by value to the server where the /// DataPortal_Execute method is invoked. The command object is then /// returned to the client by value. /// </para> /// </remarks> [Serializable] public abstract class CommandBase<T> : ManagedObjectBase, ICommandObject, ICloneable, Csla.Server.IDataPortalTarget, Csla.Core.IManageProperties, ICommandBase where T : CommandBase<T> { #region Constructors /// <summary> /// Creates an instance of the object. /// </summary> public CommandBase() { Initialize(); } #endregion #region Initialize /// <summary> /// Override this method to set up event handlers so user /// code in a partial class can respond to events raised by /// generated code. /// </summary> protected virtual void Initialize() { /* allows subclass to initialize events before any other activity occurs */ } #endregion #region Identity int IBusinessObject.Identity { get { return 0; } } #endregion #region Data Access [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void DataPortal_Create(object criteria) { throw new NotSupportedException(Resources.CreateNotSupportedException); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void DataPortal_Fetch(object criteria) { throw new NotSupportedException(Resources.FetchNotSupportedException); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void DataPortal_Update() { throw new NotSupportedException(Resources.UpdateNotSupportedException); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void DataPortal_Delete(object criteria) { throw new NotSupportedException(Resources.DeleteNotSupportedException); } /// <summary> /// Override this method to implement any server-side code /// that is to be run when the command is executed. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] protected virtual void DataPortal_Execute() { throw new NotSupportedException(Resources.ExecuteNotSupportedException); } /// <summary> /// Called by the server-side DataPortal prior to calling the /// requested DataPortal_xyz method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal after calling the /// requested DataPortal_xyz method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal if an exception /// occurs during server-side processing. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> /// <param name="ex">The Exception thrown during processing.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } #endregion #region IDataPortalTarget Members void IDataPortalTarget.CheckRules() { } void IDataPortalTarget.MarkAsChild() { } void IDataPortalTarget.MarkNew() { } void IDataPortalTarget.MarkOld() { } void IDataPortalTarget.DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvoke(e); } void IDataPortalTarget.DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvokeComplete(e); } void IDataPortalTarget.DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { this.DataPortal_OnDataPortalException(e, ex); } void IDataPortalTarget.Child_OnDataPortalInvoke(DataPortalEventArgs e) { } void IDataPortalTarget.Child_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } void IDataPortalTarget.Child_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } #endregion #region ICloneable object ICloneable.Clone() { return GetClone(); } /// <summary> /// Creates a clone of the object. /// </summary> /// <returns> /// A new object containing the exact data of the original object. /// </returns> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual object GetClone() { return ObjectCloner.Clone(this); } /// <summary> /// Creates a clone of the object. /// </summary> /// <returns> /// A new object containing the exact data of the original object. /// </returns> public T Clone() { return (T)GetClone(); } #endregion #region Register Properties /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P"> /// Type of property. /// </typeparam> /// <param name="info"> /// PropertyInfo object for the property. /// </param> /// <returns> /// The provided IPropertyInfo object. /// </returns> protected static PropertyInfo<P> RegisterProperty<P>(PropertyInfo<P> info) { return Core.FieldManager.PropertyInfoManager.RegisterProperty<P>(typeof(T), info); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="defaultValue">Default Value for the property</param> /// <returns></returns> [Obsolete] protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, P defaultValue) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), reflectedPropertyInfo.Name, reflectedPropertyInfo.Name, defaultValue)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, RelationshipTypes relationship) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, string.Empty, relationship)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, RelationshipTypes relationship) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name, relationship); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name, friendlyName); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> [Obsolete] protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, RelationshipTypes relationship) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), reflectedPropertyInfo.Name, friendlyName, relationship)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName, P defaultValue) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName, defaultValue)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, P defaultValue) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name, friendlyName, defaultValue); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName, P defaultValue, RelationshipTypes relationship) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName, defaultValue, relationship)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, P defaultValue, RelationshipTypes relationship) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name, friendlyName, defaultValue, relationship); } #endregion #region IManageProperties Members bool IManageProperties.HasManagedProperties { get { return (FieldManager != null && FieldManager.HasFields); } } List<IPropertyInfo> IManageProperties.GetManagedProperties() { return FieldManager.GetRegisteredProperties(); } object IManageProperties.GetProperty(IPropertyInfo propertyInfo) { return ReadProperty(propertyInfo); } object IManageProperties.ReadProperty(IPropertyInfo propertyInfo) { return ReadProperty(propertyInfo); } P IManageProperties.ReadProperty<P>(PropertyInfo<P> propertyInfo) { return ReadProperty<P>(propertyInfo); } void IManageProperties.SetProperty(IPropertyInfo propertyInfo, object newValue) { FieldManager.SetFieldData(propertyInfo, newValue); } void IManageProperties.LoadProperty(IPropertyInfo propertyInfo, object newValue) { LoadProperty(propertyInfo, newValue); } void IManageProperties.LoadProperty<P>(PropertyInfo<P> propertyInfo, P newValue) { LoadProperty<P>(propertyInfo, newValue); } bool IManageProperties.LoadPropertyMarkDirty(IPropertyInfo propertyInfo, object newValue) { LoadProperty(propertyInfo, newValue); return false; } List<object> IManageProperties.GetChildren() { return FieldManager.GetChildren(); } bool IManageProperties.FieldExists(Core.IPropertyInfo property) { return FieldManager.FieldExists(property); } object IManageProperties.LazyGetProperty<P>(PropertyInfo<P> propertyInfo, Func<P> valueGenerator) { throw new NotImplementedException(); } object IManageProperties.LazyGetPropertyAsync<P>(PropertyInfo<P> propertyInfo, Task<P> factory) { throw new NotImplementedException(); } P IManageProperties.LazyReadProperty<P>(PropertyInfo<P> propertyInfo, Func<P> valueGenerator) { throw new NotImplementedException(); } P IManageProperties.LazyReadPropertyAsync<P>(PropertyInfo<P> propertyInfo, Task<P> factory) { throw new NotImplementedException(); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Tests.ApiHarness.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable /// public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int" />, <see cref="string" />, <see cref="Enum" />, <see cref="DateTime" />, /// <see cref="Uri" />, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}" />. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}" /> /// Tuples: <see cref="Tuple{T1}" />, <see cref="Tuple{T1,T2}" />, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}" /> or anything deriving from /// <see cref="IDictionary{TKey,TValue}" />. /// Collections: <see cref="IList{T}" />, <see cref="IEnumerable{T}" />, <see cref="ICollection{T}" />, /// <see cref="IList" />, <see cref="IEnumerable" />, <see cref="ICollection" /> or anything deriving from /// <see cref="ICollection{T}" /> or <see cref="IList" />. /// Queryables: <see cref="IQueryable" />, <see cref="IQueryable{T}" />. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private class SimpleTypeObjectGenerator { private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); private long _index = 0; public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } } } }
/************************************************************************************************* Required Notice: Copyright (C) EPPlus Software AB. This software is licensed under PolyForm Noncommercial License 1.0.0 and may only be used for noncommercial purposes https://polyformproject.org/licenses/noncommercial/1.0.0/ A commercial license to use this software can be purchased at https://epplussoftware.com *************************************************************************************************/ // Actually THIS code in this file isn't under PolyForm Noncommercial License, // it's under Bloom's usual one. But the notice above is apparently required // to use this package. We qualify as non-commercial as a charitable organization // (also as educational). using Bloom.ImageProcessing; using OfficeOpenXml; using OfficeOpenXml.Style; using SIL.IO; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Text.RegularExpressions; using Bloom.web; namespace Bloom.Spreadsheet { /// <summary> /// Class that manages writing and reading Excel files using EPPlus library. /// </summary> public class SpreadsheetIO { private const int standardLeadingColumnWidth = 15; private const int languageColumnWidth = 30; private const int defaultImageWidth = 150; //width of images in pixels. static SpreadsheetIO() { // The package requires us to do this as a way of acknowledging that we // accept the terms of the NonCommercial license. ExcelPackage.LicenseContext = LicenseContext.NonCommercial; } public static void WriteSpreadsheet(InternalSpreadsheet spreadsheet, string outputPath, bool retainMarkup, IWebSocketProgress progress = null) { using (var package = new ExcelPackage()) { var worksheet = package.Workbook.Worksheets.Add("BloomBook"); worksheet.DefaultColWidth = languageColumnWidth; for (int i = 1; i <= spreadsheet.StandardLeadingColumns.Length; i++) { worksheet.Column(i).Width = standardLeadingColumnWidth; } var imageSourceColumn = spreadsheet.GetColumnForTag(InternalSpreadsheet.ImageSourceColumnLabel); var imageThumbnailColumn = spreadsheet.GetColumnForTag(InternalSpreadsheet.ImageThumbnailColumnLabel); // Apparently the width is in some approximation of 'characters'. This empirically determined // conversion factor seems to do a pretty good job. worksheet.Column(imageThumbnailColumn + 1).Width = defaultImageWidth /6.88; int r = 0; foreach (var row in spreadsheet.AllRows()) { r++; for (var c = 0; c < row.Count; c++) { // Enhance: Excel complains about cells that contain pure numbers // but are created as strings. We could possibly tell it that cells // that contain simple numbers can be treated accordingly. // It might be helpful for some uses of the group-on-page-index // if Excel knew to treat them as numbers. var sourceCell = row.GetCell(c); var content = sourceCell.Content; // Parse xml for markdown formatting on language columns, // Display formatting in excel spreadsheet ExcelRange currentCell = worksheet.Cells[r, c + 1]; if (!string.IsNullOrEmpty(sourceCell.Comment)) { // Second arg is supposed to be the author. currentCell.AddComment(sourceCell.Comment, "Bloom"); } if (!retainMarkup && IsWysiwygFormattedColumn(row, c) && IsWysiwygFormattedRow(row)) { MarkedUpText markedUpText = MarkedUpText.ParseXml(content); if (markedUpText.HasFormatting) { currentCell.IsRichText = true; foreach (MarkedUpTextRun run in markedUpText.Runs) { if (!run.Text.Equals("")) { ExcelRichText text = currentCell.RichText.Add(run.Text); text.Bold = run.Bold; text.Italic = run.Italic; text.UnderLine = run.Underlined; if (run.Superscript) { text.VerticalAlign = ExcelVerticalAlignmentFont.Superscript; } } } } else { currentCell.Value = markedUpText.PlainText(); } } else { // Either the retainMarkup flag is set, or this is not book text. It could be header or leading column. // Generally, we just want to blast our cell content into the spreadsheet cell. // However, there are cases where we put an error message in an image thumbnail cell when processing the image path. // We don't want to overwrite these. An easy way to prevent it is to not overwrite any cell that already has content. // Since export is creating a new spreadsheet, cells we want to write will always be empty initially. if (currentCell.Value == null) { currentCell.Value = content; } } //Embed any images in the excel file if (c == imageSourceColumn) { var imageSrc = sourceCell.Content; // if this row has an image source value that is not a header if (imageSrc != "" && !row.IsHeader) { var sheetFolder = Path.GetDirectoryName(outputPath); var imagePath = Path.Combine(sheetFolder, imageSrc); //Images show up in the cell 1 row greater and 1 column greater than assigned //So this will put them in row r, column imageThumbnailColumn+1 like we want var rowHeight = embedImage(imagePath, r - 1, imageThumbnailColumn); worksheet.Row(r).Height = rowHeight * 72/96 + 3; //so the image is visible; height seems to be points } } } if (row is HeaderRow) { using (ExcelRange rng = GetRangeForRow(worksheet, r)) rng.Style.Font.Bold = true; } if (row.Hidden) { worksheet.Row(r).Hidden = true; SetBackgroundColorOfRow(worksheet, r, InternalSpreadsheet.HiddenColor); } else if (row.BackgroundColor != default(Color)) { SetBackgroundColorOfRow(worksheet, r, row.BackgroundColor); } } worksheet.Cells[1, 1, r, spreadsheet.ColumnCount].Style.WrapText = true; int embedImage(string imageSrcPath, int rowNum, int colNum) { int finalHeight = 30; // a reasonable default if we don't manage to embed an image. try { using (Image image = Image.FromFile(imageSrcPath)) { string imageName = Path.GetFileNameWithoutExtension(imageSrcPath); var origImageHeight = image.Size.Height; var origImageWidth = image.Size.Width; int finalWidth = defaultImageWidth; finalHeight = (int)(finalWidth * origImageHeight / origImageWidth); var size = new Size(finalWidth, finalHeight); using (Image thumbnail = ImageUtils.ResizeImageIfNecessary(size, image, false)) { var excelImage = worksheet.Drawings.AddPicture(imageName, thumbnail); excelImage.SetPosition(rowNum, 2, colNum, 2); } } } catch (Exception) { string errorText; if (!RobustFile.Exists(imageSrcPath)) { errorText = "Missing"; } else if (Path.GetExtension(imageSrcPath).ToLowerInvariant().Equals(".svg")) { errorText = "Can't display SVG"; } else { errorText = "Bad image file"; } progress?.MessageWithoutLocalizing(errorText + ": " + imageSrcPath); worksheet.Cells[r, imageThumbnailColumn + 1].Value = errorText; } return Math.Max(finalHeight, 30); } foreach (var iColumn in spreadsheet.HiddenColumns) { // This is pretty yucky... our internal spreadsheet is all 0-based, but the EPPlus library is all 1-based... var iColumn1Based = iColumn + 1; worksheet.Column(iColumn1Based).Hidden = true; SetBackgroundColorOfColumn(worksheet, iColumn1Based, InternalSpreadsheet.HiddenColor); } try { RobustFile.Delete(outputPath); var xlFile = new FileInfo(outputPath); package.SaveAs(xlFile); } catch (IOException ex) when ((ex.HResult & 0x0000FFFF) == 32)//ERROR_SHARING_VIOLATION { Console.WriteLine("Writing Spreadsheet failed. Do you have it open in another program?"); Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); progress?.Message("Spreadsheet.SpreadsheetLocked", "", "Bloom could not write to the spreadsheet because another program has it locked. Do you have it open in another program?", ProgressKind.Error); } catch (Exception ex) { progress?.Message("Spreadsheet.ExportFailed", "", "Export failed: " + ex.Message, ProgressKind.Error); } } } private static bool IsWysiwygFormattedRow(SpreadsheetRow row) { var key = row.MetadataKey; // At this point we're treating all content rows except the headers (and some labels) as wysiwyg return key != InternalSpreadsheet.RowTypeColumnLabel && key.StartsWith("[") && key.EndsWith("]"); } // A list of columns that, even if in Wysiwyg rows, should not receive Wysiwyg processing. // They are columns that do not contain markup when exported and should not receive paragraph // wrappers when imported. This is the data that supports the implementation of IsWysiwygFormattedColumn. // We use tags like this rather than comparing the column index to the count of leading columns // because, on import, some of the standard columns may be missing, // or there may be extra columns added as comments. The basic idea is that all the language // data columns should get the Wysiwyg processing, which prevents HTML markup appearing in // exports, and prevents unexpected HTML getting imported and processed. // The asterisk 'language' is special because it is used for data-div stuff like [styleNumberSequence] // for which we don't want import to wrap paragraph tags around the content. // Review: is it better to try to come up with an inventory of rows like [styleNumberSequence] // where the * column should not be wysiwyg processed? We had a hard time previously when attempting // to come up with a list of rows that SHOULD be. private static HashSet<string> nonWysiwygColumns = new HashSet<string>(new[] { "[*]", InternalSpreadsheet.RowTypeColumnLabel, InternalSpreadsheet.ImageSourceColumnLabel, InternalSpreadsheet.ImageThumbnailColumnLabel, InternalSpreadsheet.PageNumberColumnLabel }); private static bool IsWysiwygFormattedColumn(SpreadsheetRow row, int index) { var key = row.Spreadsheet.Header.GetRow(0).GetCell(index).Content; return !nonWysiwygColumns.Contains(key); } public static void ReadSpreadsheet(InternalSpreadsheet spreadsheet, string path) { var info = new FileInfo(path); using (var package = new ExcelPackage(info)) { var worksheet = package.Workbook.Worksheets[0]; var rowCount = worksheet.Dimension.Rows; var colCount = worksheet.Dimension.Columns; // Enhance: eventually we should detect any rows that are not ContentRows, // and either drop them or make plain SpreadsheetRows. int numHeaderRows = spreadsheet.Header.RowCount; for (int i = 0; i < numHeaderRows; ++i) { ReadRow(worksheet, i, colCount, spreadsheet.Header.GetRow(i)); } for (var r = numHeaderRows; r < rowCount; r++) { var row = new ContentRow(spreadsheet); ReadRow(worksheet, r, colCount, row); } } } private static void ReadRow(ExcelWorksheet worksheet, int rowIndex, int colCount, SpreadsheetRow row) { for (var c = 0; c < colCount; c++) { ExcelRange currentCell = worksheet.Cells[rowIndex + 1, c + 1]; // The first row is special because it contains the headers needed by IsWysiwygFormattedColumn if (rowIndex > 0 && IsWysiwygFormattedColumn(row, c) && IsWysiwygFormattedRow(row)) { row.AddCell(BuildXmlString(currentCell)); } else { var cellContent = worksheet.Cells[rowIndex + 1, c + 1].Value ?? ""; row.AddCell(ReplaceExcelEscapedCharsAndEscapeXmlOnes(cellContent.ToString())); } } } public static string ReplaceExcelEscapedCharsAndEscapeXmlOnes(string escapedString) { string plainString = escapedString; string pattern = "_x([0-9A-F]{4})_"; Regex rgx = new Regex(pattern); Match match = rgx.Match(plainString); while (match.Success) { string x = match.Groups[1].Value; int value = Convert.ToInt32(x, 16); char charValue = (char)value; plainString = plainString.Replace(match.Value, charValue.ToString()); match = rgx.Match(plainString); } // Note: ampersand must be handled first! Otherwise it will modify the output of the other replaces. return plainString.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;"); } public static string BuildXmlString(ExcelRange cell) { if (cell.Value == null) { return ""; } string rawText = cell.Value.ToString(); if (string.IsNullOrEmpty(rawText)) return ""; // otherwise we'd wrap a paragraph around it, making it harder to detect empty cells. StringBuilder markedupStringBuilder = new StringBuilder(); var whitespaceSplitters = new string[] { "\n", "\r\n" }; if (cell.IsRichText) { var content = cell.RichText; var cellLevelFormatting = cell.Style.Font; foreach (var run in content) { if (run.Text.Length > 0) { run.Text = ReplaceExcelEscapedCharsAndEscapeXmlOnes(run.Text); } var splits = run.Text.Split(whitespaceSplitters, StringSplitOptions.None); string pending = ""; foreach (var split in splits) { markedupStringBuilder.Append(pending); AddRunToXmlString(run, cellLevelFormatting, split, markedupStringBuilder); // Not something that is or might be \r\n. See comment in MarkedUpText.ParseXml() pending = "\n"; } } } else { markedupStringBuilder.Append(ReplaceExcelEscapedCharsAndEscapeXmlOnes(rawText)); } StringBuilder paragraphedStringBuilder = new StringBuilder(); var markedUpString = markedupStringBuilder.ToString(); string[] paragraphs = markedUpString.Split(whitespaceSplitters, StringSplitOptions.None); if (paragraphs.Length >= 1) { paragraphedStringBuilder.Append("<p>"); paragraphedStringBuilder.Append(paragraphs[0]); } for (int i=1; i<paragraphs.Length; i++) { // The \xfeff is not inserted by our export. Rather, it is inserted by the code in // BloomField.InsertLineBreak which handles shift-enter in Bloom. It is therefore // normal that a span with class bloom-linebreak will be exported with this invisible // (zero-width no-break space) character following it. We use that here to determine // that the Excel line-break should be imported as a bloom-linebreak rather than as // a transition between <p> elements. if (paragraphs[i].Length >= 1 && paragraphs[i][0] == '\xfeff') { paragraphedStringBuilder.Append(@"<span class=""bloom-linebreak""></span>"); } else { paragraphedStringBuilder.Append("</p><p>"); } paragraphedStringBuilder.Append(paragraphs[i]); } if (paragraphs.Length >= 1) { paragraphedStringBuilder.Append("</p>"); } return paragraphedStringBuilder.ToString(); } // Excel formatting can be at the entire cell level (e.g. the entire cell is marked italic) // or at the text level (e.g. some words in the cell are marked italic). // We detect and import both types, but if the user mixes levels for the same formatting type // e.g.selects the entire cell, bolds it, then selected some text within the cell and unbolds it, // we may get weird results, so we should tell users to use text-level formatting only /// <param name="formattingText">Has any text-level formatting we want this run to have. Text content does not matter.</param> /// <param name="cellFormatting">Has any cell-level formatting we want this run to have.</param> /// <param name="text">The text content of this run</param> /// <param name="stringBuilder">The string builder to which we are adding the xmlstring of this run private static void AddRunToXmlString(ExcelRichText formattingText, ExcelFont cellFormatting, string text, StringBuilder stringBuilder) { if (text.Length==0) { return; } List<string> endTags = new List<string>(); if (formattingText.Bold || cellFormatting.Bold) { addTags("strong", endTags); } if (formattingText.Italic || cellFormatting.Italic) { addTags("em", endTags); } if (formattingText.UnderLine || cellFormatting.UnderLine) { addTags("u", endTags); } if (formattingText.VerticalAlign == ExcelVerticalAlignmentFont.Superscript || cellFormatting.VerticalAlign == ExcelVerticalAlignmentFont.Superscript) { addTags("sup", endTags); } stringBuilder.Append(text); endTags.Reverse(); foreach (var endTag in endTags) { stringBuilder.Append(endTag); } void addTags(string tagName, List<string> endTag) { stringBuilder.Append("<" + tagName + ">"); endTag.Add("</" + tagName + ">"); } } private static void SetBackgroundColorOfRow(ExcelWorksheet worksheet, int iRow, Color color) { using (ExcelRange range = GetRangeForRow(worksheet, iRow)) SetBackgroundColorOfRange(range, color); } private static void SetBackgroundColorOfColumn(ExcelWorksheet worksheet, int iColumn, Color color) { using (ExcelRange range = GetRangeForColumn(worksheet, iColumn)) SetBackgroundColorOfRange(range, color); } private static void SetBackgroundColorOfRange(ExcelRange range, Color color) { range.Style.Fill.PatternType = ExcelFillStyle.Solid; range.Style.Fill.BackgroundColor.SetColor(color); } private static ExcelRange GetRangeForRow(ExcelWorksheet worksheet, int iRow) { return worksheet.Cells[iRow, 1, iRow, worksheet.Dimension.End.Column]; } private static ExcelRange GetRangeForColumn(ExcelWorksheet worksheet, int iColumn) { return worksheet.Cells[1, iColumn, worksheet.Dimension.End.Row, iColumn]; } } }
// --------------------------------------------------------------------------- // <copyright file="TimeoutMessageBox.cs" company="Tethys"> // Copyright (C) 1998-2021 T. Graf // </copyright> // // SPDX-License-Identifier: Apache-2.0 // // Licensed under the Apache License, Version 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. // --------------------------------------------------------------------------- // ReSharper disable once CheckNamespace namespace Tethys.Forms { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; using Tethys.Win32; /// <summary> /// TimeoutMessageBox implements a message box that is closed automatically /// after a given timeout. /// </summary> /// <remarks> /// How does it work? /// Just before calling MessageBox.Show(...), SetWindowsHookEx(WH_CALLWNDPROCRET,) /// is called. The hook procedure looks for a WM_INITDIALOG on a window with text equal /// to the message box caption. A windows timer is started on that window with /// the appropriate timeout. When the timeout fires EndDialog is called with the /// result set to the dialog default button ID. You can get that ID by sending /// a dialog box a DM_GETDEFID message. Pretty simple. /// <br/> /// This implementation is based on the work of RodgerB that has been /// published on <a href="www.codeproject.com">Code Project</a>. /// </remarks> public static class TimeoutMessageBox { #region SHOW() FUNCTIONS /// <summary> /// Displays a message box with specified text. /// </summary> /// <param name="text">The text to display in the message box.</param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show(string text, int timeout) { Init(string.Empty, timeout); return MessageBox.Show(text); } // Show() /// <summary> /// Displays a message box with specified text and caption. /// </summary> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the message box. </param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show(string text, string caption, int timeout) { Init(caption, timeout); return MessageBox.Show(text, caption); } // Show() /// <summary> /// Displays a message box with specified text, caption, and buttons. /// </summary> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies which buttons to display in the message box.</param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, int timeout) { Init(caption, timeout); return MessageBox.Show(text, caption, buttons); } // Show() /// <summary> /// Displays a message box with specified text, caption, buttons, and icon. /// </summary> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies which icon to display in the message box. </param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show( string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, int timeout) { Init(caption, timeout); return MessageBox.Show(text, caption, buttons, icon); } // Show() /// <summary> /// Displays a message box with the specified text, caption, buttons, /// icon, and default button. /// </summary> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defButton">One for the MessageBoxDefaultButton values which specifies which is the default button for the message box.</param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show( string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, int timeout) { Init(caption, timeout); return MessageBox.Show(text, caption, buttons, icon, defButton); } // Show() /// <summary> /// Displays a message box with the specified text, caption, buttons, /// icon, and default button. /// </summary> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defButton">One for the MessageBoxDefaultButton values which specifies which is the default button for the message box.</param> /// <param name="options">Message box Options.</param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show( string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options, int timeout) { Init(caption, timeout); return MessageBox.Show(text, caption, buttons, icon, defButton, options); } // Show() /// <summary> /// Displays a message box with specified text. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box.</param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, int timeout) { Init(string.Empty, timeout); return MessageBox.Show(owner, text); } // Show() /// <summary> /// Displays a message box with specified text and caption. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the message box. </param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show(IWin32Window owner, string text, string caption, int timeout) { Init(caption, timeout); return MessageBox.Show(owner, text, caption); } // Show() /// <summary> /// Displays a message box with specified text, caption, and buttons. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies which buttons to display in the message box.</param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show( IWin32Window owner, string text, string caption, MessageBoxButtons buttons, int timeout) { Init(caption, timeout); return MessageBox.Show(owner, text, caption, buttons); } // Show() /// <summary> /// Displays a message box with specified text, caption, buttons, and icon. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies which icon to display in the message box. </param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show( IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, int timeout) { Init(caption, timeout); return MessageBox.Show(owner, text, caption, buttons, icon); } // Show() /// <summary> /// Displays a message box with the specified text, caption, buttons, /// icon, and default button. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defButton">One for the MessageBoxDefaultButton values which specifies which is the default button for the message box.</param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show( IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, int timeout) { Init(caption, timeout); return MessageBox.Show(owner, text, caption, buttons, icon, defButton); } // Show() /// <summary> /// Displays a message box with the specified text, caption, buttons, /// icon, and default button. /// </summary> /// <param name="owner">Window parent (owner).</param> /// <param name="text">The text to display in the message box. </param> /// <param name="caption">The text to display in the title bar of the message box. </param> /// <param name="buttons">One of the MessageBoxButtons that specifies which buttons to display in the message box.</param> /// <param name="icon">One of the MessageBoxIcon values that specifies which icon to display in the message box.</param> /// <param name="defButton">One for the MessageBoxDefaultButton values which specifies which is the default button for the message box.</param> /// <param name="options">Message box Options.</param> /// <param name="timeout">timeout value in milliseconds.</param> /// <returns>One of the DialogResult values.</returns> public static DialogResult Show( IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defButton, MessageBoxOptions options, int timeout) { Init(caption, timeout); return MessageBox.Show(owner, text, caption, buttons, icon, defButton, options); } // Show() #endregion // SHOW() FUNCTIONS //// -------------------------------------------------------------------- #region PRIVATE PROPERTIES /// <summary> /// The user message id. /// </summary> // ReSharper disable InconsistentNaming [SuppressMessage( "StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Reviewed. Suppression is OK here.")] private const int DM_GETDEFID = (int)Msg.WM_USER + 0; // ReSharper restore InconsistentNaming /// <summary> /// Timer Id. /// </summary> private const int TimerId = 42; /// <summary> /// Hook 1. /// </summary> private static readonly Win32Api.HookProc HookProc = MessageBoxHookProc; /// <summary> /// Hook 2. /// </summary> private static readonly Win32Api.TimerProc HookTimer = MessageBoxTimerProc; /// <summary> /// Hook timeout. /// </summary> private static uint hookTimeout; /// <summary> /// Hook caption. /// </summary> private static string hookCaption; /// <summary> /// Hook handle. /// </summary> private static IntPtr handleHook = IntPtr.Zero; #endregion // PRIVATE PROPERTIES //// -------------------------------------------------------------------- #region CONSTRUCTION /// <summary> /// Initialize hook management. /// </summary> /// <param name="caption">The caption.</param> /// <param name="timeout">The timeout.</param> /// <exception cref="System.NotSupportedException">multiple calls are not supported.</exception> private static void Init(string caption, int timeout) { if (handleHook != IntPtr.Zero) { // prohibit reentrancy throw new NotSupportedException("multiple calls are not supported"); } // if // create hook hookTimeout = (uint)timeout; hookCaption = caption ?? string.Empty; handleHook = Win32Api.SetWindowsHookEx( (int)WindowsHookCodes.WH_CALLWNDPROCRET, HookProc, IntPtr.Zero, Thread.CurrentThread.ManagedThreadId); } // Init() #endregion // CONSTRUCTION //// -------------------------------------------------------------------- #region HOOK & TIMER MANAGEMENT /// <summary> /// This is the function called by the Windows hook management. /// We assume, that when an WM_INITDIALOG message is sent and /// the window text is the same like the one of our window that /// the window to hook call comes from is indeed our window. /// We start the timer and unhook ourselves. /// </summary> /// <param name="nCode">The n code.</param> /// <param name="wParam">The w parameter.</param> /// <param name="lParam">The l parameter.</param> /// <returns>A handle.</returns> private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode < 0) { return Win32Api.CallNextHookEx(handleHook, nCode, wParam, lParam); } // if var msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT)); var hook = handleHook; if ((hookCaption != null) && (msg.message == (uint)Msg.WM_INITDIALOG)) { // get window text var length = Win32Api.GetWindowTextLength(msg.hwnd); var text = new StringBuilder(length + 1); var result = Win32Api.GetWindowText(msg.hwnd, text, text.Capacity); Debug.Assert(result > 0, "GetWindowText reports error!"); // check whether this is the text we expect if (hookCaption == text.ToString()) { hookCaption = null; // set timer Win32Api.SetTimer(msg.hwnd, (UIntPtr)TimerId, hookTimeout, HookTimer); // unhook Win32Api.UnhookWindowsHookEx(handleHook); handleHook = IntPtr.Zero; } // if } // if // default: call next hook return Win32Api.CallNextHookEx(hook, nCode, wParam, lParam); } // MessageBoxHookProc() /// <summary> /// This function is called when the timeout is reached. /// Then we close the dialog. /// </summary> /// <param name="hWnd">The h WND.</param> /// <param name="uMsg">The u MSG.</param> /// <param name="idEvent">The n ID event.</param> /// <param name="time">The dw time.</param> private static void MessageBoxTimerProc(IntPtr hWnd, uint uMsg, UIntPtr idEvent, uint time) { if (idEvent == (UIntPtr)TimerId) { // get dialog default button ID short dw = (short)Win32Api.SendMessage(hWnd, DM_GETDEFID, 0, 0); // end dialog with default button ID var result = Win32Api.EndDialog(hWnd, (IntPtr)dw); Debug.Assert(result != 0, "EndDialog reports error!"); } // if } // MessageBoxTimerProc() #endregion // HOOK & TIMER MANAGEMENT } // TimeoutMessageBox } // Tethys.Forms // ========================================= // Tethys.Forms: end of TimeoutMessageBox.cs // =========================================
// [Twin] Copyright eBay Inc., Twin authors, and other contributors. // This file is provided to you under the terms of the Apache License, Version 2.0. // See LICENSE.txt and NOTICE.txt for license and copyright information. using System; using System.Collections.Generic; using System.Text; using System.IO; using Twin.Generic; namespace Twin.Generic { class JSON { public static string quote(string text) { StringBuilder result = new StringBuilder(); result.Append('"'); foreach (char c in text) { if (c < 32 || c >= 128) result.AppendFormat("\\u{0:x4}", (int)c); else if (c == '\\') result.Append(@"\\"); else if (c == '"') result.Append(@"\"""); else result.Append(c); } result.Append('"'); return result.ToString(); } public static void Write(object p, TextWriter writer) { Write(p, writer, -1, 0); } public static void Write(object p, TextWriter writer, int indent) { Write(p, writer, 0, indent); } private static void Indent(int count, TextWriter writer) { for (int i = 0; i < count; i++) writer.Write(' '); } private static void Write(object p, TextWriter writer, int indent, int indentIncrement) { if (p == null) { writer.Write("null"); } else if (p is IJSONable) { Write(((IJSONable)p).JSONForm, writer, indent, indentIncrement); } else if (p is Byte || p is SByte || p is Int16 || p is UInt16 || p is Int32 || p is UInt32 || p is Int64 || p is UInt64) { writer.Write(p.ToString()); } else if (p is Single || p is Double || p is Decimal) { writer.Write(p.ToString()); } else if (p is Boolean) { writer.Write((Boolean)p ? "true" : "false"); } else if (p is String) { writer.Write(quote((String)p)); } else if (p is System.Collections.IDictionary) { bool first = true; writer.Write('{'); System.Collections.IDictionary dict = (System.Collections.IDictionary)p; if (dict.Count > 0) { if (indent >= 0) writer.Write('\n'); foreach (System.Collections.DictionaryEntry kv in dict) { if (!first) { writer.Write(','); if (indent >= 0) writer.Write("\n"); } first = false; Indent(indent + indentIncrement, writer); Write(kv.Key.ToString(), writer, indent + indentIncrement, indentIncrement); writer.Write(':'); if (indent >= 0) writer.Write(' '); Write(kv.Value, writer, indent + indentIncrement, indentIncrement); } if (indent >= 0) writer.Write("\n"); Indent(indent, writer); } writer.Write('}'); } else if (p is System.Collections.IEnumerable) { bool first = true; writer.Write('['); foreach (object o in (System.Collections.IEnumerable)p) { if (!first) writer.Write(','); if (indent >= 0) writer.Write('\n'); first = false; Indent(indent + indentIncrement, writer); Write(o, writer, indent + indentIncrement, indentIncrement); } if (!first) { if (indent >= 0) writer.Write('\n'); Indent(indent, writer); } writer.Write(']'); } else { throw new ArgumentException("Cannot serialise " + p + " of type " + p.GetType()); } } private static void SkipSpace(TextReader reader) { while(true) { int c = reader.Peek(); if(c < 0 || !Char.IsWhiteSpace((char)c)) return; reader.Read(); } } public static object Read(TextReader reader) { SkipSpace(reader); int c = reader.Read(); if (c < 0) throw new FormatException("Unexpected EOF"); if (c == '{') { Dictionary<string, object> dict = new Dictionary<string, object>(); while (true) { SkipSpace(reader); int d = reader.Peek(); if (d == '"') { string key = (string)Read(reader); SkipSpace(reader); int e = reader.Read(); if (e == ':') { object value = Read(reader); dict[key] = value; SkipSpace(reader); int f = reader.Read(); if(f == '}') break; else if(f == ',') continue; else throw new FormatException("Expected } or , after key-value pair in object but got "+(char)f); } else { throw new FormatException("Expected : after key " + key+" but got "+(char)e); } } else if (d == '}' && dict.Count == 0) { reader.Read(); break; } else { throw new FormatException("Expected \" to start an object but got "+(char)d); } } return dict; } if (c == '[') { List<object> list = new List<object>(); while (true) { SkipSpace(reader); int d = reader.Peek(); if (d == ']' && list.Count == 0) { reader.Read(); break; } else { list.Add(Read(reader)); SkipSpace(reader); int e = reader.Read(); if (e == ']') break; else if (e == ',') continue; else throw new FormatException("Expected ] or , after array entry but got " + (char)e); } } return list; } if (c == 'n') { int i = reader.Read(); int j = reader.Read(); int k = reader.Read(); if (i == 'u' && j == 'l' && k == 'l') return null; throw new FormatException("Expected 'ull' after n but got " + (char)i + " " + (char)j + " " + (char)k); } if (c == 't') { int i = reader.Read(); int j = reader.Read(); int k = reader.Read(); if (i == 'r' && j == 'u' && k == 'e') return true; throw new FormatException("Expected 'rue' after t but got " + (char)i + " " + (char)j + " " + (char)k); } if (c == 'f') { int i = reader.Read(); int j = reader.Read(); int k = reader.Read(); int m = reader.Read(); if (i == 'a' && j == 'l' && k == 's' && m=='e') return false; throw new FormatException("Expected 'alse' after f but got " + (char)i + " " + (char)j + " " + (char)k + " " + (char)m); } if (c == '"') { StringBuilder text = new StringBuilder(); while (true) { int next = reader.Read(); if (next < 0) throw new FormatException("Runaway string meets EOF"); if (next == '"') return text.ToString(); if (next == '\\') { int escape = reader.Read(); switch (escape) { case -1: throw new FormatException("Escaped EOF in string"); case '\"': case '\\': case '/': text.Append((char)escape); break; case 'b': text.Append('\b'); break; case 'f': text.Append('\f'); break; case 'n': text.Append('\n'); break; case 'r': text.Append('\r'); break; case 't': text.Append('\t'); break; case 'u': int hex1 = reader.Read(); int hex2 = reader.Read(); int hex3 = reader.Read(); int hex4 = reader.Read(); if(hex4 < 0) throw new FormatException("Unicode escape meets EOF"); text.Append((char)Convert.ToInt32("" + (char)hex1 + (char)hex2 + (char)hex3 + (char)hex4, 16)); break; default: throw new FormatException("Unknown string escape "+(char)escape); } } else { if(next < 32) throw new FormatException("Control character included inline in string: "+next); text.Append((char)next); } } } if(Char.IsDigit((char)c) || c=='-') { int multiplier = (c=='-') ? -1 : 1; UInt64 integer = (c == '-') ? 0 : (ulong)(c - '0'); while(true) { int d = reader.Peek(); if(d >= 0 && Char.IsDigit((char)d)) { reader.Read(); integer *= 10; integer += (ulong)(d - '0'); continue; } break; } int decimalDigits = 0; UInt64 decimalData = 0; if(reader.Peek() == '.') { reader.Read(); while(true) { int d = reader.Peek(); if (d >= 0 && Char.IsDigit((char)d)) { reader.Read(); decimalData *= 10; decimalData += (ulong)(d - '0'); decimalDigits++; continue; } break; } } int exponentMultiplier = 1; UInt64 exponentData = 0; if(reader.Peek() == 'e' || reader.Peek() == 'E') { reader.Read(); int sign = reader.Peek(); if(sign == '+') reader.Read(); if(sign == '-') { reader.Read(); exponentMultiplier = -1; } while(true) { int d = reader.Peek(); if (d >= 0 && char.IsDigit((char)d)) { reader.Read(); exponentData *= 10; exponentData += (ulong)(d - '0'); continue; } break; } } if(exponentData==0 && decimalDigits ==0 && integer <= (multiplier > 0 ? (ulong)int.MaxValue : (ulong)(- (long)int.MinValue))) { return multiplier * (int)integer; } double value = (double)multiplier * (double)integer; if(decimalDigits != 0) value += decimalData / Math.Pow(10, decimalDigits); if(exponentData != 0) value *= Math.Pow(10, (double)exponentMultiplier * (double)exponentData); return value; } throw new FormatException("Unknown JSON type starting with "+(char)c); } public static string ToString(object o) { using (StringWriter writer = new StringWriter()) { Write(o, writer); return writer.ToString(); } } public static string ToString(object o, int indent) { using (StringWriter writer = new StringWriter()) { Write(o, writer, indent); return writer.ToString(); } } public static object ToObject(string s) { if(s == null) return null; using (TextReader reader = new StringReader(s)) { return Read(reader); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using DotVVM.Framework.Binding; using DotVVM.Framework.Controls; using DotVVM.Framework.Utils; using FastExpressionCompiler; using Microsoft.Extensions.DependencyInjection; namespace DotVVM.Framework.Compilation.ViewCompiler { public class DefaultViewCompilerCodeEmitter { private static Type[] emptyTypeArguments = new Type[] { }; private int CurrentControlIndex; public const string ControlBuilderFactoryParameterName = "controlBuilderFactory"; public const string ServiceProviderParameterName = "services"; public const string BuildTemplateFunctionName = "BuildTemplate"; private Dictionary<GroupedDotvvmProperty, string> cachedGroupedDotvvmProperties = new Dictionary<GroupedDotvvmProperty, string>(); private ConcurrentDictionary<(Type obj, string argTypes), string> injectionFactoryCache = new ConcurrentDictionary<(Type obj, string argTypes), string>(); private readonly Stack<BlockInfo> blockStack = new(); public Type? ResultControlType { get; set; } public ParameterExpression EmitCreateVariable(Expression expression) { var name = ("c" + CurrentControlIndex).DotvvmInternString(); CurrentControlIndex++; var variable = Expression.Variable(expression.Type, name); blockStack.Peek().Variables.Add(name, variable); blockStack.Peek().Expressions.Add(Expression.Assign(variable, expression)); return variable; } public Expression EmitValue(object? value) => Expression.Constant(value); /// <summary> /// Emits the create object expression. /// </summary> public ParameterExpression EmitCreateObject(Type type, object?[]? constructorArguments = null) { constructorArguments ??= new object[0]; var arguments = constructorArguments.Select(EmitValue); var argumentTypes = arguments.Select(a => a.Type).ToArray(); var constructor = type.GetConstructor(argumentTypes).NotNull($"Could not find constructor of {type} with arguments ({string.Join(", ", argumentTypes.Select(a => a.Name))})"); return EmitCreateObject(constructor, arguments); } /// <summary> /// Emits the create object expression. /// </summary> public ParameterExpression EmitCreateObject(ConstructorInfo ctor, object?[]? constructorArguments = null) { constructorArguments ??= new object[0]; var parameters = ctor.GetParameters(); if (parameters.Length != constructorArguments.Length) throw new ArgumentException($"Constructor {ctor.DeclaringType?.Name}.{ctor.Name} has {parameters.Length} parameters, but {constructorArguments.Length} arguments were provided."); return EmitCreateObject(ctor, constructorArguments.Zip(parameters, (a, p) => Expression.Constant(a, p.ParameterType))); } public ParameterExpression EmitCustomInjectionFactoryInvocation(Type factoryType, Type controlType) { //[controlType] c = ([controlType])(([factoryType])services.GetService(factoryType)(services,controlType)) var servicesParameter = GetParameterOrVariable(ServiceProviderParameterName); var getServiceCall = Expression.Call(servicesParameter, nameof(IServiceProvider.GetService), emptyTypeArguments, Expression.Constant(factoryType)); var factoryInstance = Expression.Convert(getServiceCall, factoryType); var factoryInvoke = Expression.Invoke(factoryInstance, servicesParameter, Expression.Constant(controlType)); return EmitCreateVariable(Expression.Convert(factoryInvoke, controlType)); } public ParameterExpression EmitInjectionFactoryInvocation(Type type, object[] arguments) { //[type] v = ([type])factory(services, object[] { ...arguments.Expression } ) var objectFactory = ActivatorUtilities.CreateFactory(type, arguments.Select(a => a.GetType()).ToArray()); var factoryInvoke = Expression.Invoke(Expression.Constant(objectFactory), GetParameterOrVariable(ServiceProviderParameterName), Expression.Constant(arguments, typeof(object[]))); return EmitCreateVariable(Expression.Convert(factoryInvoke, type)); } private ParameterExpression EmitCreateObject(ConstructorInfo ctor, IEnumerable<Expression> arguments) { return EmitCreateVariable(EmitCreateObjectExpression(ctor, arguments)); } private Expression EmitCreateObjectExpression(ConstructorInfo ctor, IEnumerable<Expression> arguments) { return Expression.New(ctor, arguments.ToArray()); } public static Expression EmitCreateArray(Type elementType, IEnumerable<Expression> values) { //new [elementType] [] = { ([elementType])v1, ([elementType])v2, ([elementType])v3, ... } //note: [elementType] is name of the type provided in 'elementType' parameter. var convertedValues = values.Select(v => Expression.Convert(v, elementType)); return Expression.NewArrayInit(elementType, convertedValues); } public ParameterExpression EmitInvokeControlBuilder(Type controlType, string virtualPath) { var builderValueExpression = GetControlBuilderCreatingExpression(virtualPath); return EmitInvokeBuildControl(controlType, builderValueExpression); } private ParameterExpression EmitInvokeBuildControl(Type controlType, Expression builderValueExpression) { //var [untypedName] = [builderName].BuildControl(controlBuilderFactory, services) var controlBuilderFactoryParameter = GetParameterOrVariable(ControlBuilderFactoryParameterName); var servicesParameter = GetParameterOrVariable(ServiceProviderParameterName); var buildControlCall = Expression.Call(builderValueExpression, nameof(IControlBuilder.BuildControl), emptyTypeArguments, controlBuilderFactoryParameter, servicesParameter); return EmitCreateVariable(Expression.Convert(buildControlCall, controlType)); } private Expression GetControlBuilderCreatingExpression(string virtualPath) { //var [builderName] = controlBuilderFactory.GetControlBuilder(virtualPath).Item2.Value var controlBuilderFactoryParameter = GetParameterOrVariable(ControlBuilderFactoryParameterName); var getBuilderCall = Expression.Call(controlBuilderFactoryParameter, nameof(IControlBuilderFactory.GetControlBuilder), emptyTypeArguments, EmitValue(virtualPath)); var builderValueExpression = Expression.PropertyOrField( Expression.PropertyOrField(getBuilderCall, "Item2"), "Value"); return builderValueExpression; } public void EmitSetProperty(string controlName, string propertyName, Expression valueExpression) { //[controlName].[propertyName] = [value] var controlParameter = GetParameterOrVariable(controlName); var assigment = Expression.Assign(Expression.PropertyOrField(controlParameter, propertyName), valueExpression); blockStack.Peek().Expressions.Add(assigment); } private readonly Dictionary<string, List<(DotvvmProperty prop, Expression value)>> controlProperties = new Dictionary<string, List<(DotvvmProperty, Expression)>>(); public void EmitSetDotvvmProperty(string controlName, DotvvmProperty property, object? value) => EmitSetDotvvmProperty(controlName, property, EmitValue(value)); public void EmitSetDotvvmProperty(string controlName, DotvvmProperty property, Expression value) { if (!controlProperties.TryGetValue(controlName, out var propertyList)) throw new Exception($"Can not set property, control {controlName} is not registered"); propertyList.Add((property, value)); } /// Instructs the emitter that this object can receive DotvvmProperties /// Note that the properties have to be committed using <see cref="CommitDotvvmProperties(string)" /> public void RegisterDotvvmProperties(string controlName) => controlProperties.Add(controlName, new List<(DotvvmProperty prop, Expression value)>()); public void CommitDotvvmProperties(string name) { var properties = controlProperties[name]; controlProperties.Remove(name); if (properties.Count == 0) return; properties.Sort((a, b) => string.Compare(a.prop.FullName, b.prop.FullName, StringComparison.Ordinal)); var (hashSeed, keys, values) = PropertyImmutableHashtable.CreateTableWithValues(properties.Select(p => p.prop).ToArray(), properties.Select(p => p.value).ToArray()); Expression valueExpr; if (TryCreateArrayOfConstants(values, out var invertedValues)) { valueExpr = EmitValue(invertedValues); } else { valueExpr = EmitCreateArray( typeof(object), values.Select(v => v ?? EmitValue(null)) ); } var keyExpr = EmitValue(keys); // control.MagicSetValue(keys, values, hashSeed) var controlParameter = GetParameterOrVariable(name); var magicSetValueCall = Expression.Call(controlParameter, nameof(DotvvmBindableObject.MagicSetValue), emptyTypeArguments, keyExpr, valueExpr, EmitValue(hashSeed)); blockStack.Peek().Expressions.Add(magicSetValueCall); } private bool TryCreateArrayOfConstants(Expression?[] values, out object?[] invertedValues) { invertedValues = new object?[values.Length]; for (int i = 0; i < values.Length; i++) { if (values[i] == null) { continue; } if (values[i] is ConstantExpression constant) { invertedValues[i] = constant.Value; } else { return false; } } return true; } /// <summary> /// Emits the code that adds the specified value as a child item in the collection. /// </summary> public void EmitAddCollectionItem(string collectionName, string variableName) { var collectionParameter = GetParameterOrVariable(collectionName); var variablePartameter = GetParameterOrVariable(variableName); //[collectionParameter].Add([variablePartameter]) var collectionAddCall = Expression.Call(collectionParameter, "Add", emptyTypeArguments, variablePartameter); blockStack.Peek().Expressions.Add(collectionAddCall); } /// <summary> /// Emits the code that adds the specified value as a child of the control /// </summary> public void EmitAddChildControl(string controlName, string variableName) { var controlParameter = GetParameterOrVariable(controlName); var collectionExpression = Expression.PropertyOrField(controlParameter, "Children"); var variablePartameter = GetParameterOrVariable(variableName); //[collectionExpression].Children.AddUnchecked([variableParameter]) var collectionAddCall = Expression.Call(collectionExpression, "AddUnchecked", emptyTypeArguments, variablePartameter); blockStack.Peek().Expressions.Add(collectionAddCall); } /// <summary> /// Emits the add HTML attribute. /// </summary> public void EmitAddToDictionary(string controlName, string propertyName, string key, Expression valueExpression) { //[controlName].[propertyName][key]= value; var controlParameter = GetParameterOrVariable(controlName); var dictionaryKeyExpression = Expression.Property( Expression.PropertyOrField(controlParameter, propertyName), "Item", EmitValue(key)); var assigment = Expression.Assign(dictionaryKeyExpression, valueExpression); blockStack.Peek().Expressions.Add(assigment); } /// <summary> /// Emits the add directive. /// </summary> public void EmitAddDirective(string controlName, string name, string value) { EmitAddToDictionary(controlName, "Directives", name, EmitValue(value)); } public ParameterExpression EmitEnsureCollectionInitialized(string parentName, DotvvmProperty property) { //if([parentName].GetValue(property) == null) //{ // [parentName].SetValue(property, new [property.PropertyType]()); //} var parentParameter = GetParameterOrVariable(parentName); var getPropertyValue = Expression.Call( parentParameter, "GetValue", emptyTypeArguments, /*property:*/ EmitValue(property), /*inherit:*/ EmitValue(true /*default*/ )); var ifCondition = Expression.Equal(getPropertyValue, Expression.Constant(null)); var statement = Expression.Call( parentParameter, "SetValue", emptyTypeArguments, /*property*/ EmitValue(property), /*value*/ EmitCreateObject(property.PropertyType)); var ifStatement = Expression.IfThen(ifCondition, statement); blockStack.Peek().Expressions.Add(ifStatement); //var c = ([property.PropertyType])[parentName].GetValue(property); return EmitCreateVariable(Expression.Convert(getPropertyValue, property.PropertyType)); } /// <summary> /// Emits the return clause. /// </summary> public void EmitReturnClause(string variableName) { var parameter = GetParameterOrVariable(variableName); blockStack.Peek().Expressions.Add(parameter); } public ParameterExpression GetParameterOrVariable(string identifierName) => GetCurrentBlock().GetParameterOrVariable(identifierName); private BlockInfo GetCurrentBlock() => blockStack.Peek(); public ParameterExpression EmitParameter(string name, Type type) => Expression.Parameter(type, name); public ParameterExpression[] EmitControlBuilderParameters() => new[] { EmitParameter(ControlBuilderFactoryParameterName, typeof(IControlBuilderFactory)), EmitParameter(ServiceProviderParameterName, typeof(IServiceProvider)) }; /// <summary> /// Pushes the new method. /// </summary> public void PushNewMethod(params ParameterExpression[] parameters) { blockStack.Push(new BlockInfo(parameters)); } /// <summary> /// Pops the method. /// </summary> public TDelegate PopMethod<TDelegate>() where TDelegate : Delegate { var blockInfo = blockStack.Pop(); var block = Expression.Block(blockInfo.Variables.Values, blockInfo.Expressions); var lambda = Expression.Lambda<TDelegate>(block, blockInfo.Parameters.Values); return lambda.CompileFast(flags: CompilerFlags.ThrowOnNotSupportedExpression); } private record BlockInfo { public IReadOnlyDictionary<string, ParameterExpression> Parameters { get; } public Dictionary<string, ParameterExpression> Variables { get; set; } = new(); public List<Expression> Expressions { get; set; } = new(); public BlockInfo(ParameterExpression[] parameters) { Parameters = parameters.ToDictionary(k => k.Name.NotNull(), v => v); } public ParameterExpression GetParameterOrVariable(string identifierName) => Variables.ContainsKey(identifierName) ? Variables[identifierName] : Parameters.ContainsKey(identifierName) ? Parameters[identifierName] : throw new ArgumentException($"Parameter or variable '{identifierName}' was not found in the current block."); } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Security.DoSDeviceBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(SecurityDoSDeviceVectorStatistics))] public partial class SecurityDoSDevice : iControlInterface { public SecurityDoSDevice() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_vector_packet_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void add_vector_packet_type( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors, SecurityDoSDeviceDoSNetworkVectorPacketType [] [] [] packet_types ) { this.Invoke("add_vector_packet_type", new object [] { devices, vectors, packet_types}); } public System.IAsyncResult Beginadd_vector_packet_type(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors,SecurityDoSDeviceDoSNetworkVectorPacketType [] [] [] packet_types, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_vector_packet_type", new object[] { devices, vectors, packet_types}, callback, asyncState); } public void Endadd_vector_packet_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_all_vector_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public SecurityDoSDeviceVectorStatistics [] get_all_vector_statistics( string [] devices ) { object [] results = this.Invoke("get_all_vector_statistics", new object [] { devices}); return ((SecurityDoSDeviceVectorStatistics [])(results[0])); } public System.IAsyncResult Beginget_all_vector_statistics(string [] devices, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_vector_statistics", new object[] { devices}, callback, asyncState); } public SecurityDoSDeviceVectorStatistics [] Endget_all_vector_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((SecurityDoSDeviceVectorStatistics [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] devices ) { object [] results = this.Invoke("get_description", new object [] { devices}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] devices, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { devices}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_publisher //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_publisher( string [] devices ) { object [] results = this.Invoke("get_publisher", new object [] { devices}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_publisher(string [] devices, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_publisher", new object[] { devices}, callback, asyncState); } public string [] Endget_publisher(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_vector //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public SecurityDoSDeviceDoSDeviceVector [] [] get_vector( string [] devices ) { object [] results = this.Invoke("get_vector", new object [] { devices}); return ((SecurityDoSDeviceDoSDeviceVector [] [])(results[0])); } public System.IAsyncResult Beginget_vector(string [] devices, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vector", new object[] { devices}, callback, asyncState); } public SecurityDoSDeviceDoSDeviceVector [] [] Endget_vector(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((SecurityDoSDeviceDoSDeviceVector [] [])(results[0])); } //----------------------------------------------------------------------- // get_vector_auto_blacklisting_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState [] [] get_vector_auto_blacklisting_state( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors ) { object [] results = this.Invoke("get_vector_auto_blacklisting_state", new object [] { devices, vectors}); return ((CommonEnabledState [] [])(results[0])); } public System.IAsyncResult Beginget_vector_auto_blacklisting_state(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vector_auto_blacklisting_state", new object[] { devices, vectors}, callback, asyncState); } public CommonEnabledState [] [] Endget_vector_auto_blacklisting_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState [] [])(results[0])); } //----------------------------------------------------------------------- // get_vector_blacklist_category //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_vector_blacklist_category( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors ) { object [] results = this.Invoke("get_vector_blacklist_category", new object [] { devices, vectors}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_vector_blacklist_category(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vector_blacklist_category", new object[] { devices, vectors}, callback, asyncState); } public string [] [] Endget_vector_blacklist_category(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_vector_blacklist_detection_seconds //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] [] get_vector_blacklist_detection_seconds( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors ) { object [] results = this.Invoke("get_vector_blacklist_detection_seconds", new object [] { devices, vectors}); return ((long [] [])(results[0])); } public System.IAsyncResult Beginget_vector_blacklist_detection_seconds(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vector_blacklist_detection_seconds", new object[] { devices, vectors}, callback, asyncState); } public long [] [] Endget_vector_blacklist_detection_seconds(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [] [])(results[0])); } //----------------------------------------------------------------------- // get_vector_blacklist_duration //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] [] get_vector_blacklist_duration( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors ) { object [] results = this.Invoke("get_vector_blacklist_duration", new object [] { devices, vectors}); return ((long [] [])(results[0])); } public System.IAsyncResult Beginget_vector_blacklist_duration(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vector_blacklist_duration", new object[] { devices, vectors}, callback, asyncState); } public long [] [] Endget_vector_blacklist_duration(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [] [])(results[0])); } //----------------------------------------------------------------------- // get_vector_default_internal_rate_limit //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] [] get_vector_default_internal_rate_limit( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors ) { object [] results = this.Invoke("get_vector_default_internal_rate_limit", new object [] { devices, vectors}); return ((long [] [])(results[0])); } public System.IAsyncResult Beginget_vector_default_internal_rate_limit(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vector_default_internal_rate_limit", new object[] { devices, vectors}, callback, asyncState); } public long [] [] Endget_vector_default_internal_rate_limit(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [] [])(results[0])); } //----------------------------------------------------------------------- // get_vector_detection_threshold_percent //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] [] get_vector_detection_threshold_percent( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors ) { object [] results = this.Invoke("get_vector_detection_threshold_percent", new object [] { devices, vectors}); return ((long [] [])(results[0])); } public System.IAsyncResult Beginget_vector_detection_threshold_percent(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vector_detection_threshold_percent", new object[] { devices, vectors}, callback, asyncState); } public long [] [] Endget_vector_detection_threshold_percent(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [] [])(results[0])); } //----------------------------------------------------------------------- // get_vector_detection_threshold_pps //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] [] get_vector_detection_threshold_pps( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors ) { object [] results = this.Invoke("get_vector_detection_threshold_pps", new object [] { devices, vectors}); return ((long [] [])(results[0])); } public System.IAsyncResult Beginget_vector_detection_threshold_pps(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vector_detection_threshold_pps", new object[] { devices, vectors}, callback, asyncState); } public long [] [] Endget_vector_detection_threshold_pps(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [] [])(results[0])); } //----------------------------------------------------------------------- // get_vector_packet_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public SecurityDoSDeviceDoSNetworkVectorPacketType [] [] [] get_vector_packet_type( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors ) { object [] results = this.Invoke("get_vector_packet_type", new object [] { devices, vectors}); return ((SecurityDoSDeviceDoSNetworkVectorPacketType [] [] [])(results[0])); } public System.IAsyncResult Beginget_vector_packet_type(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vector_packet_type", new object[] { devices, vectors}, callback, asyncState); } public SecurityDoSDeviceDoSNetworkVectorPacketType [] [] [] Endget_vector_packet_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((SecurityDoSDeviceDoSNetworkVectorPacketType [] [] [])(results[0])); } //----------------------------------------------------------------------- // get_vector_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public SecurityDoSDeviceVectorStatistics [] get_vector_statistics( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors ) { object [] results = this.Invoke("get_vector_statistics", new object [] { devices, vectors}); return ((SecurityDoSDeviceVectorStatistics [])(results[0])); } public System.IAsyncResult Beginget_vector_statistics(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vector_statistics", new object[] { devices, vectors}, callback, asyncState); } public SecurityDoSDeviceVectorStatistics [] Endget_vector_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((SecurityDoSDeviceVectorStatistics [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // remove_all_vector_packet_types //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void remove_all_vector_packet_types( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors ) { this.Invoke("remove_all_vector_packet_types", new object [] { devices, vectors}); } public System.IAsyncResult Beginremove_all_vector_packet_types(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_vector_packet_types", new object[] { devices, vectors}, callback, asyncState); } public void Endremove_all_vector_packet_types(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_vector_packet_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void remove_vector_packet_type( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors, SecurityDoSDeviceDoSNetworkVectorPacketType [] [] [] packet_types ) { this.Invoke("remove_vector_packet_type", new object [] { devices, vectors, packet_types}); } public System.IAsyncResult Beginremove_vector_packet_type(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors,SecurityDoSDeviceDoSNetworkVectorPacketType [] [] [] packet_types, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_vector_packet_type", new object[] { devices, vectors, packet_types}, callback, asyncState); } public void Endremove_vector_packet_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_vector_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void reset_vector_statistics( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors ) { this.Invoke("reset_vector_statistics", new object [] { devices, vectors}); } public System.IAsyncResult Beginreset_vector_statistics(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_vector_statistics", new object[] { devices, vectors}, callback, asyncState); } public void Endreset_vector_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void set_description( string [] devices, string [] descriptions ) { this.Invoke("set_description", new object [] { devices, descriptions}); } public System.IAsyncResult Beginset_description(string [] devices,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { devices, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_publisher //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void set_publisher( string [] devices, string [] publishers ) { this.Invoke("set_publisher", new object [] { devices, publishers}); } public System.IAsyncResult Beginset_publisher(string [] devices,string [] publishers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_publisher", new object[] { devices, publishers}, callback, asyncState); } public void Endset_publisher(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_vector_auto_blacklisting_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void set_vector_auto_blacklisting_state( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors, CommonEnabledState [] [] states ) { this.Invoke("set_vector_auto_blacklisting_state", new object [] { devices, vectors, states}); } public System.IAsyncResult Beginset_vector_auto_blacklisting_state(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors,CommonEnabledState [] [] states, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_vector_auto_blacklisting_state", new object[] { devices, vectors, states}, callback, asyncState); } public void Endset_vector_auto_blacklisting_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_vector_blacklist_category //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void set_vector_blacklist_category( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors, string [] [] values ) { this.Invoke("set_vector_blacklist_category", new object [] { devices, vectors, values}); } public System.IAsyncResult Beginset_vector_blacklist_category(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors,string [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_vector_blacklist_category", new object[] { devices, vectors, values}, callback, asyncState); } public void Endset_vector_blacklist_category(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_vector_blacklist_detection_seconds //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void set_vector_blacklist_detection_seconds( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors, long [] [] values ) { this.Invoke("set_vector_blacklist_detection_seconds", new object [] { devices, vectors, values}); } public System.IAsyncResult Beginset_vector_blacklist_detection_seconds(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors,long [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_vector_blacklist_detection_seconds", new object[] { devices, vectors, values}, callback, asyncState); } public void Endset_vector_blacklist_detection_seconds(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_vector_blacklist_duration //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void set_vector_blacklist_duration( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors, long [] [] values ) { this.Invoke("set_vector_blacklist_duration", new object [] { devices, vectors, values}); } public System.IAsyncResult Beginset_vector_blacklist_duration(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors,long [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_vector_blacklist_duration", new object[] { devices, vectors, values}, callback, asyncState); } public void Endset_vector_blacklist_duration(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_vector_default_internal_rate_limit //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void set_vector_default_internal_rate_limit( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors, long [] [] values ) { this.Invoke("set_vector_default_internal_rate_limit", new object [] { devices, vectors, values}); } public System.IAsyncResult Beginset_vector_default_internal_rate_limit(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors,long [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_vector_default_internal_rate_limit", new object[] { devices, vectors, values}, callback, asyncState); } public void Endset_vector_default_internal_rate_limit(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_vector_detection_threshold_percent //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void set_vector_detection_threshold_percent( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors, long [] [] values ) { this.Invoke("set_vector_detection_threshold_percent", new object [] { devices, vectors, values}); } public System.IAsyncResult Beginset_vector_detection_threshold_percent(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors,long [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_vector_detection_threshold_percent", new object[] { devices, vectors, values}, callback, asyncState); } public void Endset_vector_detection_threshold_percent(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_vector_detection_threshold_pps //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Security/DoSDevice", RequestNamespace="urn:iControl:Security/DoSDevice", ResponseNamespace="urn:iControl:Security/DoSDevice")] public void set_vector_detection_threshold_pps( string [] devices, SecurityDoSDeviceDoSDeviceVector [] [] vectors, long [] [] values ) { this.Invoke("set_vector_detection_threshold_pps", new object [] { devices, vectors, values}); } public System.IAsyncResult Beginset_vector_detection_threshold_pps(string [] devices,SecurityDoSDeviceDoSDeviceVector [] [] vectors,long [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_vector_detection_threshold_pps", new object[] { devices, vectors, values}, callback, asyncState); } public void Endset_vector_detection_threshold_pps(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Security.DoSDevice.DoSDeviceVector", Namespace = "urn:iControl")] public enum SecurityDoSDeviceDoSDeviceVector { DOS_DEVICE_VECTOR_UNKNOWN, DOS_DEVICE_VECTOR_ARP_FLOOD, DOS_DEVICE_VECTOR_BAD_ICMP_FRAME, DOS_DEVICE_VECTOR_IP_OPT_ILL_LEN, DOS_DEVICE_VECTOR_BAD_IPV6_HOP_COUNT, DOS_DEVICE_VECTOR_BAD_IPV6_VER, DOS_DEVICE_VECTOR_BAD_TCP_CHECKSUM, DOS_DEVICE_VECTOR_BAD_TCP_FLAGS_ALL_CLR, DOS_DEVICE_VECTOR_BAD_TCP_FLAGS_ALL_SET, DOS_DEVICE_VECTOR_BAD_TTL_VALUE, DOS_DEVICE_VECTOR_BAD_UDP_CHECKSUM, DOS_DEVICE_VECTOR_BAD_UDP_HEADER, DOS_DEVICE_VECTOR_BAD_VERSION, DOS_DEVICE_VECTOR_DNS_RESPONSE_FLOOD, DOS_DEVICE_VECTOR_ETHER_BRDCST_PKT, DOS_DEVICE_VECTOR_ETHER_MAC_SA_EQ_DA, DOS_DEVICE_VECTOR_ETHER_MULTICST_PKT, DOS_DEVICE_VECTOR_FIN_ONLY_SET, DOS_DEVICE_VECTOR_HEADER_LENGTH_GT_L2_LENGTH, DOS_DEVICE_VECTOR_HEADER_LENGTH_TOO_SHORT, DOS_DEVICE_VECTOR_HOST_UNREACHABLE, DOS_DEVICE_VECTOR_ICMP_FLOOD, DOS_DEVICE_VECTOR_ICMP_FRAG, DOS_DEVICE_VECTOR_ICMP_FRAME_TOO_LARGE, DOS_DEVICE_VECTOR_IP_ERR_CHECKSUM, DOS_DEVICE_VECTOR_IP_FRAG, DOS_DEVICE_VECTOR_IP_FRAG_FLOOD, DOS_DEVICE_VECTOR_IP_LENGTH_GT_L2_LENGTH, DOS_DEVICE_VECTOR_IP_OPT_FRAMES, DOS_DEVICE_VECTOR_IP_OVERLAP_FRAG, DOS_DEVICE_VECTOR_IP_SA_EQ_DA, DOS_DEVICE_VECTOR_IP_SHORT_FRAG, DOS_DEVICE_VECTOR_IPV6_EXT_HEADER_FRAMES, DOS_DEVICE_VECTOR_IPV6_FRAG, DOS_DEVICE_VECTOR_IPV6_FRAG_FLOOD, DOS_DEVICE_VECTOR_IPV6_LENGTH_GT_L2_LENGTH, DOS_DEVICE_VECTOR_IPV6_OVERLAP_FRAG, DOS_DEVICE_VECTOR_IPV6_SA_EQ_DA, DOS_DEVICE_VECTOR_IPV6_SHORT_FRAG, DOS_DEVICE_VECTOR_L2_LENGTH_GGT_IP_LENGTH, DOS_DEVICE_VECTOR_L4_EXT_HEADERS_GO_END, DOS_DEVICE_VECTOR_NO_L4, DOS_DEVICE_VECTOR_OPT_PRESENT_WITH_ILLEGAL_LENGTH, DOS_DEVICE_VECTOR_PAYLOAD_LENGTH_LS_L2_LENGTH, DOS_DEVICE_VECTOR_ROUTING_HEADER_TYPE_0, DOS_DEVICE_VECTOR_SSL_RENEGOTIATION, DOS_DEVICE_VECTOR_SYN_AND_FIN_SET, DOS_DEVICE_VECTOR_TCP_BADACK_FLOOD, DOS_DEVICE_VECTOR_TCP_HEADER_LENGTH_GT_L2_LENGTH, DOS_DEVICE_VECTOR_TCP_HEADER_LENGTH_TOO_SHORT, DOS_DEVICE_VECTOR_TCP_LAND, DOS_DEVICE_VECTOR_TCP_OPT_OVERRUNS_TCP_HEADER, DOS_DEVICE_VECTOR_TCP_RST_FLOOD, DOS_DEVICE_VECTOR_TCP_SYNACK_FLOOD, DOS_DEVICE_VECTOR_TCP_SYN_FLOOD, DOS_DEVICE_VECTOR_TIDCMP, DOS_DEVICE_VECTOR_TOO_MANY_EXT_HEADERS, DOS_DEVICE_VECTOR_IP_LOW_TTL, DOS_DEVICE_VECTOR_UDP_LAND, DOS_DEVICE_VECTOR_UNK_TCP_OPT_TYPE, DOS_DEVICE_VECTOR_FLOOD, DOS_DEVICE_VECTOR_SWEEP, DOS_DEVICE_VECTOR_ICMPV6_FLOOD, DOS_DEVICE_VECTOR_IPV6_DUPLICATE_EXTENSION_HEADERS, DOS_DEVICE_VECTOR_IPV6_EXTENSION_HEADERS_WRONG_ORDER, DOS_DEVICE_VECTOR_IPV6_EXTENSION_HEADERS_TOO_LARGE, DOS_DEVICE_VECTOR_IPV6_HOP_COUNT_LOW, DOS_DEVICE_VECTOR_UDP_FLOOD, DOS_DEVICE_VECTOR_ICMPV4_FLOOD, DOS_DEVICE_VECTOR_BAD_IGMP_FRAME, DOS_DEVICE_VECTOR_IGMP_FLOOD, DOS_DEVICE_VECTOR_DUP_EXT_HDR, DOS_DEVICE_VECTOR_EXT_HDR_TOO_LARGE, DOS_DEVICE_VECTOR_HOP_CNT_LOW, DOS_DEVICE_VECTOR_BAD_EXT_HDR_ORDER, DOS_DEVICE_VECTOR_IGMP_FRAG_FLOOD, DOS_DEVICE_VECTOR_BAD_ICMP_CHKSUM, DOS_DEVICE_VECTOR_TCP_BAD_URG, DOS_DEVICE_VECTOR_TCP_WINDOW_SIZE, DOS_DEVICE_VECTOR_IPV6_ATOMIC_FRAG, DOS_DEVICE_VECTOR_BAD_UDP_HDR, DOS_DEVICE_VECTOR_BAD_UDP_CHKSUM, DOS_DEVICE_VECTOR_IP_BAD_SRC, DOS_DEVICE_VECTOR_IPV6_BAD_ADDR, DOS_DEVICE_VECTOR_DNS_OVERSIZE, DOS_DEVICE_VECTOR_LAND_ATTACK, DOS_DEVICE_VECTOR_UDPDNS_RESPONSE_FLOOD, DOS_DEVICE_VECTOR_UDPDNS_MALFORMED, DOS_DEVICE_VECTOR_UDPDNS_QDCOUNT_LIMIT, DOS_DEVICE_VECTOR_UDPDNS_ANY_QUERY, DOS_DEVICE_VECTOR_UDPDNS_A_QUERY, DOS_DEVICE_VECTOR_UDPDNS_PTR_QUERY, DOS_DEVICE_VECTOR_UDPDNS_NS_QUERY, DOS_DEVICE_VECTOR_UDPDNS_SOA_QUERY, DOS_DEVICE_VECTOR_UDPDNS_CNAME_QUERY, DOS_DEVICE_VECTOR_UDPDNS_MX_QUERY, DOS_DEVICE_VECTOR_UDPDNS_AAAA_QUERY, DOS_DEVICE_VECTOR_UDPDNS_TXT_QUERY, DOS_DEVICE_VECTOR_UDPDNS_SRV_QUERY, DOS_DEVICE_VECTOR_UDPDNS_AXFR_QUERY, DOS_DEVICE_VECTOR_UDPDNS_IXFR_QUERY, DOS_DEVICE_VECTOR_UDPDNS_OTHER_QUERY, DOS_DEVICE_VECTOR_UDPSIP_MALFORMED, DOS_DEVICE_VECTOR_UDPSIP_INVITE_METHOD, DOS_DEVICE_VECTOR_UDPSIP_ACK_METHOD, DOS_DEVICE_VECTOR_UDPSIP_OPTIONS_METHOD, DOS_DEVICE_VECTOR_UDPSIP_BYE_METHOD, DOS_DEVICE_VECTOR_UDPSIP_CANCEL_METHOD, DOS_DEVICE_VECTOR_UDPSIP_REGISTER_METHOD, DOS_DEVICE_VECTOR_UDPSIP_PUBLISH_METHOD, DOS_DEVICE_VECTOR_UDPSIP_NOTIFY_METHOD, DOS_DEVICE_VECTOR_UDPSIP_SUBSCRIBE_METHOD, DOS_DEVICE_VECTOR_UDPSIP_MESSAGE_METHOD, DOS_DEVICE_VECTOR_UDPSIP_PRACK_METHOD, DOS_DEVICE_VECTOR_UDPSIP_OTHER_METHOD, DOS_DEVICE_VECTOR_UNK_IPOPT_TYPE, DOS_DEVICE_VECTOR_BAD_SCTP_CHECKSUM, DOS_DEVICE_VECTOR_IP_UNKNOWN_PROTOCOL, DOS_DEVICE_VECTOR_TCP_SYN_OVERSIZE, } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Security.DoSDevice.DoSNetworkVectorPacketType", Namespace = "urn:iControl")] public enum SecurityDoSDeviceDoSNetworkVectorPacketType { NETWORK_ATTACK_PACKET_UNKNOWN, NETWORK_ATTACK_PACKET_UDP, NETWORK_ATTACK_PACKET_TCP_SYN_ONLY, NETWORK_ATTACK_PACKET_IPV4_ICMP, NETWORK_ATTACK_PACKET_IPV4_ANY, NETWORK_ATTACK_PACKET_IPV6_UDP, NETWORK_ATTACK_PACKET_IPV6_TCP_SYN_ONLY, NETWORK_ATTACK_PACKET_IPV6_ICMP, NETWORK_ATTACK_PACKET_IPV6_ANY, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Security.DoSDevice.VectorStatisticEntry", Namespace = "urn:iControl")] public partial class SecurityDoSDeviceVectorStatisticEntry { private SecurityDoSDeviceDoSDeviceVector attack_vectorField; public SecurityDoSDeviceDoSDeviceVector attack_vector { get { return this.attack_vectorField; } set { this.attack_vectorField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Security.DoSDevice.VectorStatistics", Namespace = "urn:iControl")] public partial class SecurityDoSDeviceVectorStatistics { private SecurityDoSDeviceVectorStatisticEntry [] statisticsField; public SecurityDoSDeviceVectorStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }
//----------------------------------------------------------------------------- // Verve // Copyright (C) - Violent Tulip //----------------------------------------------------------------------------- function VControllerPropertyList::CreateInspectorGroup( %this, %targetStack ) { %baseGroup = Parent::CreateInspectorGroup( %this, %targetStack ); if ( %baseGroup.getClassName() !$= "ScriptGroup" ) { // Temp Store. %temp = %baseGroup; // Create SimSet. %baseGroup = new SimSet(); // Add Original Control. %baseGroup.add( %temp ); } // Create Data Table Group. %groupRollout = %targetStack.CreatePropertyRollout( "VController DataTable" ); %propertyStack = %groupRollout.Stack; // Reference. %propertyStack.InternalName = "DataTableStack"; // Store. %baseGroup.add( %groupRollout ); // Return. return %baseGroup; } function VControllerPropertyList::InspectObject( %this, %object ) { if ( !%object.isMemberOfClass( "VController" ) ) { // Invalid Object. return; } // Default Inspect. Parent::InspectObject( %this, %object ); // Update Data Table. %dataTableStack = %this.ControlCache.findObjectByInternalName( "DataTableStack", true ); if ( !isObject( %dataTableStack ) ) { // Invalid Table. return; } // Clear Stack. while ( %dataTableStack.getCount() > 1 ) { // Delete Object. %dataTableStack.getObject( 1 ).delete(); } %dataFieldCount = %object.getDataFieldCount(); for ( %i = 0; %i < %dataFieldCount; %i++ ) { // Add To List. %dataFieldList = trim( %dataFieldList SPC %object.getDataFieldName( %i ) ); } // Sort Word List. %dataFieldList = sortWordList( %dataFieldList ); for ( %i = 0; %i < %dataFieldCount; %i++ ) { // Fetch Field Name. %dataFieldName = getWord( %dataFieldList, %i ); // Create Field. VerveEditor::CreateField( %dataTableStack, %dataFieldName, "Data" ); } // Create Add Field. VerveEditor::CreateAddDataField( %dataTableStack ); // Update. %dataTableStack.InspectObject( %object ); } function VController::DisplayContextMenu( %this, %x, %y ) { %contextMenu = $VerveEditor::VController::ContextMenu; if ( !isObject( %contextMenu ) ) { %contextMenu = new PopupMenu() { SuperClass = "VerveWindowMenu"; IsPopup = true; Label = "VControllerContextMenu"; Position = 0; Item[0] = "Add Group" TAB ""; Item[1] = "" TAB ""; Item[2] = "Cu&t" TAB "" TAB ""; Item[3] = "&Copy" TAB "" TAB ""; Item[4] = "&Paste" TAB "" TAB "VerveEditor::Paste();"; Item[5] = "" TAB ""; Item[6] = "&Delete" TAB "" TAB ""; PasteIndex = 4; }; %contextMenu.Init(); // Disable Cut, Copy & Delete. %contextMenu.enableItem( 2, false ); %contextMenu.enableItem( 3, false ); %contextMenu.enableItem( 6, false ); // Cache. $VerveEditor::VController::ContextMenu = %contextMenu; } // Remove Add Menu. %contextMenu.removeItem( %contextMenu.AddIndex ); // Insert Menu. %contextMenu.insertSubMenu( %contextMenu.AddIndex, getField( %contextMenu.Item[0], 0 ), %this.GetAddGroupMenu() ); // Enable/Disable Pasting. %contextMenu.enableItem( %contextMenu.PasteIndex, VerveEditor::CanPaste() ); if ( %x $= "" || %y $= "" ) { %position = %this.getGlobalPosition(); %extent = %this.getExtent(); %x = getWord( %position, 0 ) + getWord( %extent, 0 ); %y = getWord( %position, 1 ); } // Display. %contextMenu.showPopup( VerveEditorWindow, %x, %y ); } function VController::GetAddGroupMenu( %this ) { %contextMenu = $VerveEditor::VController::ContextMenu[%this.getClassName()]; if ( !isObject( %contextMenu ) ) { %customTemplateMenu = new PopupMenu() { Class = "VerveCustomTemplateMenu"; SuperClass = "VerveWindowMenu"; IsPopup = true; Label = "VGroupAddGroupMenu"; Position = 0; }; %customTemplateMenu.Init(); %contextMenu = new PopupMenu() { SuperClass = "VerveWindowMenu"; IsPopup = true; Label = "VGroupAddGroupMenu"; Position = 0; Item[0] = "Add Camera Group" TAB "" TAB "VerveEditor::AddGroup(\"VCameraGroup\");"; Item[1] = "Add Director Group" TAB "" TAB "VerveEditor::AddGroup(\"VDirectorGroup\");"; Item[2] = "Add Light Object Group" TAB "" TAB "VerveEditor::AddGroup(\"VLightObjectGroup\");"; Item[3] = "Add Particle Effect Group" TAB "" TAB "VerveEditor::AddGroup(\"VParticleEffectGroup\");"; Item[4] = "Add Scene Object Group" TAB "" TAB "VerveEditor::AddGroup(\"VSceneObjectGroup\");"; Item[5] = "Add Spawn Sphere Group" TAB "" TAB "VerveEditor::AddGroup(\"VSpawnSphereGroup\");"; Item[6] = "" TAB ""; Item[7] = "Add Custom Group" TAB %customTemplateMenu; DirectorIndex = 1; CustomIndex = 7; CustomMenu = %customTemplateMenu; }; %contextMenu.Init(); // Refresh Menu. %customTemplateMenu = %contextMenu.CustomMenu; if ( %customTemplateMenu.getItemCount() == 0 ) { // Remove Item. %contextMenu.removeItem( %contextMenu.CustomIndex ); // Add Dummy. %contextMenu.insertItem( %contextMenu.CustomIndex, getField( %contextMenu.Item[%contextMenu.CustomIndex], 0 ) ); // Disable Custom Menu. %contextMenu.enableItem( %contextMenu.CustomIndex, false ); } // Cache. $VerveEditor::VController::ContextMenu[%this.getClassName()] = %contextMenu; } // Enable / Disable Director Group. %contextMenu.enableItem( %contextMenu.DirectorIndex, %this.CanAdd( "VDirectorGroup" ) ); // Return Menu. return %contextMenu; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Globalization; using System.Security; using System.Text; using System.Threading; using System.Collections; using System.ComponentModel; using Microsoft.Win32; using System.IO; namespace System.Diagnostics { internal class PerformanceCounterLib { internal const string PerfShimName = "netfxperf.dll"; private const string PerfShimFullNameSuffix = @"\netfxperf.dll"; private const string PerfShimPathExp = @"%systemroot%\system32\netfxperf.dll"; internal const string OpenEntryPoint = "OpenPerformanceData"; internal const string CollectEntryPoint = "CollectPerformanceData"; internal const string CloseEntryPoint = "ClosePerformanceData"; internal const string SingleInstanceName = "systemdiagnosticsperfcounterlibsingleinstance"; private const string PerflibPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib"; internal const string ServicePath = "SYSTEM\\CurrentControlSet\\Services"; private const string CategorySymbolPrefix = "OBJECT_"; private const string ConterSymbolPrefix = "DEVICE_COUNTER_"; private const string HelpSufix = "_HELP"; private const string NameSufix = "_NAME"; private const string TextDefinition = "[text]"; private const string InfoDefinition = "[info]"; private const string LanguageDefinition = "[languages]"; private const string ObjectDefinition = "[objects]"; private const string DriverNameKeyword = "drivername"; private const string SymbolFileKeyword = "symbolfile"; private const string DefineKeyword = "#define"; private const string LanguageKeyword = "language"; private const string DllName = "netfxperf.dll"; private const int EnglishLCID = 0x009; private static volatile string s_computerName; private static volatile string s_iniFilePath; private static volatile string s_symbolFilePath; private PerformanceMonitor _performanceMonitor; private string _machineName; private string _perfLcid; private Hashtable _customCategoryTable; private static volatile Hashtable s_libraryTable; private Hashtable _categoryTable; private Hashtable _nameTable; private Hashtable _helpTable; private readonly object _categoryTableLock = new Object(); private readonly object _nameTableLock = new Object(); private readonly object _helpTableLock = new Object(); private static Object s_internalSyncObject; private static Object InternalSyncObject { get { if (s_internalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange(ref s_internalSyncObject, o, null); } return s_internalSyncObject; } } internal PerformanceCounterLib(string machineName, string lcid) { _machineName = machineName; _perfLcid = lcid; } /// <internalonly/> internal static string ComputerName { get { if (s_computerName == null) { lock (InternalSyncObject) { if (s_computerName == null) { s_computerName = Interop.Kernel32.GetComputerName() ?? string.Empty; } } } return s_computerName; } } private unsafe Hashtable CategoryTable { get { if (_categoryTable == null) { lock (_categoryTableLock) { if (_categoryTable == null) { byte[] perfData = GetPerformanceData("Global"); fixed (byte* perfDataPtr = perfData) { IntPtr dataRef = new IntPtr((void*)perfDataPtr); Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK(); Marshal.PtrToStructure(dataRef, dataBlock); dataRef = (IntPtr)((long)dataRef + dataBlock.HeaderLength); int categoryNumber = dataBlock.NumObjectTypes; // on some machines MSMQ claims to have 4 categories, even though it only has 2. // This causes us to walk past the end of our data, potentially crashing or reading // data we shouldn't. We use endPerfData to make sure we don't go past the end // of the perf data. long endPerfData = (long)(new IntPtr((void*)perfDataPtr)) + dataBlock.TotalByteLength; Hashtable tempCategoryTable = new Hashtable(categoryNumber, StringComparer.OrdinalIgnoreCase); for (int index = 0; index < categoryNumber && ((long)dataRef < endPerfData); index++) { Interop.Advapi32.PERF_OBJECT_TYPE perfObject = new Interop.Advapi32.PERF_OBJECT_TYPE(); Marshal.PtrToStructure(dataRef, perfObject); CategoryEntry newCategoryEntry = new CategoryEntry(perfObject); IntPtr nextRef = (IntPtr)((long)dataRef + perfObject.TotalByteLength); dataRef = (IntPtr)((long)dataRef + perfObject.HeaderLength); int index3 = 0; int previousCounterIndex = -1; //Need to filter out counters that are repeated, some providers might //return several adyacent copies of the same counter. for (int index2 = 0; index2 < newCategoryEntry.CounterIndexes.Length; ++index2) { Interop.Advapi32.PERF_COUNTER_DEFINITION perfCounter = new Interop.Advapi32.PERF_COUNTER_DEFINITION(); Marshal.PtrToStructure(dataRef, perfCounter); if (perfCounter.CounterNameTitleIndex != previousCounterIndex) { newCategoryEntry.CounterIndexes[index3] = perfCounter.CounterNameTitleIndex; newCategoryEntry.HelpIndexes[index3] = perfCounter.CounterHelpTitleIndex; previousCounterIndex = perfCounter.CounterNameTitleIndex; ++index3; } dataRef = (IntPtr)((long)dataRef + perfCounter.ByteLength); } //Lets adjust the entry counter arrays in case there were repeated copies if (index3 < newCategoryEntry.CounterIndexes.Length) { int[] adjustedCounterIndexes = new int[index3]; int[] adjustedHelpIndexes = new int[index3]; Array.Copy(newCategoryEntry.CounterIndexes, adjustedCounterIndexes, index3); Array.Copy(newCategoryEntry.HelpIndexes, adjustedHelpIndexes, index3); newCategoryEntry.CounterIndexes = adjustedCounterIndexes; newCategoryEntry.HelpIndexes = adjustedHelpIndexes; } string categoryName = (string)NameTable[newCategoryEntry.NameIndex]; if (categoryName != null) tempCategoryTable[categoryName] = newCategoryEntry; dataRef = nextRef; } _categoryTable = tempCategoryTable; } } } } return _categoryTable; } } internal Hashtable HelpTable { get { if (_helpTable == null) { lock (_helpTableLock) { if (_helpTable == null) _helpTable = GetStringTable(true); } } return _helpTable; } } // Returns a temp file name private static string IniFilePath { get { if (s_iniFilePath == null) { lock (InternalSyncObject) { if (s_iniFilePath == null) { try { s_iniFilePath = Path.GetTempFileName(); } finally { } } } } return s_iniFilePath; } } internal Hashtable NameTable { get { if (_nameTable == null) { lock (_nameTableLock) { if (_nameTable == null) _nameTable = GetStringTable(false); } } return _nameTable; } } // Returns a temp file name private static string SymbolFilePath { get { if (s_symbolFilePath == null) { lock (InternalSyncObject) { if (s_symbolFilePath == null) { string tempPath; tempPath = Path.GetTempPath(); try { s_symbolFilePath = Path.GetTempFileName(); } finally { } } } } return s_symbolFilePath; } } internal static bool CategoryExists(string machine, string category) { PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID)); if (library.CategoryExists(category)) return true; if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) { CultureInfo culture = CultureInfo.CurrentCulture; while (culture != CultureInfo.InvariantCulture) { library = GetPerformanceCounterLib(machine, culture); if (library.CategoryExists(category)) return true; culture = culture.Parent; } } return false; } internal bool CategoryExists(string category) { return CategoryTable.ContainsKey(category); } internal static void CloseAllLibraries() { if (s_libraryTable != null) { foreach (PerformanceCounterLib library in s_libraryTable.Values) library.Close(); s_libraryTable = null; } } internal static void CloseAllTables() { if (s_libraryTable != null) { foreach (PerformanceCounterLib library in s_libraryTable.Values) library.CloseTables(); } } internal void CloseTables() { _nameTable = null; _helpTable = null; _categoryTable = null; _customCategoryTable = null; } internal void Close() { if (_performanceMonitor != null) { _performanceMonitor.Close(); _performanceMonitor = null; } CloseTables(); } internal static bool CounterExists(string machine, string category, string counter) { PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID)); bool categoryExists = false; bool counterExists = library.CounterExists(category, counter, ref categoryExists); if (!categoryExists && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) { CultureInfo culture = CultureInfo.CurrentCulture; while (culture != CultureInfo.InvariantCulture) { library = GetPerformanceCounterLib(machine, culture); counterExists = library.CounterExists(category, counter, ref categoryExists); if (counterExists) break; culture = culture.Parent; } } if (!categoryExists) { // Consider adding diagnostic logic here, may be we can dump the nameTable... throw new InvalidOperationException(SR.Format(SR.MissingCategory)); } return counterExists; } private bool CounterExists(string category, string counter, ref bool categoryExists) { categoryExists = false; if (!CategoryTable.ContainsKey(category)) return false; else categoryExists = true; CategoryEntry entry = (CategoryEntry)CategoryTable[category]; for (int index = 0; index < entry.CounterIndexes.Length; ++index) { int counterIndex = entry.CounterIndexes[index]; string counterName = (string)NameTable[counterIndex]; if (counterName == null) counterName = string.Empty; if (string.Equals(counterName, counter, StringComparison.OrdinalIgnoreCase)) return true; } return false; } private static void CreateIniFile(string categoryName, string categoryHelp, CounterCreationDataCollection creationData, string[] languageIds) { try { StreamWriter iniWriter = new StreamWriter(IniFilePath, false, Encoding.Unicode); try { //NT4 won't be able to parse Unicode ini files without this //extra white space. iniWriter.WriteLine(""); iniWriter.WriteLine(InfoDefinition); iniWriter.Write(DriverNameKeyword); iniWriter.Write("="); iniWriter.WriteLine(categoryName); iniWriter.Write(SymbolFileKeyword); iniWriter.Write("="); iniWriter.WriteLine(Path.GetFileName(SymbolFilePath)); iniWriter.WriteLine(""); iniWriter.WriteLine(LanguageDefinition); foreach (string languageId in languageIds) { iniWriter.Write(languageId); iniWriter.Write("="); iniWriter.Write(LanguageKeyword); iniWriter.WriteLine(languageId); } iniWriter.WriteLine(""); iniWriter.WriteLine(ObjectDefinition); foreach (string languageId in languageIds) { iniWriter.Write(CategorySymbolPrefix); iniWriter.Write("1_"); iniWriter.Write(languageId); iniWriter.Write(NameSufix); iniWriter.Write("="); iniWriter.WriteLine(categoryName); } iniWriter.WriteLine(""); iniWriter.WriteLine(TextDefinition); foreach (string languageId in languageIds) { iniWriter.Write(CategorySymbolPrefix); iniWriter.Write("1_"); iniWriter.Write(languageId); iniWriter.Write(NameSufix); iniWriter.Write("="); iniWriter.WriteLine(categoryName); iniWriter.Write(CategorySymbolPrefix); iniWriter.Write("1_"); iniWriter.Write(languageId); iniWriter.Write(HelpSufix); iniWriter.Write("="); if (categoryHelp == null || categoryHelp == string.Empty) iniWriter.WriteLine(SR.Format(SR.HelpNotAvailable)); else iniWriter.WriteLine(categoryHelp); int counterIndex = 0; foreach (CounterCreationData counterData in creationData) { ++counterIndex; iniWriter.WriteLine(""); iniWriter.Write(ConterSymbolPrefix); iniWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture)); iniWriter.Write("_"); iniWriter.Write(languageId); iniWriter.Write(NameSufix); iniWriter.Write("="); iniWriter.WriteLine(counterData.CounterName); iniWriter.Write(ConterSymbolPrefix); iniWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture)); iniWriter.Write("_"); iniWriter.Write(languageId); iniWriter.Write(HelpSufix); iniWriter.Write("="); Debug.Assert(!string.IsNullOrEmpty(counterData.CounterHelp), "CounterHelp should have been fixed up by the caller"); iniWriter.WriteLine(counterData.CounterHelp); } } iniWriter.WriteLine(""); } finally { iniWriter.Close(); } } finally { } } private static void CreateRegistryEntry(string categoryName, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection creationData, ref bool iniRegistered) { RegistryKey serviceParentKey = null; RegistryKey serviceKey = null; RegistryKey linkageKey = null; try { serviceParentKey = Registry.LocalMachine.OpenSubKey(ServicePath, true); serviceKey = serviceParentKey.OpenSubKey(categoryName + "\\Performance", true); if (serviceKey == null) serviceKey = serviceParentKey.CreateSubKey(categoryName + "\\Performance"); serviceKey.SetValue("Open", "OpenPerformanceData"); serviceKey.SetValue("Collect", "CollectPerformanceData"); serviceKey.SetValue("Close", "ClosePerformanceData"); serviceKey.SetValue("Library", DllName); serviceKey.SetValue("IsMultiInstance", (int)categoryType, RegistryValueKind.DWord); serviceKey.SetValue("CategoryOptions", 0x3, RegistryValueKind.DWord); string[] counters = new string[creationData.Count]; string[] counterTypes = new string[creationData.Count]; for (int i = 0; i < creationData.Count; i++) { counters[i] = creationData[i].CounterName; counterTypes[i] = ((int)creationData[i].CounterType).ToString(CultureInfo.InvariantCulture); } linkageKey = serviceParentKey.OpenSubKey(categoryName + "\\Linkage", true); if (linkageKey == null) linkageKey = serviceParentKey.CreateSubKey(categoryName + "\\Linkage"); linkageKey.SetValue("Export", new string[] { categoryName }); serviceKey.SetValue("Counter Types", (object)counterTypes); serviceKey.SetValue("Counter Names", (object)counters); object firstID = serviceKey.GetValue("First Counter"); if (firstID != null) iniRegistered = true; else iniRegistered = false; } finally { if (serviceKey != null) serviceKey.Close(); if (linkageKey != null) linkageKey.Close(); if (serviceParentKey != null) serviceParentKey.Close(); } } private static void CreateSymbolFile(CounterCreationDataCollection creationData) { try { StreamWriter symbolWriter = new StreamWriter(SymbolFilePath); try { symbolWriter.Write(DefineKeyword); symbolWriter.Write(" "); symbolWriter.Write(CategorySymbolPrefix); symbolWriter.WriteLine("1 0;"); for (int counterIndex = 1; counterIndex <= creationData.Count; ++counterIndex) { symbolWriter.Write(DefineKeyword); symbolWriter.Write(" "); symbolWriter.Write(ConterSymbolPrefix); symbolWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture)); symbolWriter.Write(" "); symbolWriter.Write((counterIndex * 2).ToString(CultureInfo.InvariantCulture)); symbolWriter.WriteLine(";"); } symbolWriter.WriteLine(""); } finally { symbolWriter.Close(); } } finally { } } private static void DeleteRegistryEntry(string categoryName) { RegistryKey serviceKey = null; try { serviceKey = Registry.LocalMachine.OpenSubKey(ServicePath, true); bool deleteCategoryKey = false; using (RegistryKey categoryKey = serviceKey.OpenSubKey(categoryName, true)) { if (categoryKey != null) { if (categoryKey.GetValueNames().Length == 0) { deleteCategoryKey = true; } else { categoryKey.DeleteSubKeyTree("Linkage"); categoryKey.DeleteSubKeyTree("Performance"); } } } if (deleteCategoryKey) serviceKey.DeleteSubKeyTree(categoryName); } finally { if (serviceKey != null) serviceKey.Close(); } } private static void DeleteTemporaryFiles() { try { File.Delete(IniFilePath); } catch { } try { File.Delete(SymbolFilePath); } catch { } } // Ensures that the customCategoryTable is initialized and decides whether the category passed in // 1) is a custom category // 2) is a multi instance custom category // The return value is whether the category is a custom category or not. internal bool FindCustomCategory(string category, out PerformanceCounterCategoryType categoryType) { RegistryKey key = null; RegistryKey baseKey = null; categoryType = PerformanceCounterCategoryType.Unknown; if (_customCategoryTable == null) { Interlocked.CompareExchange(ref _customCategoryTable, new Hashtable(StringComparer.OrdinalIgnoreCase), null); } if (_customCategoryTable.ContainsKey(category)) { categoryType = (PerformanceCounterCategoryType)_customCategoryTable[category]; return true; } else { try { string keyPath = ServicePath + "\\" + category + "\\Performance"; if (_machineName == "." || string.Equals(_machineName, ComputerName, StringComparison.OrdinalIgnoreCase)) { key = Registry.LocalMachine.OpenSubKey(keyPath); } else { baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "\\\\" + _machineName); if (baseKey != null) { try { key = baseKey.OpenSubKey(keyPath); } catch (SecurityException) { // we may not have permission to read the registry key on the remote machine. The security exception // is thrown when RegOpenKeyEx returns ERROR_ACCESS_DENIED or ERROR_BAD_IMPERSONATION_LEVEL // // In this case we return an 'Unknown' category type and 'false' to indicate the category is *not* custom. // categoryType = PerformanceCounterCategoryType.Unknown; _customCategoryTable[category] = categoryType; return false; } } } if (key != null) { object systemDllName = key.GetValue("Library", null, RegistryValueOptions.DoNotExpandEnvironmentNames); if (systemDllName != null && systemDllName is string && (string.Equals((string)systemDllName, PerformanceCounterLib.PerfShimName, StringComparison.OrdinalIgnoreCase) || ((string)systemDllName).EndsWith(PerformanceCounterLib.PerfShimFullNameSuffix, StringComparison.OrdinalIgnoreCase))) { object isMultiInstanceObject = key.GetValue("IsMultiInstance"); if (isMultiInstanceObject != null) { categoryType = (PerformanceCounterCategoryType)isMultiInstanceObject; if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance) categoryType = PerformanceCounterCategoryType.Unknown; } else categoryType = PerformanceCounterCategoryType.Unknown; object objectID = key.GetValue("First Counter"); if (objectID != null) { int firstID = (int)objectID; _customCategoryTable[category] = categoryType; return true; } } } } finally { if (key != null) key.Close(); if (baseKey != null) baseKey.Close(); } } return false; } internal static string[] GetCategories(string machineName) { PerformanceCounterLib library; CultureInfo culture = CultureInfo.CurrentCulture; while (culture != CultureInfo.InvariantCulture) { library = GetPerformanceCounterLib(machineName, culture); string[] categories = library.GetCategories(); if (categories.Length != 0) return categories; culture = culture.Parent; } library = GetPerformanceCounterLib(machineName, new CultureInfo(EnglishLCID)); return library.GetCategories(); } internal string[] GetCategories() { ICollection keys = CategoryTable.Keys; string[] categories = new string[keys.Count]; keys.CopyTo(categories, 0); return categories; } internal static string GetCategoryHelp(string machine, string category) { PerformanceCounterLib library; string help; //First check the current culture for the category. This will allow //PerformanceCounterCategory.CategoryHelp to return localized strings. if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) { CultureInfo culture = CultureInfo.CurrentCulture; while (culture != CultureInfo.InvariantCulture) { library = GetPerformanceCounterLib(machine, culture); help = library.GetCategoryHelp(category); if (help != null) return help; culture = culture.Parent; } } //We did not find the category walking up the culture hierarchy. Try looking // for the category in the default culture English. library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID)); help = library.GetCategoryHelp(category); if (help == null) throw new InvalidOperationException(SR.Format(SR.MissingCategory)); return help; } private string GetCategoryHelp(string category) { CategoryEntry entry = (CategoryEntry)CategoryTable[category]; if (entry == null) return null; return (string)HelpTable[entry.HelpIndex]; } internal static CategorySample GetCategorySample(string machine, string category) { PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID)); CategorySample sample = library.GetCategorySample(category); if (sample == null && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) { CultureInfo culture = CultureInfo.CurrentCulture; while (culture != CultureInfo.InvariantCulture) { library = GetPerformanceCounterLib(machine, culture); sample = library.GetCategorySample(category); if (sample != null) return sample; culture = culture.Parent; } } if (sample == null) throw new InvalidOperationException(SR.Format(SR.MissingCategory)); return sample; } private CategorySample GetCategorySample(string category) { CategoryEntry entry = (CategoryEntry)CategoryTable[category]; if (entry == null) return null; CategorySample sample = null; byte[] dataRef = GetPerformanceData(entry.NameIndex.ToString(CultureInfo.InvariantCulture)); if (dataRef == null) throw new InvalidOperationException(SR.Format(SR.CantReadCategory, category)); sample = new CategorySample(dataRef, entry, this); return sample; } internal static string[] GetCounters(string machine, string category) { PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID)); bool categoryExists = false; string[] counters = library.GetCounters(category, ref categoryExists); if (!categoryExists && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) { CultureInfo culture = CultureInfo.CurrentCulture; while (culture != CultureInfo.InvariantCulture) { library = GetPerformanceCounterLib(machine, culture); counters = library.GetCounters(category, ref categoryExists); if (categoryExists) return counters; culture = culture.Parent; } } if (!categoryExists) throw new InvalidOperationException(SR.Format(SR.MissingCategory)); return counters; } private string[] GetCounters(string category, ref bool categoryExists) { categoryExists = false; CategoryEntry entry = (CategoryEntry)CategoryTable[category]; if (entry == null) return null; else categoryExists = true; int index2 = 0; string[] counters = new string[entry.CounterIndexes.Length]; for (int index = 0; index < counters.Length; ++index) { int counterIndex = entry.CounterIndexes[index]; string counterName = (string)NameTable[counterIndex]; if (counterName != null && counterName != string.Empty) { counters[index2] = counterName; ++index2; } } //Lets adjust the array in case there were null entries if (index2 < counters.Length) { string[] adjustedCounters = new string[index2]; Array.Copy(counters, adjustedCounters, index2); counters = adjustedCounters; } return counters; } internal static string GetCounterHelp(string machine, string category, string counter) { PerformanceCounterLib library; bool categoryExists = false; string help; //First check the current culture for the counter. This will allow //PerformanceCounter.CounterHelp to return localized strings. if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) { CultureInfo culture = CultureInfo.CurrentCulture; while (culture != CultureInfo.InvariantCulture) { library = GetPerformanceCounterLib(machine, culture); help = library.GetCounterHelp(category, counter, ref categoryExists); if (categoryExists) return help; culture = culture.Parent; } } //We did not find the counter walking up the culture hierarchy. Try looking // for the counter in the default culture English. library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID)); help = library.GetCounterHelp(category, counter, ref categoryExists); if (!categoryExists) throw new InvalidOperationException(SR.Format(SR.MissingCategoryDetail, category)); return help; } private string GetCounterHelp(string category, string counter, ref bool categoryExists) { categoryExists = false; CategoryEntry entry = (CategoryEntry)CategoryTable[category]; if (entry == null) return null; else categoryExists = true; int helpIndex = -1; for (int index = 0; index < entry.CounterIndexes.Length; ++index) { int counterIndex = entry.CounterIndexes[index]; string counterName = (string)NameTable[counterIndex]; if (counterName == null) counterName = string.Empty; if (string.Equals(counterName, counter, StringComparison.OrdinalIgnoreCase)) { helpIndex = entry.HelpIndexes[index]; break; } } if (helpIndex == -1) throw new InvalidOperationException(SR.Format(SR.MissingCounter, counter)); string help = (string)HelpTable[helpIndex]; if (help == null) return string.Empty; else return help; } private static string[] GetLanguageIds() { RegistryKey libraryParentKey = null; string[] ids = Array.Empty<string>(); try { libraryParentKey = Registry.LocalMachine.OpenSubKey(PerflibPath); if (libraryParentKey != null) ids = libraryParentKey.GetSubKeyNames(); } finally { if (libraryParentKey != null) libraryParentKey.Close(); } return ids; } internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture) { string lcidString = culture.LCID.ToString("X3", CultureInfo.InvariantCulture); machineName = (machineName == "." ? ComputerName : machineName).ToLowerInvariant(); if (PerformanceCounterLib.s_libraryTable == null) { lock (InternalSyncObject) { if (PerformanceCounterLib.s_libraryTable == null) PerformanceCounterLib.s_libraryTable = new Hashtable(); } } string libraryKey = machineName + ":" + lcidString; if (PerformanceCounterLib.s_libraryTable.Contains(libraryKey)) return (PerformanceCounterLib)PerformanceCounterLib.s_libraryTable[libraryKey]; else { PerformanceCounterLib library = new PerformanceCounterLib(machineName, lcidString); PerformanceCounterLib.s_libraryTable[libraryKey] = library; return library; } } internal byte[] GetPerformanceData(string item) { if (_performanceMonitor == null) { lock (InternalSyncObject) { if (_performanceMonitor == null) _performanceMonitor = new PerformanceMonitor(_machineName); } } return _performanceMonitor.GetData(item); } private Hashtable GetStringTable(bool isHelp) { Hashtable stringTable; RegistryKey libraryKey; if (string.Equals(_machineName, ComputerName, StringComparison.OrdinalIgnoreCase)) libraryKey = Registry.PerformanceData; else { libraryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, _machineName); } try { string[] names = null; int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // In some stress situations, querying counter values from // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009 // often returns null/empty data back. We should build fault-tolerance logic to // make it more reliable because getting null back once doesn't necessarily mean // that the data is corrupted, most of the time we would get the data just fine // in subsequent tries. while (waitRetries > 0) { try { if (!isHelp) names = (string[])libraryKey.GetValue("Counter " + _perfLcid); else names = (string[])libraryKey.GetValue("Explain " + _perfLcid); if ((names == null) || (names.Length == 0)) { --waitRetries; if (waitSleep == 0) waitSleep = 10; else { System.Threading.Thread.Sleep(waitSleep); waitSleep *= 2; } } else break; } catch (IOException) { // RegistryKey throws if it can't find the value. We want to return an empty table // and throw a different exception higher up the stack. names = null; break; } catch (InvalidCastException) { // Unable to cast object of type 'System.Byte[]' to type 'System.String[]'. // this happens when the registry data store is corrupt and the type is not even REG_MULTI_SZ names = null; break; } } if (names == null) stringTable = new Hashtable(); else { stringTable = new Hashtable(names.Length / 2); for (int index = 0; index < (names.Length / 2); ++index) { string nameString = names[(index * 2) + 1]; if (nameString == null) nameString = string.Empty; int key; if (!Int32.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key)) { if (isHelp) { // Category Help Table throw new InvalidOperationException(SR.Format(SR.CategoryHelpCorrupt, names[index * 2])); } else { // Counter Name Table throw new InvalidOperationException(SR.Format(SR.CounterNameCorrupt, names[index * 2])); } } stringTable[key] = nameString; } } } finally { libraryKey.Close(); } return stringTable; } internal static bool IsCustomCategory(string machine, string category) { PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID)); if (library.IsCustomCategory(category)) return true; if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) { CultureInfo culture = CultureInfo.CurrentCulture; while (culture != CultureInfo.InvariantCulture) { library = GetPerformanceCounterLib(machine, culture); if (library.IsCustomCategory(category)) return true; culture = culture.Parent; } } return false; } internal static bool IsBaseCounter(int type) { return (type == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_BASE || type == Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_MULTI_BASE || type == Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_BASE || type == Interop.Kernel32.PerformanceCounterOptions.PERF_LARGE_RAW_BASE || type == Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_BASE); } private bool IsCustomCategory(string category) { PerformanceCounterCategoryType categoryType; return FindCustomCategory(category, out categoryType); } internal static PerformanceCounterCategoryType GetCategoryType(string machine, string category) { PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown; PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID)); if (!library.FindCustomCategory(category, out categoryType)) { if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) { CultureInfo culture = CultureInfo.CurrentCulture; while (culture != CultureInfo.InvariantCulture) { library = GetPerformanceCounterLib(machine, culture); if (library.FindCustomCategory(category, out categoryType)) return categoryType; culture = culture.Parent; } } } return categoryType; } internal static void RegisterCategory(string categoryName, PerformanceCounterCategoryType categoryType, string categoryHelp, CounterCreationDataCollection creationData) { try { bool iniRegistered = false; CreateRegistryEntry(categoryName, categoryType, creationData, ref iniRegistered); if (!iniRegistered) { string[] languageIds = GetLanguageIds(); CreateIniFile(categoryName, categoryHelp, creationData, languageIds); CreateSymbolFile(creationData); RegisterFiles(IniFilePath, false); } CloseAllTables(); CloseAllLibraries(); } finally { DeleteTemporaryFiles(); } } private static void RegisterFiles(string arg0, bool unregister) { Process p; ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.UseShellExecute = false; processStartInfo.CreateNoWindow = true; processStartInfo.ErrorDialog = false; processStartInfo.WindowStyle = ProcessWindowStyle.Hidden; processStartInfo.WorkingDirectory = Environment.SystemDirectory; if (unregister) processStartInfo.FileName = Environment.SystemDirectory + "\\unlodctr.exe"; else processStartInfo.FileName = Environment.SystemDirectory + "\\lodctr.exe"; int res = 0; try { processStartInfo.Arguments = "\"" + arg0 + "\""; p = Process.Start(processStartInfo); p.WaitForExit(); res = p.ExitCode; } finally { } if (res == Interop.Errors.ERROR_ACCESS_DENIED) { throw new UnauthorizedAccessException(SR.Format(SR.CantChangeCategoryRegistration, arg0)); } // Look at Q269225, unlodctr might return 2 when WMI is not installed. if (unregister && res == 2) res = 0; if (res != 0) throw SharedUtils.CreateSafeWin32Exception(res); } internal static void UnregisterCategory(string categoryName) { RegisterFiles(categoryName, true); DeleteRegistryEntry(categoryName); CloseAllTables(); CloseAllLibraries(); } } internal class PerformanceMonitor { private RegistryKey perfDataKey = null; private string machineName; internal PerformanceMonitor(string machineName) { this.machineName = machineName; Init(); } private void Init() { try { if (machineName != "." && !string.Equals(machineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase)) { perfDataKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, machineName); } else perfDataKey = Registry.PerformanceData; } catch (UnauthorizedAccessException) { // we need to do this for compatibility with v1.1 and v1.0. throw new Win32Exception(Interop.Errors.ERROR_ACCESS_DENIED); } catch (IOException e) { // we need to do this for compatibility with v1.1 and v1.0. throw new Win32Exception(Marshal.GetHRForException(e)); } } internal void Close() { if (perfDataKey != null) perfDataKey.Close(); perfDataKey = null; } // Win32 RegQueryValueEx for perf data could deadlock (for a Mutex) up to 2mins in some // scenarios before they detect it and exit gracefully. In the mean time, ERROR_BUSY, // ERROR_NOT_READY etc can be seen by other concurrent calls (which is the reason for the // wait loop and switch case below). We want to wait most certainly more than a 2min window. // The curent wait time of up to 10mins takes care of the known stress deadlock issues. In most // cases we wouldn't wait for more than 2mins anyways but in worst cases how much ever time // we wait may not be sufficient if the Win32 code keeps running into this deadlock again // and again. A condition very rare but possible in theory. We would get back to the user // in this case with InvalidOperationException after the wait time expires. internal byte[] GetData(string item) { int waitRetries = 17; //2^16*10ms == approximately 10mins int waitSleep = 0; byte[] data = null; int error = 0; // no need to revert here since we'll fall off the end of the method while (waitRetries > 0) { try { data = (byte[])perfDataKey.GetValue(item); return data; } catch (IOException e) { error = Marshal.GetHRForException(e); switch (error) { case Interop.Advapi32.RPCStatus.RPC_S_CALL_FAILED: case Interop.Errors.ERROR_INVALID_HANDLE: case Interop.Advapi32.RPCStatus.RPC_S_SERVER_UNAVAILABLE: Init(); goto case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT; case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT: case Interop.Errors.ERROR_NOT_READY: case Interop.Errors.ERROR_LOCK_FAILED: case Interop.Errors.ERROR_BUSY: --waitRetries; if (waitSleep == 0) { waitSleep = 10; } else { System.Threading.Thread.Sleep(waitSleep); waitSleep *= 2; } break; default: throw SharedUtils.CreateSafeWin32Exception(error); } } catch (InvalidCastException e) { throw new InvalidOperationException(SR.Format(SR.CounterDataCorrupt, perfDataKey.ToString()), e); } } throw SharedUtils.CreateSafeWin32Exception(error); } } internal class CategoryEntry { internal int NameIndex; internal int HelpIndex; internal int[] CounterIndexes; internal int[] HelpIndexes; internal CategoryEntry(Interop.Advapi32.PERF_OBJECT_TYPE perfObject) { NameIndex = perfObject.ObjectNameTitleIndex; HelpIndex = perfObject.ObjectHelpTitleIndex; CounterIndexes = new int[perfObject.NumCounters]; HelpIndexes = new int[perfObject.NumCounters]; } } internal class CategorySample { internal readonly long _systemFrequency; internal readonly long _timeStamp; internal readonly long _timeStamp100nSec; internal readonly long _counterFrequency; internal readonly long _counterTimeStamp; internal Hashtable _counterTable; internal Hashtable _instanceNameTable; internal bool _isMultiInstance; private CategoryEntry _entry; private PerformanceCounterLib _library; internal unsafe CategorySample(byte[] data, CategoryEntry entry, PerformanceCounterLib library) { _entry = entry; _library = library; int categoryIndex = entry.NameIndex; Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK(); fixed (byte* dataPtr = data) { IntPtr dataRef = new IntPtr((void*)dataPtr); Marshal.PtrToStructure(dataRef, dataBlock); _systemFrequency = dataBlock.PerfFreq; _timeStamp = dataBlock.PerfTime; _timeStamp100nSec = dataBlock.PerfTime100nSec; dataRef = (IntPtr)((long)dataRef + dataBlock.HeaderLength); int numPerfObjects = dataBlock.NumObjectTypes; if (numPerfObjects == 0) { _counterTable = new Hashtable(); _instanceNameTable = new Hashtable(StringComparer.OrdinalIgnoreCase); return; } //Need to find the right category, GetPerformanceData might return //several of them. Interop.Advapi32.PERF_OBJECT_TYPE perfObject = null; bool foundCategory = false; for (int index = 0; index < numPerfObjects; index++) { perfObject = new Interop.Advapi32.PERF_OBJECT_TYPE(); Marshal.PtrToStructure(dataRef, perfObject); if (perfObject.ObjectNameTitleIndex == categoryIndex) { foundCategory = true; break; } dataRef = (IntPtr)((long)dataRef + perfObject.TotalByteLength); } if (!foundCategory) throw new InvalidOperationException(SR.Format(SR.CantReadCategoryIndex, categoryIndex.ToString(CultureInfo.CurrentCulture))); _counterFrequency = perfObject.PerfFreq; _counterTimeStamp = perfObject.PerfTime; int counterNumber = perfObject.NumCounters; int instanceNumber = perfObject.NumInstances; if (instanceNumber == -1) _isMultiInstance = false; else _isMultiInstance = true; // Move pointer forward to end of PERF_OBJECT_TYPE dataRef = (IntPtr)((long)dataRef + perfObject.HeaderLength); CounterDefinitionSample[] samples = new CounterDefinitionSample[counterNumber]; _counterTable = new Hashtable(counterNumber); for (int index = 0; index < samples.Length; ++index) { Interop.Advapi32.PERF_COUNTER_DEFINITION perfCounter = new Interop.Advapi32.PERF_COUNTER_DEFINITION(); Marshal.PtrToStructure(dataRef, perfCounter); samples[index] = new CounterDefinitionSample(perfCounter, this, instanceNumber); dataRef = (IntPtr)((long)dataRef + perfCounter.ByteLength); int currentSampleType = samples[index]._counterType; if (!PerformanceCounterLib.IsBaseCounter(currentSampleType)) { // We'll put only non-base counters in the table. if (currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_COUNTER_NODATA) _counterTable[samples[index]._nameIndex] = samples[index]; } else { // it's a base counter, try to hook it up to the main counter. Debug.Assert(index > 0, "Index > 0 because base counters should never be at index 0"); if (index > 0) samples[index - 1]._baseCounterDefinitionSample = samples[index]; } } // now set up the InstanceNameTable. if (!_isMultiInstance) { _instanceNameTable = new Hashtable(1, StringComparer.OrdinalIgnoreCase); _instanceNameTable[PerformanceCounterLib.SingleInstanceName] = 0; for (int index = 0; index < samples.Length; ++index) { samples[index].SetInstanceValue(0, dataRef); } } else { string[] parentInstanceNames = null; _instanceNameTable = new Hashtable(instanceNumber, StringComparer.OrdinalIgnoreCase); for (int i = 0; i < instanceNumber; i++) { Interop.Advapi32.PERF_INSTANCE_DEFINITION perfInstance = new Interop.Advapi32.PERF_INSTANCE_DEFINITION(); Marshal.PtrToStructure(dataRef, perfInstance); if (perfInstance.ParentObjectTitleIndex > 0 && parentInstanceNames == null) parentInstanceNames = GetInstanceNamesFromIndex(perfInstance.ParentObjectTitleIndex); string instanceName; if (parentInstanceNames != null && perfInstance.ParentObjectInstance >= 0 && perfInstance.ParentObjectInstance < parentInstanceNames.Length - 1) instanceName = parentInstanceNames[perfInstance.ParentObjectInstance] + "/" + Marshal.PtrToStringUni((IntPtr)((long)dataRef + perfInstance.NameOffset)); else instanceName = Marshal.PtrToStringUni((IntPtr)((long)dataRef + perfInstance.NameOffset)); //In some cases instance names are not unique (Process), same as perfmon //generate a unique name. string newInstanceName = instanceName; int newInstanceNumber = 1; while (true) { if (!_instanceNameTable.ContainsKey(newInstanceName)) { _instanceNameTable[newInstanceName] = i; break; } else { newInstanceName = instanceName + "#" + newInstanceNumber.ToString(CultureInfo.InvariantCulture); ++newInstanceNumber; } } dataRef = (IntPtr)((long)dataRef + perfInstance.ByteLength); for (int index = 0; index < samples.Length; ++index) samples[index].SetInstanceValue(i, dataRef); dataRef = (IntPtr)((long)dataRef + Marshal.ReadInt32(dataRef)); } } } } internal unsafe string[] GetInstanceNamesFromIndex(int categoryIndex) { byte[] data = _library.GetPerformanceData(categoryIndex.ToString(CultureInfo.InvariantCulture)); fixed (byte* dataPtr = data) { IntPtr dataRef = new IntPtr((void*)dataPtr); Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK(); Marshal.PtrToStructure(dataRef, dataBlock); dataRef = (IntPtr)((long)dataRef + dataBlock.HeaderLength); int numPerfObjects = dataBlock.NumObjectTypes; Interop.Advapi32.PERF_OBJECT_TYPE perfObject = null; bool foundCategory = false; for (int index = 0; index < numPerfObjects; index++) { perfObject = new Interop.Advapi32.PERF_OBJECT_TYPE(); Marshal.PtrToStructure(dataRef, perfObject); if (perfObject.ObjectNameTitleIndex == categoryIndex) { foundCategory = true; break; } dataRef = (IntPtr)((long)dataRef + perfObject.TotalByteLength); } if (!foundCategory) return Array.Empty<string>(); int counterNumber = perfObject.NumCounters; int instanceNumber = perfObject.NumInstances; dataRef = (IntPtr)((long)dataRef + perfObject.HeaderLength); if (instanceNumber == -1) return Array.Empty<string>(); CounterDefinitionSample[] samples = new CounterDefinitionSample[counterNumber]; for (int index = 0; index < samples.Length; ++index) { Interop.Advapi32.PERF_COUNTER_DEFINITION perfCounter = new Interop.Advapi32.PERF_COUNTER_DEFINITION(); Marshal.PtrToStructure(dataRef, perfCounter); dataRef = (IntPtr)((long)dataRef + perfCounter.ByteLength); } string[] instanceNames = new string[instanceNumber]; for (int i = 0; i < instanceNumber; i++) { Interop.Advapi32.PERF_INSTANCE_DEFINITION perfInstance = new Interop.Advapi32.PERF_INSTANCE_DEFINITION(); Marshal.PtrToStructure(dataRef, perfInstance); instanceNames[i] = Marshal.PtrToStringUni((IntPtr)((long)dataRef + perfInstance.NameOffset)); dataRef = (IntPtr)((long)dataRef + perfInstance.ByteLength); dataRef = (IntPtr)((long)dataRef + Marshal.ReadInt32(dataRef)); } return instanceNames; } } internal CounterDefinitionSample GetCounterDefinitionSample(string counter) { for (int index = 0; index < _entry.CounterIndexes.Length; ++index) { int counterIndex = _entry.CounterIndexes[index]; string counterName = (string)_library.NameTable[counterIndex]; if (counterName != null) { if (string.Equals(counterName, counter, StringComparison.OrdinalIgnoreCase)) { CounterDefinitionSample sample = (CounterDefinitionSample)_counterTable[counterIndex]; if (sample == null) { //This is a base counter and has not been added to the table foreach (CounterDefinitionSample multiSample in _counterTable.Values) { if (multiSample._baseCounterDefinitionSample != null && multiSample._baseCounterDefinitionSample._nameIndex == counterIndex) return multiSample._baseCounterDefinitionSample; } throw new InvalidOperationException(SR.Format(SR.CounterLayout)); } return sample; } } } throw new InvalidOperationException(SR.Format(SR.CantReadCounter, counter)); } internal InstanceDataCollectionCollection ReadCategory() { #pragma warning disable 618 InstanceDataCollectionCollection data = new InstanceDataCollectionCollection(); #pragma warning restore 618 for (int index = 0; index < _entry.CounterIndexes.Length; ++index) { int counterIndex = _entry.CounterIndexes[index]; string name = (string)_library.NameTable[counterIndex]; if (name != null && name != string.Empty) { CounterDefinitionSample sample = (CounterDefinitionSample)_counterTable[counterIndex]; if (sample != null) //If the current index refers to a counter base, //the sample will be null data.Add(name, sample.ReadInstanceData(name)); } } return data; } } internal class CounterDefinitionSample { internal readonly int _nameIndex; internal readonly int _counterType; internal CounterDefinitionSample _baseCounterDefinitionSample; private readonly int _size; private readonly int _offset; private long[] _instanceValues; private CategorySample _categorySample; internal CounterDefinitionSample(Interop.Advapi32.PERF_COUNTER_DEFINITION perfCounter, CategorySample categorySample, int instanceNumber) { _nameIndex = perfCounter.CounterNameTitleIndex; _counterType = perfCounter.CounterType; _offset = perfCounter.CounterOffset; _size = perfCounter.CounterSize; if (instanceNumber == -1) { _instanceValues = new long[1]; } else _instanceValues = new long[instanceNumber]; _categorySample = categorySample; } private long ReadValue(IntPtr pointer) { if (_size == 4) { return (long)(uint)Marshal.ReadInt32((IntPtr)((long)pointer + _offset)); } else if (_size == 8) { return (long)Marshal.ReadInt64((IntPtr)((long)pointer + _offset)); } return -1; } internal CounterSample GetInstanceValue(string instanceName) { if (!_categorySample._instanceNameTable.ContainsKey(instanceName)) { // Our native dll truncates instance names to 128 characters. If we can't find the instance // with the full name, try truncating to 128 characters. if (instanceName.Length > SharedPerformanceCounter.InstanceNameMaxLength) instanceName = instanceName.Substring(0, SharedPerformanceCounter.InstanceNameMaxLength); if (!_categorySample._instanceNameTable.ContainsKey(instanceName)) throw new InvalidOperationException(SR.Format(SR.CantReadInstance, instanceName)); } int index = (int)_categorySample._instanceNameTable[instanceName]; long rawValue = _instanceValues[index]; long baseValue = 0; if (_baseCounterDefinitionSample != null) { CategorySample baseCategorySample = _baseCounterDefinitionSample._categorySample; int baseIndex = (int)baseCategorySample._instanceNameTable[instanceName]; baseValue = _baseCounterDefinitionSample._instanceValues[baseIndex]; } return new CounterSample(rawValue, baseValue, _categorySample._counterFrequency, _categorySample._systemFrequency, _categorySample._timeStamp, _categorySample._timeStamp100nSec, (PerformanceCounterType)_counterType, _categorySample._counterTimeStamp); } internal InstanceDataCollection ReadInstanceData(string counterName) { #pragma warning disable 618 InstanceDataCollection data = new InstanceDataCollection(counterName); #pragma warning restore 618 string[] keys = new string[_categorySample._instanceNameTable.Count]; _categorySample._instanceNameTable.Keys.CopyTo(keys, 0); int[] indexes = new int[_categorySample._instanceNameTable.Count]; _categorySample._instanceNameTable.Values.CopyTo(indexes, 0); for (int index = 0; index < keys.Length; ++index) { long baseValue = 0; if (_baseCounterDefinitionSample != null) { CategorySample baseCategorySample = _baseCounterDefinitionSample._categorySample; int baseIndex = (int)baseCategorySample._instanceNameTable[keys[index]]; baseValue = _baseCounterDefinitionSample._instanceValues[baseIndex]; } CounterSample sample = new CounterSample(_instanceValues[indexes[index]], baseValue, _categorySample._counterFrequency, _categorySample._systemFrequency, _categorySample._timeStamp, _categorySample._timeStamp100nSec, (PerformanceCounterType)_counterType, _categorySample._counterTimeStamp); data.Add(keys[index], new InstanceData(keys[index], sample)); } return data; } internal CounterSample GetSingleValue() { long rawValue = _instanceValues[0]; long baseValue = 0; if (_baseCounterDefinitionSample != null) baseValue = _baseCounterDefinitionSample._instanceValues[0]; return new CounterSample(rawValue, baseValue, _categorySample._counterFrequency, _categorySample._systemFrequency, _categorySample._timeStamp, _categorySample._timeStamp100nSec, (PerformanceCounterType)_counterType, _categorySample._counterTimeStamp); } internal void SetInstanceValue(int index, IntPtr dataRef) { long rawValue = ReadValue(dataRef); _instanceValues[index] = rawValue; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; //using System.Linq; using System.Text; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; namespace System.Text { // Summary: // Converts a sequence of encoded bytes into a set of characters. public abstract class Decoder { #if false // Summary: // Initializes a new instance of the System.Text.Decoder class. protected Decoder(); // Summary: // Gets or sets a System.Text.DecoderFallback object for the current System.Text.Decoder // object. // // Returns: // A System.Text.DecoderFallback object. // // Exceptions: // System.ArgumentNullException: // The value in a set operation is null (Nothing). // // System.ArgumentException: // A new value cannot be assigned in a set operation because the current System.Text.DecoderFallbackBuffer // object contains data that has not been decoded yet. public DecoderFallback Fallback { get; set; } // // Summary: // Gets the System.Text.DecoderFallbackBuffer object associated with the current // System.Text.Decoder object. // // Returns: // A System.Text.DecoderFallbackBuffer object. public DecoderFallbackBuffer FallbackBuffer { get; } // Summary: // Converts a buffer of encoded bytes to Unicode characters and stores the result // in another buffer. // // Parameters: // bytes: // The address of a buffer that contains the byte sequences to convert. // // byteCount: // The number of bytes in bytes to convert. // // chars: // The address of a buffer to store the converted characters. // // charCount: // The maximum number of characters in chars to use in the conversion. // // flush: // true to indicate no further data is to be converted; otherwise, false. // // bytesUsed: // When this method returns, contains the number of bytes that were produced // by the conversion. This parameter is passed uninitialized. // // charsUsed: // When this method returns, contains the number of characters from chars that // were used in the conversion. This parameter is passed uninitialized. // // completed: // When this method returns, contains true if all the characters specified by // byteCount were converted; otherwise, false. This parameter is passed uninitialized. // // Exceptions: // System.ArgumentNullException: // chars or bytes is null (Nothing). // // System.ArgumentOutOfRangeException: // charCount or byteCount is less than zero. // // System.ArgumentException: // The output buffer is too small to contain any of the converted input. The // output buffer should be greater than or equal to the size indicated by the // Overload:System.Text.Decoder.GetCharCount method. // // System.Text.DecoderFallbackException: // A fallback occurred (see Understanding Encodings for fuller explanation)-and-System.Text.Decoder.Fallback // is set to System.Text.DecoderExceptionFallback. unsafe public virtual void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed); // // Summary: // Converts an array of encoded bytes to Unicode characters and stores the result // in a byte array. // // Parameters: // bytes: // A byte array to convert. // // byteIndex: // The first element of bytes to convert. // // byteCount: // The number of elements of bytes to convert. // // chars: // An array to store the converted characters. // // charIndex: // The first element of chars in which data is stored. // // charCount: // The maximum number of elements of chars to use in the conversion. // // flush: // true to indicate that no further data is to be converted; otherwise, false. // // bytesUsed: // When this method returns, contains the number of bytes that were used in // the conversion. This parameter is passed uninitialized. // // charsUsed: // When this method returns, contains the number of characters from chars that // were produced by the conversion. This parameter is passed uninitialized. // // completed: // When this method returns, contains true if all the characters specified by // byteCount were converted; otherwise, false. This parameter is passed uninitialized. // // Exceptions: // System.ArgumentNullException: // chars or bytes is null (Nothing). // // System.ArgumentOutOfRangeException: // charIndex, charCount, byteIndex, or byteCount is less than zero.-or-The length // of chars - charIndex is less than charCount.-or-The length of bytes - byteIndex // is less than byteCount. // // System.ArgumentException: // The output buffer is too small to contain any of the converted input. The // output buffer should be greater than or equal to the size indicated by the // Overload:System.Text.Decoder.GetCharCount method. // // System.Text.DecoderFallbackException: // A fallback occurred (see Understanding Encodings for fuller explanation)-and-System.Text.Decoder.Fallback // is set to System.Text.DecoderExceptionFallback. public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed); // // Summary: // When overridden in a derived class, calculates the number of characters produced // by decoding a sequence of bytes starting at the specified byte pointer. A // parameter indicates whether to clear the internal state of the decoder after // the calculation. // // Parameters: // bytes: // A pointer to the first byte to decode. // // count: // The number of bytes to decode. // // flush: // true to simulate clearing the internal state of the encoder after the calculation; // otherwise, false. // // Returns: // The number of characters produced by decoding the specified sequence of bytes // and any bytes in the internal buffer. // // Exceptions: // System.ArgumentNullException: // bytes is null (Nothing in Visual Basic .NET). // // System.ArgumentOutOfRangeException: // count is less than zero. // // System.Text.DecoderFallbackException: // A fallback occurred (see Understanding Encodings for fuller explanation)-and-System.Text.Decoder.Fallback // is set to System.Text.DecoderExceptionFallback. unsafe public virtual int GetCharCount(byte* bytes, int count, bool flush); // // Summary: // When overridden in a derived class, calculates the number of characters produced // by decoding a sequence of bytes from the specified byte array. // // Parameters: // bytes: // The byte array containing the sequence of bytes to decode. // // index: // The index of the first byte to decode. // // count: // The number of bytes to decode. // // Returns: // The number of characters produced by decoding the specified sequence of bytes // and any bytes in the internal buffer. // // Exceptions: // System.ArgumentNullException: // bytes is null (Nothing). // // System.ArgumentOutOfRangeException: // index or count is less than zero.-or- index and count do not denote a valid // range in bytes. // // System.Text.DecoderFallbackException: // A fallback occurred (see Understanding Encodings for fuller explanation)-and-System.Text.Decoder.Fallback // is set to System.Text.DecoderExceptionFallback. public abstract int GetCharCount(byte[] bytes, int index, int count); // // Summary: // When overridden in a derived class, calculates the number of characters produced // by decoding a sequence of bytes from the specified byte array. A parameter // indicates whether to clear the internal state of the decoder after the calculation. // // Parameters: // bytes: // The byte array containing the sequence of bytes to decode. // // index: // The index of the first byte to decode. // // count: // The number of bytes to decode. // // flush: // true to simulate clearing the internal state of the encoder after the calculation; // otherwise, false. // // Returns: // The number of characters produced by decoding the specified sequence of bytes // and any bytes in the internal buffer. // // Exceptions: // System.ArgumentNullException: // bytes is null (Nothing). // // System.ArgumentOutOfRangeException: // index or count is less than zero.-or- index and count do not denote a valid // range in bytes. // // System.Text.DecoderFallbackException: // A fallback occurred (see Understanding Encodings for fuller explanation)-and-System.Text.Decoder.Fallback // is set to System.Text.DecoderExceptionFallback. public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush); // // Summary: // When overridden in a derived class, decodes a sequence of bytes starting // at the specified byte pointer and any bytes in the internal buffer into a // set of characters that are stored starting at the specified character pointer. // A parameter indicates whether to clear the internal state of the decoder // after the conversion. // // Parameters: // bytes: // A pointer to the first byte to decode. // // byteCount: // The number of bytes to decode. // // chars: // A pointer to the location at which to start writing the resulting set of // characters. // // charCount: // The maximum number of characters to write. // // flush: // true to clear the internal state of the decoder after the conversion; otherwise, // false. // // Returns: // The actual number of characters written at the location indicated by the // chars parameter. // // Exceptions: // System.ArgumentNullException: // bytes is null (Nothing).-or- chars is null (Nothing). // // System.ArgumentOutOfRangeException: // byteCount or charCount is less than zero. // // System.ArgumentException: // charCount is less than the resulting number of characters. // // System.Text.DecoderFallbackException: // A fallback occurred (see Understanding Encodings for fuller explanation)-and-System.Text.Decoder.Fallback // is set to System.Text.DecoderExceptionFallback. unsafe public virtual int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush); // // Summary: // When overridden in a derived class, decodes a sequence of bytes from the // specified byte array and any bytes in the internal buffer into the specified // character array. // // Parameters: // bytes: // The byte array containing the sequence of bytes to decode. // // byteIndex: // The index of the first byte to decode. // // byteCount: // The number of bytes to decode. // // chars: // The character array to contain the resulting set of characters. // // charIndex: // The index at which to start writing the resulting set of characters. // // Returns: // The actual number of characters written into chars. // // Exceptions: // System.ArgumentNullException: // bytes is null (Nothing).-or- chars is null (Nothing). // // System.ArgumentOutOfRangeException: // byteIndex or byteCount or charIndex is less than zero.-or- byteindex and // byteCount do not denote a valid range in bytes.-or- charIndex is not a valid // index in chars. // // System.ArgumentException: // chars does not have enough capacity from charIndex to the end of the array // to accommodate the resulting characters. // // System.Text.DecoderFallbackException: // A fallback occurred (see Understanding Encodings for fuller explanation)-and-System.Text.Decoder.Fallback // is set to System.Text.DecoderExceptionFallback. public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); // // Summary: // When overridden in a derived class, decodes a sequence of bytes from the // specified byte array and any bytes in the internal buffer into the specified // character array. A parameter indicates whether to clear the internal state // of the decoder after the conversion. // // Parameters: // bytes: // The byte array containing the sequence of bytes to decode. // // byteIndex: // The index of the first byte to decode. // // byteCount: // The number of bytes to decode. // // chars: // The character array to contain the resulting set of characters. // // charIndex: // The index at which to start writing the resulting set of characters. // // flush: // true to clear the internal state of the decoder after the conversion; otherwise, // false. // // Returns: // The actual number of characters written into the chars parameter. // // Exceptions: // System.ArgumentNullException: // bytes is null (Nothing).-or- chars is null (Nothing). // // System.ArgumentOutOfRangeException: // byteIndex or byteCount or charIndex is less than zero.-or- byteindex and // byteCount do not denote a valid range in bytes.-or- charIndex is not a valid // index in chars. // // System.ArgumentException: // chars does not have enough capacity from charIndex to the end of the array // to accommodate the resulting characters. // // System.Text.DecoderFallbackException: // A fallback occurred (see Understanding Encodings for fuller explanation)-and-System.Text.Decoder.Fallback // is set to System.Text.DecoderExceptionFallback. public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush); // // Summary: // When overridden in a derived class, sets the decoder back to its initial // state. public virtual void Reset(); #endif } }
// /* // * Copyright (c) 2016, Alachisoft. All Rights Reserved. // * // * Licensed under the Apache License, Version 2.0 (the "License"); // * you may not use this file except in compliance with the License. // * You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // */ using System; using System.Text; #if JAVA using Alachisoft.TayzGrid.Runtime.Serialization; #else using Alachisoft.NosDB.Common.Serialization; #endif #if JAVA using Alachisoft.TayzGrid.Runtime.Serialization.IO; #else using Alachisoft.NosDB.Common.Serialization.IO; #endif using System.Collections; using Alachisoft.NosDB.Common.Net; using System.Runtime.Serialization.Formatters.Binary; using System.IO; namespace Alachisoft.NosDB.Common.DataStructures { /// <summary> /// Contains new hashmap and related information for client /// </summary> public sealed class NewHashmap : ICompactSerializable { private long _lastViewId; private Hashtable _map; private ArrayList _members; private byte[] _buffer; private bool _updateMap = false; /// <summary> /// Default constructor /// </summary> public NewHashmap() { } public NewHashmap(long lastViewid, Hashtable map, ArrayList members) { this._lastViewId = lastViewid; this._map = map; this._members = new ArrayList(members.Count); foreach (Address address in members) { this._members.Add(address.IpAddress.ToString()); } } /// <summary> /// Last view id that was published /// </summary> public long LastViewId { get { return this._lastViewId; } } /// <summary> /// New hash map /// </summary> public Hashtable Map { get { return this._map; } } /// <summary> /// Just change the view id /// </summary> public bool UpdateMap { get { return _updateMap; } set { _updateMap = value; } } /// <summary> /// List of server members (string representation of IP addresses) /// </summary> public ArrayList Members { get { return this._members; } } /// <summary> /// Returned the serialized object of NewHashmap /// </summary> public byte[] Buffer { get { return this._buffer; } } /// <summary> /// Serialize NewHashmap /// </summary> /// <param name="instance"></param> /// <param name="serializationContext">Serialization context used to serialize the object</param> public static void Serialize(NewHashmap instance, string serializationContext, bool updateClientMap) { Hashtable mapInfo = null; if (instance != null) { mapInfo = new Hashtable(); mapInfo.Add("ViewId", instance._lastViewId); mapInfo.Add("Members", instance._members); mapInfo.Add("Map", instance._map); mapInfo.Add("UpdateMap", updateClientMap); BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, mapInfo); instance._buffer = stream.ToArray(); } //this._buffer = CompactBinaryFormatter.ToByteBuffer(this, serializationContext); } /// <summary> /// Deserialize NewHashmap /// </summary> /// <param name="serializationContext"></param> /// <returns></returns> public static NewHashmap Deserialize(byte[] buffer, string serializationContext) { NewHashmap hashmap = null; if (buffer != null && buffer.Length > 0) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(buffer); Hashtable map = formatter.Deserialize(stream) as Hashtable; if (map != null) { hashmap = new NewHashmap(); hashmap._lastViewId = (long)map["ViewId"]; hashmap._members = (ArrayList)map["Members"]; hashmap._map = (Hashtable)map["Map"]; hashmap._updateMap = (map["UpdateMap"] != null) ? (bool)map["UpdateMap"] : false; } } return hashmap; } #region ICompactSerializable Members /// <summary> /// Deserialize the object /// </summary> /// <param name="reader"></param> public void Deserialize(CompactReader reader) { this._lastViewId = reader.ReadInt64(); this._members = reader.ReadObject() as ArrayList; this._map = reader.ReadObject() as Hashtable; this._updateMap = reader.ReadBoolean(); } /// <summary> /// Serialize the object /// </summary> /// <param name="writer"></param> public void Serialize(CompactWriter writer) { writer.Write(this._lastViewId); writer.WriteObject(this._members); writer.WriteObject(this._map); writer.Write(this._updateMap); } #endregion public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("{ ("); builder.Append(this._lastViewId); builder.Append(") "); builder.Append("["); for (int i = 0; i < this.Members.Count; i++) { builder.Append(this.Members[i]); if (i < (this.Members.Count - 1)) { builder.Append(","); } } builder.Append("] }"); return builder.ToString(); } } }
using System.Linq; using NakedObjects.Boot; using NakedObjects.Core.NakedObjectsSystem; using NakedObjects.EntityObjectStore; using NakedObjects.Services; using NakedObjects.Xat; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Data.Entity; using Cluster.Documents.Impl; using Cluster.Documents.Api; using Cluster.Users.Mock; using Cluster.System.Mock; using System; using Helpers; namespace Cluster.Documents.Test { [TestClass()] public class DocumentsXAT : ClusterXAT<DocumentsTestDbContext, DocumentsFixture> { #region Run configuration //Set up the properties in this region exactly the same way as in your Run class protected override IServicesInstaller MenuServices { get { return new ServicesInstaller( new SimpleRepository<Note>(), new SimpleRepository<SimpleHolder>(), new SimpleRepository<DocumentWithFileAttachment>(), new DocumentService(), new PolymorphicNavigator(), new MockUserService(), new FixedClock(new DateTime(2000, 1, 1))); } } protected override IFixturesInstaller Fixtures { get { return new FixturesInstaller( new MockUsersFixture(), new DocumentsFixture() ); } } #endregion #region Initialize and Cleanup [TestInitialize()] public void Initialize() { InitializeNakedObjectsFramework(); // Use e.g. DatabaseUtils.RestoreDatabase to revert database before each test (or within a [ClassInitialize()] method). } [TestCleanup()] public void Cleanup() { CleanupNakedObjectsFramework(); } #endregion [TestMethod()] public virtual void RecentDocumentsAssociatedWithHolder() { var holder = GetTestService("Simple Holders").GetAction("Find By Key").InvokeReturnObject(2); holder.AssertIsType(typeof(SimpleHolder)); var newNote = holder.GetAction("Add Note", "Documents").InvokeReturnObject(holder); var text = newNote.GetPropertyByName("Text").SetValue("Foo"); newNote.Save(); var recent = holder.GetAction("Recent Documents", "Documents").InvokeReturnCollection(holder); recent.AssertCountIs(1); var doc = recent.ElementAt(0); doc.AssertIsType(typeof(Note)); } [TestMethod()] public virtual void FindDocumentsAssociatedWithHolder() { var holder = GetTestService("Simple Holders").GetAction("Find By Key").InvokeReturnObject(3); holder.AssertIsType(typeof(SimpleHolder)); var newNote = holder.GetAction("Add Note", "Documents").InvokeReturnObject(holder); var text = newNote.GetPropertyByName("Text").SetValue("Foo"); newNote.Save(); var recent = holder.GetAction("Find Documents", "Documents").InvokeReturnCollection(holder, DocumentType.Note, null, null, null, null); recent.AssertCountIs(1); var doc = recent.ElementAt(0); doc.AssertIsType(typeof(Note)); } #region Notes [TestMethod] public void PersistedNote() { SetUser("Richard"); var note = GetTestService("Notes").GetAction("Find By Key").InvokeReturnObject(1); note.GetPropertyByName("Text").AssertIsUnmodifiable().AssertValueIsEqual("Note1\nTest, 01/01/2000 00:00:00"); note.GetPropertyByName("Id").AssertIsInvisible(); note.GetPropertyByName("Creating Holder").AssertIsInvisible(); note.GetPropertyByName("Holder Links").AssertIsInvisible(); note.GetPropertyByName("Status").AssertIsUnmodifiable().AssertValueIsEqual("Active"); note.GetPropertyByName("User").AssertIsVisible().AssertIsUnmodifiable().AssertTitleIsEqual("Test"); note.GetPropertyByName("Last Modified").AssertIsVisible().AssertIsUnmodifiable(); } [TestMethod()] public virtual void AddNoteToHolderWhereNonePrevious() { var holder = GetTestService("Simple Holders").GetAction("Find By Key").InvokeReturnObject(6); holder.AssertIsType(typeof(SimpleHolder)).AssertIsPersistent(); var newNote = holder.GetAction("Add Note", "Documents").InvokeReturnObject(holder); newNote.AssertIsType(typeof(Note)).AssertIsTransient().AssertTitleEquals("Notes"); var text = newNote.GetPropertyByName("Text"); text.AssertIsEmpty().AssertIsMandatory(); text.SetValue("Foo"); var userName = newNote.GetPropertyByName("User"); userName.AssertIsInvisible(); var timeStamp = newNote.GetPropertyByName("Last Modified"); timeStamp.AssertIsUnmodifiable(); newNote.Save(); newNote.AssertTitleEquals("Notes"); timeStamp.AssertIsVisible().AssertIsNotEmpty(); userName.AssertIsVisible().AssertValueIsEqual("Test"); var links = newNote.GetPropertyByName("Holder Links").AssertIsInvisible(); var link = links.ContentAsCollection.AssertCountIs(1).ElementAt(0); Assert.AreEqual(holder, link.GetPropertyByName("Associated Role Object").ContentAsObject); } [TestMethod()] public virtual void AddNoteOntoPrevious() { var holder = GetTestService("Simple Holders").GetAction("Find By Key").InvokeReturnObject(4); holder.AssertIsType(typeof(SimpleHolder)); var newNote = holder.GetAction("Add Note", "Documents").InvokeReturnObject(holder); var text = newNote.GetPropertyByName("Text").SetValue("Foo"); newNote.Save(); var oldNote = holder.GetAction("Add Note", "Documents").InvokeReturnObject(holder); oldNote.AssertIsPersistent(); text = oldNote.GetPropertyByName("Text").AssertIsUnmodifiable(); var lines = text.Title.Split('\n'); Assert.AreEqual(2, lines.Count()); Assert.AreEqual("Foo", lines[0]); Assert.IsTrue(lines[1].StartsWith("Test,")); oldNote.GetAction("Add To Note").AssertIsEnabled().InvokeReturnObject("Bar"); lines = text.Title.Split('\n'); Assert.AreEqual(5, lines.Count()); Assert.AreEqual("", lines[2]); Assert.AreEqual("Bar", lines[3]); Assert.IsTrue(lines[4].StartsWith("Test,")); oldNote.GetAction("Add To Note").AssertIsEnabled().InvokeReturnObject("Yon"); lines = text.Title.Split('\n'); Assert.AreEqual(8, lines.Count()); Assert.AreEqual("", lines[5]); Assert.AreEqual("Yon", lines[6]); Assert.IsTrue(lines[7].StartsWith("Test,")); } [TestMethod] public void FinishThisNoteAndStartANewOne() { var holder = GetTestService("Simple Holders").GetAction("Find By Key").InvokeReturnObject(5); var note = holder.GetAction("Add Note", "Documents").InvokeReturnObject(holder); var text = note.GetPropertyByName("Text").SetValue("Foo"); note.Save(); var status = note.GetPropertyByName("Status"); status.AssertIsUnmodifiable().AssertValueIsEqual("Active"); var addToNote = note.GetAction("Add To Note").AssertIsEnabled(); var finish = note.GetAction("Finish This Note").AssertIsEnabled(); finish.InvokeReturnObject(); status.AssertValueIsEqual("Finished"); addToNote.AssertIsDisabled(); finish.AssertIsInvisible(); note = holder.GetAction("Add Note", "Documents").InvokeReturnObject(holder); note.AssertIsTransient(); } #endregion #region File Attachments [TestMethod] public void PersistedFA() { var fa = GetTestService("Document With File Attachments").GetAction("All Instances").InvokeReturnCollection().ElementAt(0); fa.AssertIsType(typeof(DocumentWithFileAttachment)); fa.GetPropertyByName("Description").AssertIsModifiable().AssertValueIsEqual("Foo"); var att = fa.GetPropertyByName("Attachment"); att.AssertTitleIsEqual("TextFile1.txt"); } [TestMethod()] public virtual void AddFileAttachment() { var holder = GetTestService("Simple Holders").GetAction("Find By Key").InvokeReturnObject(1); holder.AssertIsType(typeof(SimpleHolder)); var add = holder.GetAction("Add File Attachment", "Documents"); add.Parameters[0].AssertIsNamed("Holder").AssertIsMandatory(); add.Parameters[1].AssertIsNamed("File").AssertIsMandatory(); add.Parameters[2].AssertIsNamed("Description").AssertIsOptional(); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedRegionUrlMapsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<RegionUrlMaps.RegionUrlMapsClient> mockGrpcClient = new moq::Mock<RegionUrlMaps.RegionUrlMapsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionUrlMapRequest request = new GetRegionUrlMapRequest { Region = "regionedb20d96", Project = "projectaa6ff846", UrlMap = "url_map3ccdbf57", }; UrlMap expectedResponse = new UrlMap { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", Tests = { new UrlMapTest(), }, Region = "regionedb20d96", Fingerprint = "fingerprint009e6052", PathMatchers = { new PathMatcher(), }, HostRules = { new HostRule(), }, HeaderAction = new HttpHeaderAction(), DefaultUrlRedirect = new HttpRedirectAction(), DefaultService = "default_serviceb867731a", DefaultRouteAction = new HttpRouteAction(), Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionUrlMapsClient client = new RegionUrlMapsClientImpl(mockGrpcClient.Object, null); UrlMap response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<RegionUrlMaps.RegionUrlMapsClient> mockGrpcClient = new moq::Mock<RegionUrlMaps.RegionUrlMapsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionUrlMapRequest request = new GetRegionUrlMapRequest { Region = "regionedb20d96", Project = "projectaa6ff846", UrlMap = "url_map3ccdbf57", }; UrlMap expectedResponse = new UrlMap { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", Tests = { new UrlMapTest(), }, Region = "regionedb20d96", Fingerprint = "fingerprint009e6052", PathMatchers = { new PathMatcher(), }, HostRules = { new HostRule(), }, HeaderAction = new HttpHeaderAction(), DefaultUrlRedirect = new HttpRedirectAction(), DefaultService = "default_serviceb867731a", DefaultRouteAction = new HttpRouteAction(), Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UrlMap>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionUrlMapsClient client = new RegionUrlMapsClientImpl(mockGrpcClient.Object, null); UrlMap responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UrlMap responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<RegionUrlMaps.RegionUrlMapsClient> mockGrpcClient = new moq::Mock<RegionUrlMaps.RegionUrlMapsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionUrlMapRequest request = new GetRegionUrlMapRequest { Region = "regionedb20d96", Project = "projectaa6ff846", UrlMap = "url_map3ccdbf57", }; UrlMap expectedResponse = new UrlMap { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", Tests = { new UrlMapTest(), }, Region = "regionedb20d96", Fingerprint = "fingerprint009e6052", PathMatchers = { new PathMatcher(), }, HostRules = { new HostRule(), }, HeaderAction = new HttpHeaderAction(), DefaultUrlRedirect = new HttpRedirectAction(), DefaultService = "default_serviceb867731a", DefaultRouteAction = new HttpRouteAction(), Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionUrlMapsClient client = new RegionUrlMapsClientImpl(mockGrpcClient.Object, null); UrlMap response = client.Get(request.Project, request.Region, request.UrlMap); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<RegionUrlMaps.RegionUrlMapsClient> mockGrpcClient = new moq::Mock<RegionUrlMaps.RegionUrlMapsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRegionUrlMapRequest request = new GetRegionUrlMapRequest { Region = "regionedb20d96", Project = "projectaa6ff846", UrlMap = "url_map3ccdbf57", }; UrlMap expectedResponse = new UrlMap { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", Tests = { new UrlMapTest(), }, Region = "regionedb20d96", Fingerprint = "fingerprint009e6052", PathMatchers = { new PathMatcher(), }, HostRules = { new HostRule(), }, HeaderAction = new HttpHeaderAction(), DefaultUrlRedirect = new HttpRedirectAction(), DefaultService = "default_serviceb867731a", DefaultRouteAction = new HttpRouteAction(), Description = "description2cf9da67", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UrlMap>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionUrlMapsClient client = new RegionUrlMapsClientImpl(mockGrpcClient.Object, null); UrlMap responseCallSettings = await client.GetAsync(request.Project, request.Region, request.UrlMap, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UrlMap responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.UrlMap, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ValidateRequestObject() { moq::Mock<RegionUrlMaps.RegionUrlMapsClient> mockGrpcClient = new moq::Mock<RegionUrlMaps.RegionUrlMapsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ValidateRegionUrlMapRequest request = new ValidateRegionUrlMapRequest { RegionUrlMapsValidateRequestResource = new RegionUrlMapsValidateRequest(), Region = "regionedb20d96", Project = "projectaa6ff846", UrlMap = "url_map3ccdbf57", }; UrlMapsValidateResponse expectedResponse = new UrlMapsValidateResponse { Result = new UrlMapValidationResult(), }; mockGrpcClient.Setup(x => x.Validate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionUrlMapsClient client = new RegionUrlMapsClientImpl(mockGrpcClient.Object, null); UrlMapsValidateResponse response = client.Validate(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ValidateRequestObjectAsync() { moq::Mock<RegionUrlMaps.RegionUrlMapsClient> mockGrpcClient = new moq::Mock<RegionUrlMaps.RegionUrlMapsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ValidateRegionUrlMapRequest request = new ValidateRegionUrlMapRequest { RegionUrlMapsValidateRequestResource = new RegionUrlMapsValidateRequest(), Region = "regionedb20d96", Project = "projectaa6ff846", UrlMap = "url_map3ccdbf57", }; UrlMapsValidateResponse expectedResponse = new UrlMapsValidateResponse { Result = new UrlMapValidationResult(), }; mockGrpcClient.Setup(x => x.ValidateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UrlMapsValidateResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionUrlMapsClient client = new RegionUrlMapsClientImpl(mockGrpcClient.Object, null); UrlMapsValidateResponse responseCallSettings = await client.ValidateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UrlMapsValidateResponse responseCancellationToken = await client.ValidateAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Validate() { moq::Mock<RegionUrlMaps.RegionUrlMapsClient> mockGrpcClient = new moq::Mock<RegionUrlMaps.RegionUrlMapsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ValidateRegionUrlMapRequest request = new ValidateRegionUrlMapRequest { RegionUrlMapsValidateRequestResource = new RegionUrlMapsValidateRequest(), Region = "regionedb20d96", Project = "projectaa6ff846", UrlMap = "url_map3ccdbf57", }; UrlMapsValidateResponse expectedResponse = new UrlMapsValidateResponse { Result = new UrlMapValidationResult(), }; mockGrpcClient.Setup(x => x.Validate(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); RegionUrlMapsClient client = new RegionUrlMapsClientImpl(mockGrpcClient.Object, null); UrlMapsValidateResponse response = client.Validate(request.Project, request.Region, request.UrlMap, request.RegionUrlMapsValidateRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ValidateAsync() { moq::Mock<RegionUrlMaps.RegionUrlMapsClient> mockGrpcClient = new moq::Mock<RegionUrlMaps.RegionUrlMapsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ValidateRegionUrlMapRequest request = new ValidateRegionUrlMapRequest { RegionUrlMapsValidateRequestResource = new RegionUrlMapsValidateRequest(), Region = "regionedb20d96", Project = "projectaa6ff846", UrlMap = "url_map3ccdbf57", }; UrlMapsValidateResponse expectedResponse = new UrlMapsValidateResponse { Result = new UrlMapValidationResult(), }; mockGrpcClient.Setup(x => x.ValidateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UrlMapsValidateResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); RegionUrlMapsClient client = new RegionUrlMapsClientImpl(mockGrpcClient.Object, null); UrlMapsValidateResponse responseCallSettings = await client.ValidateAsync(request.Project, request.Region, request.UrlMap, request.RegionUrlMapsValidateRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UrlMapsValidateResponse responseCancellationToken = await client.ValidateAsync(request.Project, request.Region, request.UrlMap, request.RegionUrlMapsValidateRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Adxstudio.Xrm.Resources; using Adxstudio.Xrm.Web.UI.WebControls; using Adxstudio.Xrm.Web.UI.WebForms; using Microsoft.Xrm.Client; using Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView; namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView { /// <summary> /// Template used to create a cell of a form. /// </summary> public abstract class CellTemplate : ICellTemplate { protected CellTemplate(FormXmlCellMetadata metadata, string validationGroup, IDictionary<string, CellBinding> bindings) { if (metadata == null) { throw new ArgumentNullException("metadata"); } if (bindings == null) { throw new ArgumentNullException("bindings"); } Bindings = bindings; Metadata = metadata; ValidationGroup = validationGroup; } /// <summary> /// Number of columns the cell is to take up. /// </summary> public virtual int? ColumnSpan { get { return Metadata.ColumnSpan; } } /// <summary> /// CSS Class name assigned. /// </summary> public abstract string CssClass { get; } /// <summary> /// Indicates if the control in the cell is enabled or disabled. /// </summary> public virtual bool Enabled { get { return !Metadata.Disabled; } } protected IDictionary<string, CellBinding> Bindings { get; private set; } /// <summary> /// The id of the field. Also known as the logical name of the attribute. /// </summary> public virtual string ControlID { get { return Metadata.DataFieldName; } } protected FormXmlCellMetadata Metadata { get; set; } /// <summary> /// Number of rows a cell should take up /// </summary> public virtual int? RowSpan { get { return Metadata.RowSpan; } } protected virtual string[] ScriptIncludes { get { return new[] { "~/xrm-adx/js/crmentityformview.js" }; } } /// <summary> /// Tooltip text. /// </summary> public string ToolTip { get; set; } /// <summary> /// String of HTML markup for a control item in the Validation Summary. /// </summary> public virtual string ValidationSummaryMarkup(string message) { if (Metadata.EnableValidationSummaryLinks) { var anchorId = Metadata.ShowLabel ? string.Format("{0}_label", ControlID) : ControlID; var anchorLinkMarkupString = "<a href='#{0}' onclick='javascript:scrollToAndFocus(\"{3}\",\"{4}\");return false;'>{1} {2}</a>".FormatWith( anchorId, message, Metadata.ValidationSummaryLinkText, Metadata.ShowLabel ? string.Format("{0}_label", ControlID) : ControlID, ControlID); return anchorLinkMarkupString; } return message; } protected string ValidationGroup { get; private set; } protected virtual bool LabelIsAssociated { get { return !Metadata.LabelNotAssociated; } } public virtual void InstantiateIn(Control container) { if (!Enabled) { return; } var descriptionContainer = new HtmlGenericControl("div"); if (Metadata.AddDescription && !string.IsNullOrWhiteSpace(Metadata.Description)) { descriptionContainer.InnerHtml = Metadata.Description; switch (Metadata.DescriptionPosition) { case WebFormMetadata.DescriptionPosition.AboveLabel: descriptionContainer.Attributes["class"] = !string.IsNullOrWhiteSpace(Metadata.CssClass) ? string.Join(" ", "description", Metadata.CssClass) : "description"; break; case WebFormMetadata.DescriptionPosition.AboveControl: descriptionContainer.Attributes["class"] = !string.IsNullOrWhiteSpace(Metadata.CssClass) ? string.Join(" ", "description above", Metadata.CssClass) : "description above"; break; case WebFormMetadata.DescriptionPosition.BelowControl: descriptionContainer.Attributes["class"] = !string.IsNullOrWhiteSpace(Metadata.CssClass) ? string.Join(" ", "description below", Metadata.CssClass) : "description below"; break; } } if (Metadata.AddDescription && !string.IsNullOrWhiteSpace(Metadata.Description) && Metadata.DescriptionPosition == WebFormMetadata.DescriptionPosition.AboveLabel) { container.Controls.Add(descriptionContainer); } var cellInfoContainer = new HtmlGenericControl("div"); container.Controls.Add(cellInfoContainer); var cellInfoClasses = new List<string> { "info" }; if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired || Metadata.IsFullNameControl && !Metadata.ReadOnly) { cellInfoClasses.Add("required"); } cellInfoContainer.Attributes["class"] = string.Join(" ", cellInfoClasses.ToArray()); if (Metadata.ShowLabel) { //ClientIDMode.Static required for bookmark anchor links in Validation Summary to work. var label = new Label { ClientIDMode = ClientIDMode.Static, ID = string.Format("{0}_label", ControlID), Text = Metadata.Label, ToolTip = Metadata.ToolTip }; if (Metadata.IsRequired || Metadata.WebFormForceFieldIsRequired) { label.Text = HttpUtility.HtmlEncode(label.Text); } if (LabelIsAssociated) { label.AssociatedControlID = ControlID; } cellInfoContainer.Controls.Add(label); } if (!Metadata.ReadOnly) { var validatorContainer = new HtmlGenericControl("div"); cellInfoContainer.Controls.Add(validatorContainer); validatorContainer.Attributes["class"] = "validators"; InstantiateValidatorsIn(validatorContainer); } if (Metadata.AddDescription && !string.IsNullOrWhiteSpace(Metadata.Description) && Metadata.DescriptionPosition == WebFormMetadata.DescriptionPosition.AboveControl) { container.Controls.Add(descriptionContainer); } var controlContainer = new HtmlGenericControl("div"); container.Controls.Add(controlContainer); controlContainer.Attributes["class"] = "control"; InstantiateControlIn(controlContainer); if (Metadata.AddDescription && !string.IsNullOrWhiteSpace(Metadata.Description) && Metadata.DescriptionPosition == WebFormMetadata.DescriptionPosition.BelowControl) { container.Controls.Add(descriptionContainer); } RegisterClientSideDependencies(controlContainer); } protected abstract void InstantiateControlIn(Control container); protected virtual void InstantiateValidatorsIn(Control container) { } protected virtual void RegisterClientSideDependencies(Control control) { foreach (var script in ScriptIncludes) { var scriptManager = ScriptManager.GetCurrent(control.Page); if (scriptManager == null) { continue; } var absolutePath = VirtualPathUtility.ToAbsolute(script); scriptManager.Scripts.Add(new ScriptReference(absolutePath)); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using IndexReader = Lucene.Net.Index.IndexReader; using Term = Lucene.Net.Index.Term; using TermPositions = Lucene.Net.Index.TermPositions; using Lucene.Net.Search; using Searchable = Lucene.Net.Search.Searchable; using SpanScorer = Lucene.Net.Search.Spans.SpanScorer; using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery; using SpanWeight = Lucene.Net.Search.Spans.SpanWeight; using TermSpans = Lucene.Net.Search.Spans.TermSpans; namespace Lucene.Net.Search.Payloads { /// <summary> The BoostingTermQuery is very similar to the {@link Lucene.Net.Search.Spans.SpanTermQuery} except /// that it factors in the value of the payload located at each of the positions where the /// {@link Lucene.Net.Index.Term} occurs. /// <p> /// In order to take advantage of this, you must override {@link Lucene.Net.Search.Similarity#ScorePayload(String, byte[],int,int)} /// which returns 1 by default. /// <p> /// Payload scores are averaged across term occurrences in the document. /// /// </summary> /// <seealso cref="Lucene.Net.Search.Similarity.ScorePayload(String, byte[], int, int)"> /// </seealso> [Serializable] public class BoostingTermQuery : SpanTermQuery { public BoostingTermQuery(Term term) : base(term) { } protected internal override Weight CreateWeight(Searcher searcher) { return new BoostingTermWeight(this, this, searcher); } [Serializable] protected internal class BoostingTermWeight : SpanWeight, Weight { private void InitBlock(BoostingTermQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private BoostingTermQuery enclosingInstance; public BoostingTermQuery Enclosing_Instance { get { return enclosingInstance; } } public BoostingTermWeight(BoostingTermQuery enclosingInstance, BoostingTermQuery query, Searcher searcher) : base(query, searcher) { InitBlock(enclosingInstance); } public override Scorer Scorer(IndexReader reader) { return new BoostingSpanScorer(this, (TermSpans) query.GetSpans(reader), this, similarity, reader.Norms(query.GetField())); } protected internal class BoostingSpanScorer : SpanScorer { private void InitBlock(BoostingTermWeight enclosingInstance) { this.enclosingInstance = enclosingInstance; } private BoostingTermWeight enclosingInstance; public BoostingTermWeight Enclosing_Instance { get { return enclosingInstance; } } //TODO: is this the best way to allocate this? internal byte[] payload = new byte[256]; private TermPositions positions; protected internal float payloadScore; private int payloadsSeen; public BoostingSpanScorer(BoostingTermWeight enclosingInstance, TermSpans spans, Weight weight, Similarity similarity, byte[] norms) : base(spans, weight, similarity, norms) { InitBlock(enclosingInstance); positions = spans.GetPositions(); } protected internal override bool SetFreqCurrentDoc() { if (!more) { return false; } doc = spans.Doc(); freq = 0.0f; payloadScore = 0; payloadsSeen = 0; Similarity similarity1 = GetSimilarity(); while (more && doc == spans.Doc()) { int matchLength = spans.End() - spans.Start(); freq += similarity1.SloppyFreq(matchLength); ProcessPayload(similarity1); more = spans.Next(); //this moves positions to the next match in this document } return more || (freq != 0); } protected internal virtual void ProcessPayload(Similarity similarity) { if (positions.IsPayloadAvailable()) { payload = positions.GetPayload(payload, 0); payloadScore += similarity.ScorePayload(Enclosing_Instance.Enclosing_Instance.term.Field(), payload, 0, positions.GetPayloadLength()); payloadsSeen++; } else { //zero out the payload? } } public override float Score() { return base.Score() * (payloadsSeen > 0 ? (payloadScore / payloadsSeen) : 1); } public override Explanation Explain(int doc) { ComplexExplanation result = new ComplexExplanation(); Explanation nonPayloadExpl = base.Explain(doc); result.AddDetail(nonPayloadExpl); //QUESTION: Is there a wau to avoid this skipTo call? We need to know whether to load the payload or not Explanation payloadBoost = new Explanation(); result.AddDetail(payloadBoost); /* if (skipTo(doc) == true) { processPayload(); }*/ float avgPayloadScore = (payloadsSeen > 0 ? (payloadScore / payloadsSeen) : 1); payloadBoost.SetValue(avgPayloadScore); //GSI: I suppose we could toString the payload, but I don't think that would be a good idea payloadBoost.SetDescription("scorePayload(...)"); result.SetValue(nonPayloadExpl.GetValue() * avgPayloadScore); result.SetDescription("btq, product of:"); result.SetMatch(nonPayloadExpl.GetValue() == 0 ? false : true); // LUCENE-1303 return result; } } } public override bool Equals(object o) { if (!(o is BoostingTermQuery)) return false; BoostingTermQuery other = (BoostingTermQuery) o; return (this.GetBoost() == other.GetBoost()) && this.term.Equals(other.term); } public override int GetHashCode() // {{Aroush-2.3.1}} Do we need this methods? { return base.GetHashCode(); } } }
using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Threading; using Mono.Unix.Native; using SIL.ObjectModel; using SIL.PlatformUtilities; namespace SIL.Threading { /// <summary> /// This is a cross-platform, global, named mutex that can be used to synchronize access to data across processes. /// It supports reentrant locking. /// /// This is needed because Mono does not support system-wide, named mutexes. Mono does implement the Mutex class, /// but even when using the constructors with names, it only works within a single process. /// </summary> public class GlobalMutex : DisposableBase { private readonly IGlobalMutexAdapter _adapter; private readonly string _name; private bool _initialized; /// <summary> /// Initializes a new instance of the <see cref="GlobalMutex"/> class. /// </summary> public GlobalMutex(string name) { _name = name; if (!Platform.IsWindows) _adapter = new LinuxGlobalMutexAdapter(name); else _adapter = new WindowsGlobalMutexAdapter(name); } /// <summary> /// Gets the mutex name. /// </summary> public string Name { get { CheckDisposed(); return _name; } } /// <summary> /// Gets a value indicating whether this mutex is initialized. /// </summary> public bool IsInitialized { get { CheckDisposed(); return _initialized; } } /// <summary> /// Unlinks or removes the mutex from the system. This only has an effect on Linux. /// Windows will automatically unlink the mutex. This can be called while the mutex is locked. /// </summary> public bool Unlink() { CheckDisposed(); return _adapter.Unlink(); } /// <summary> /// Initializes this mutex. /// </summary> public bool Initialize() { CheckDisposed(); bool res = _adapter.Init(false); _initialized = true; return res; } /// <summary> /// Initializes and locks this mutex. On Windows, this is an atomic operation, so the "createdNew" /// variable is guaranteed to return a correct value. On Linux, this is not an atomic operation, /// so "createdNew" is guaranteed to be correct only if it returns true. /// </summary> public IDisposable InitializeAndLock(out bool createdNew) { CheckDisposed(); createdNew = _adapter.Init(true); return new ReleaseDisposable(_adapter); } /// <summary> /// Initializes and locks this mutex. This is an atomic operation on Windows, but not Linux. /// </summary> /// <returns></returns> public IDisposable InitializeAndLock() { bool createdNew; return InitializeAndLock(out createdNew); } /// <summary> /// Locks this mutex. /// </summary> public IDisposable Lock() { CheckDisposed(); _adapter.Wait(); return new ReleaseDisposable(_adapter); } /// <summary> /// Disposes managed resources. /// </summary> protected override void DisposeManagedResources() { _adapter.Dispose(); _initialized = false; } [SuppressMessage("Gendarme.Rules.Correctness", "DisposableFieldsShouldBeDisposedRule", Justification = "m_adapter is a reference.")] private sealed class ReleaseDisposable : DisposableBase { private readonly IGlobalMutexAdapter _adapter; public ReleaseDisposable(IGlobalMutexAdapter adapter) { _adapter = adapter; } protected override void DisposeManagedResources() { _adapter.Release(); } } private interface IGlobalMutexAdapter : IDisposable { bool Init(bool initiallyOwned); void Wait(); void Release(); bool Unlink(); } /// <summary> /// On Linux, the global mutex is implemented using file locks. /// </summary> private class LinuxGlobalMutexAdapter : DisposableBase, IGlobalMutexAdapter { private int _handle; private readonly string _name; private readonly object _syncObject = new object(); private readonly ThreadLocal<int> _waitCount = new ThreadLocal<int>(); private const int LOCK_EX = 2; private const int LOCK_UN = 8; [DllImport("libc", SetLastError = true)] private static extern int flock(int handle, int operation); public LinuxGlobalMutexAdapter(string name) { _name = Path.Combine("/var/lock", name); } public bool Init(bool initiallyOwned) { bool result; _handle = Syscall.open(_name, OpenFlags.O_CREAT | OpenFlags.O_EXCL, FilePermissions.S_IWUSR | FilePermissions.S_IRUSR); if (_handle != -1) { result = true; } else { Errno errno = Stdlib.GetLastError(); if (errno != Errno.EEXIST) throw new NativeException((int) errno); _handle = Syscall.open(_name, OpenFlags.O_CREAT, FilePermissions.S_IWUSR | FilePermissions.S_IRUSR); if (_handle == -1) throw new NativeException((int) Stdlib.GetLastError()); result = false; } if (initiallyOwned) Wait(); return result; } public void Wait() { if (_waitCount.Value == 0) { Monitor.Enter(_syncObject); if (flock(_handle, LOCK_EX) == -1) throw new NativeException(Marshal.GetLastWin32Error()); } _waitCount.Value++; } public void Release() { _waitCount.Value--; if (_waitCount.Value == 0) { if (flock(_handle, LOCK_UN) == -1) throw new NativeException(Marshal.GetLastWin32Error()); Monitor.Exit(_syncObject); } } public bool Unlink() { lock (_syncObject) { if (Syscall.unlink(_name) == -1) { Errno errno = Stdlib.GetLastError(); if (errno == Errno.ENOENT) return false; throw new NativeException((int) errno); } return true; } } protected override void DisposeManagedResources() { Unlink(); } protected override void DisposeUnmanagedResources() { Syscall.close(_handle); } } /// <summary> /// On Windows, the global mutex is implemented using a named mutex. /// </summary> private class WindowsGlobalMutexAdapter : DisposableBase, IGlobalMutexAdapter { private readonly string _name; private Mutex _mutex; public WindowsGlobalMutexAdapter(string name) { _name = name; } public bool Init(bool initiallyOwned) { bool createdNew; _mutex = new Mutex(initiallyOwned, _name, out createdNew); if (initiallyOwned && !createdNew) Wait(); return createdNew; } public void Wait() { _mutex.WaitOne(); } public void Release() { _mutex.ReleaseMutex(); } public bool Unlink() { return true; } protected override void DisposeManagedResources() { _mutex.Dispose(); } } } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Result = com.google.zxing.Result; namespace com.google.zxing.client.result { /// <summary> Parses contact information formatted according to the VCard (2.1) format. This is not a complete /// implementation but should parse information as commonly encoded in 2D barcodes. /// /// </summary> /// <author> Sean Owen /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> sealed class VCardResultParser:ResultParser { private VCardResultParser() { } public static AddressBookParsedResult parse(Result result) { // Although we should insist on the raw text ending with "END:VCARD", there's no reason // to throw out everything else we parsed just because this was omitted. In fact, Eclair // is doing just that, and we can't parse its contacts without this leniency. System.String rawText = result.Text; if (rawText == null || !rawText.StartsWith("BEGIN:VCARD")) { return null; } System.String[] names = matchVCardPrefixedField("FN", rawText, true); if (names == null) { // If no display names found, look for regular name fields and format them names = matchVCardPrefixedField("N", rawText, true); formatNames(names); } System.String[] phoneNumbers = matchVCardPrefixedField("TEL", rawText, true); System.String[] emails = matchVCardPrefixedField("EMAIL", rawText, true); System.String note = matchSingleVCardPrefixedField("NOTE", rawText, false); System.String[] addresses = matchVCardPrefixedField("ADR", rawText, true); if (addresses != null) { for (int i = 0; i < addresses.Length; i++) { addresses[i] = formatAddress(addresses[i]); } } System.String org = matchSingleVCardPrefixedField("ORG", rawText, true); System.String birthday = matchSingleVCardPrefixedField("BDAY", rawText, true); if (!isLikeVCardDate(birthday)) { birthday = null; } System.String title = matchSingleVCardPrefixedField("TITLE", rawText, true); System.String url = matchSingleVCardPrefixedField("URL", rawText, true); return new AddressBookParsedResult(names, null, phoneNumbers, emails, note, addresses, org, birthday, title, url); } private static System.String[] matchVCardPrefixedField(System.String prefix, System.String rawText, bool trim) { List<object> matches = null; int i = 0; int max = rawText.Length; while (i < max) { //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" i = rawText.IndexOf(prefix, i); if (i < 0) { break; } if (i > 0 && rawText[i - 1] != '\n') { // then this didn't start a new token, we matched in the middle of something i++; continue; } i += prefix.Length; // Skip past this prefix we found to start if (rawText[i] != ':' && rawText[i] != ';') { continue; } while (rawText[i] != ':') { // Skip until a colon i++; } i++; // skip colon int start = i; // Found the start of a match here //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" i = rawText.IndexOf('\n', i); // Really, ends in \r\n if (i < 0) { // No terminating end character? uh, done. Set i such that loop terminates and break i = max; } else if (i > start) { // found a match if (matches == null) { matches = new List<object>(); } System.String element = rawText.Substring(start, (i) - (start)); if (trim) { element = element.Trim(); } matches.Add(element); i++; } else { i++; } } if (matches == null || (matches.Count == 0)) { return null; } return toStringArray(matches); } internal static System.String matchSingleVCardPrefixedField(System.String prefix, System.String rawText, bool trim) { System.String[] values = matchVCardPrefixedField(prefix, rawText, trim); return values == null?null:values[0]; } private static bool isLikeVCardDate(System.String value_Renamed) { if (value_Renamed == null) { return true; } // Not really sure this is true but matches practice // Mach YYYYMMDD if (isStringOfDigits(value_Renamed, 8)) { return true; } // or YYYY-MM-DD return value_Renamed.Length == 10 && value_Renamed[4] == '-' && value_Renamed[7] == '-' && isSubstringOfDigits(value_Renamed, 0, 4) && isSubstringOfDigits(value_Renamed, 5, 2) && isSubstringOfDigits(value_Renamed, 8, 2); } private static System.String formatAddress(System.String address) { if (address == null) { return null; } int length = address.Length; System.Text.StringBuilder newAddress = new System.Text.StringBuilder(length); for (int j = 0; j < length; j++) { char c = address[j]; if (c == ';') { newAddress.Append(' '); } else { newAddress.Append(c); } } return newAddress.ToString().Trim(); } /// <summary> Formats name fields of the form "Public;John;Q.;Reverend;III" into a form like /// "Reverend John Q. Public III". /// /// </summary> /// <param name="names">name values to format, in place /// </param> private static void formatNames(System.String[] names) { if (names != null) { for (int i = 0; i < names.Length; i++) { System.String name = names[i]; System.String[] components = new System.String[5]; int start = 0; int end; int componentIndex = 0; //UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'" while ((end = name.IndexOf(';', start)) > 0) { components[componentIndex] = name.Substring(start, (end) - (start)); componentIndex++; start = end + 1; } components[componentIndex] = name.Substring(start); System.Text.StringBuilder newName = new System.Text.StringBuilder(100); maybeAppendComponent(components, 3, newName); maybeAppendComponent(components, 1, newName); maybeAppendComponent(components, 2, newName); maybeAppendComponent(components, 0, newName); maybeAppendComponent(components, 4, newName); names[i] = newName.ToString().Trim(); } } } private static void maybeAppendComponent(System.String[] components, int i, System.Text.StringBuilder newName) { if (components[i] != null) { newName.Append(' '); newName.Append(components[i]); } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // 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.Data.Common; using System.Collections; using Xunit; namespace System.Data.Tests { public class DataTableReaderTest { private DataTable _dt; public DataTableReaderTest() { _dt = new DataTable("test"); _dt.Columns.Add("id", typeof(int)); _dt.Columns.Add("name", typeof(string)); _dt.PrimaryKey = new DataColumn[] { _dt.Columns["id"] }; _dt.Rows.Add(new object[] { 1, "mono 1" }); _dt.Rows.Add(new object[] { 2, "mono 2" }); _dt.Rows.Add(new object[] { 3, "mono 3" }); _dt.AcceptChanges(); } #region Positive Tests [Fact] public void CtorTest() { _dt.Rows[1].Delete(); DataTableReader reader = new DataTableReader(_dt); try { int i = 0; while (reader.Read()) i++; reader.Close(); Assert.Equal(2, i); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void RowInAccessibleTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); reader.Read(); // 2nd row _dt.Rows[1].Delete(); string value = reader[1].ToString(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void IgnoreDeletedRowsDynamicTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row _dt.Rows[1].Delete(); reader.Read(); // it should be 3rd row string value = reader[0].ToString(); Assert.Equal("3", value); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void SeeTheModifiedTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row _dt.Rows[1]["name"] = "mono changed"; reader.Read(); string value = reader[1].ToString(); Assert.Equal("mono changed", value); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void SchemaTest() { DataTable another = new DataTable("another"); another.Columns.Add("x", typeof(string)); another.Rows.Add(new object[] { "test 1" }); another.Rows.Add(new object[] { "test 2" }); another.Rows.Add(new object[] { "test 3" }); DataTableReader reader = new DataTableReader(new DataTable[] { _dt, another }); try { DataTable schema = reader.GetSchemaTable(); Assert.Equal(_dt.Columns.Count, schema.Rows.Count); Assert.Equal(_dt.Columns[1].DataType.ToString(), schema.Rows[1]["DataType"].ToString()); reader.NextResult(); //schema should change here schema = reader.GetSchemaTable(); Assert.Equal(another.Columns.Count, schema.Rows.Count); Assert.Equal(another.Columns[0].DataType.ToString(), schema.Rows[0]["DataType"].ToString()); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void MultipleResultSetsTest() { DataTable dt1 = new DataTable("test2"); dt1.Columns.Add("x", typeof(string)); dt1.Rows.Add(new object[] { "test" }); dt1.Rows.Add(new object[] { "test1" }); dt1.AcceptChanges(); DataTable[] collection = new DataTable[] { _dt, dt1 }; DataTableReader reader = new DataTableReader(collection); try { int i = 0; do { while (reader.Read()) i++; } while (reader.NextResult()); Assert.Equal(5, i); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void GetTest() { _dt.Columns.Add("nullint", typeof(int)); _dt.Rows[0]["nullint"] = 333; DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); int ordinal = reader.GetOrdinal("nullint"); // Get by name Assert.Equal(1, (int)reader["id"]); Assert.Equal(333, reader.GetInt32(ordinal)); Assert.Equal("Int32", reader.GetDataTypeName(ordinal)); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void CloseTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { int i = 0; while (reader.Read() && i < 1) i++; reader.Close(); reader.Read(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void GetOrdinalTest() { DataTableReader reader = new DataTableReader(_dt); try { Assert.Equal(1, reader.GetOrdinal("name")); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } #endregion // Positive Tests #region Negative Tests [Fact] public void NoRowsTest() { _dt.Rows.Clear(); _dt.AcceptChanges(); DataTableReader reader = new DataTableReader(_dt); try { Assert.False(reader.Read()); Assert.False(reader.NextResult()); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void NoTablesTest() { AssertExtensions.Throws<ArgumentException>(null, () => { DataTableReader reader = new DataTableReader(new DataTable[] { }); try { reader.Read(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void ReadAfterClosedTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); reader.Close(); reader.Read(); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void AccessAfterClosedTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); reader.Close(); int i = (int)reader[0]; i++; // to suppress warning } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void AccessBeforeReadTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { int i = (int)reader[0]; i++; // to suppress warning } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void InvalidIndexTest() { Assert.Throws<ArgumentOutOfRangeException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); int i = (int)reader[90]; // kidding, ;-) i++; // to suppress warning } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void DontSeeTheEarlierRowsTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row // insert a row at position 0 DataRow r = _dt.NewRow(); r[0] = 0; r[1] = "adhi bagavan"; _dt.Rows.InsertAt(r, 0); Assert.Equal(2, reader.GetInt32(0)); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void AddBeforePointTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row DataRow r = _dt.NewRow(); r[0] = 0; r[1] = "adhi bagavan"; _dt.Rows.InsertAt(r, 0); _dt.Rows.Add(new object[] { 4, "mono 4" }); // should not affect the counter Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void AddAtPointTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row DataRow r = _dt.NewRow(); r[0] = 0; r[1] = "same point"; _dt.Rows.InsertAt(r, 1); _dt.Rows.Add(new object[] { 4, "mono 4" }); // should not affect the counter Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void DeletePreviousAndAcceptChangesTest() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row _dt.Rows[0].Delete(); _dt.AcceptChanges(); Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void DeleteCurrentAndAcceptChangesTest2() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row _dt.Rows[1].Delete(); // delete row, where reader points to _dt.AcceptChanges(); // accept the action Assert.Equal(1, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void DeleteFirstCurrentAndAcceptChangesTest() { Assert.Throws<InvalidOperationException>(() => { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row _dt.Rows[0].Delete(); // delete row, where reader points to _dt.AcceptChanges(); // accept the action Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } }); } [Fact] public void DeleteLastAndAcceptChangesTest2() { DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); // second row reader.Read(); // third row _dt.Rows[2].Delete(); // delete row, where reader points to _dt.AcceptChanges(); // accept the action Assert.Equal(2, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void ClearTest() { DataTableReader reader = null; try { reader = new DataTableReader(_dt); reader.Read(); // first row reader.Read(); // second row _dt.Clear(); try { int i = (int)reader[0]; i++; // suppress warning Assert.False(true); } catch (RowNotInTableException) { } // clear and add test reader.Close(); reader = new DataTableReader(_dt); reader.Read(); // first row reader.Read(); // second row _dt.Clear(); _dt.Rows.Add(new object[] { 8, "mono 8" }); _dt.AcceptChanges(); bool success = reader.Read(); Assert.False(success); // clear when reader is not read yet reader.Close(); reader = new DataTableReader(_dt); _dt.Clear(); _dt.Rows.Add(new object[] { 8, "mono 8" }); _dt.AcceptChanges(); success = reader.Read(); Assert.True(success); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } [Fact] public void MultipleDeleteTest() { _dt.Rows.Add(new object[] { 4, "mono 4" }); _dt.Rows.Add(new object[] { 5, "mono 5" }); _dt.Rows.Add(new object[] { 6, "mono 6" }); _dt.Rows.Add(new object[] { 7, "mono 7" }); _dt.Rows.Add(new object[] { 8, "mono 8" }); _dt.AcceptChanges(); DataTableReader reader = new DataTableReader(_dt); try { reader.Read(); // first row reader.Read(); reader.Read(); reader.Read(); reader.Read(); _dt.Rows[3].Delete(); _dt.Rows[1].Delete(); _dt.Rows[2].Delete(); _dt.Rows[0].Delete(); _dt.Rows[6].Delete(); _dt.AcceptChanges(); Assert.Equal(5, (int)reader[0]); } finally { if (reader != null && !reader.IsClosed) reader.Close(); } } #endregion // Negative Tests [Fact] public void TestSchemaTable() { var ds = new DataSet(); DataTable testTable = new DataTable("TestTable1"); DataTable testTable1 = new DataTable(); testTable.Namespace = "TableNamespace"; testTable1.Columns.Add("col1", typeof(int)); testTable1.Columns.Add("col2", typeof(int)); ds.Tables.Add(testTable); ds.Tables.Add(testTable1); //create a col for standard datatype testTable.Columns.Add("col_string"); testTable.Columns.Add("col_string_fixed"); testTable.Columns["col_string_fixed"].MaxLength = 10; testTable.Columns.Add("col_int", typeof(int)); testTable.Columns.Add("col_decimal", typeof(decimal)); testTable.Columns.Add("col_datetime", typeof(DateTime)); testTable.Columns.Add("col_float", typeof(float)); // Check for col constraints/properties testTable.Columns.Add("col_readonly").ReadOnly = true; testTable.Columns.Add("col_autoincrement", typeof(long)).AutoIncrement = true; testTable.Columns["col_autoincrement"].AutoIncrementStep = 5; testTable.Columns["col_autoincrement"].AutoIncrementSeed = 10; testTable.Columns.Add("col_pk"); testTable.PrimaryKey = new DataColumn[] { testTable.Columns["col_pk"] }; testTable.Columns.Add("col_unique"); testTable.Columns["col_unique"].Unique = true; testTable.Columns.Add("col_defaultvalue"); testTable.Columns["col_defaultvalue"].DefaultValue = "DefaultValue"; testTable.Columns.Add("col_expression_local", typeof(int)); testTable.Columns["col_expression_local"].Expression = "col_int*5"; ds.Relations.Add("rel", new DataColumn[] { testTable1.Columns["col1"] }, new DataColumn[] { testTable.Columns["col_int"] }, false); testTable.Columns.Add("col_expression_ext"); testTable.Columns["col_expression_ext"].Expression = "parent.col2"; testTable.Columns.Add("col_namespace"); testTable.Columns["col_namespace"].Namespace = "ColumnNamespace"; testTable.Columns.Add("col_mapping"); testTable.Columns["col_mapping"].ColumnMapping = MappingType.Attribute; DataTable schemaTable = testTable.CreateDataReader().GetSchemaTable(); Assert.Equal(25, schemaTable.Columns.Count); Assert.Equal(testTable.Columns.Count, schemaTable.Rows.Count); //True for all rows for (int i = 0; i < schemaTable.Rows.Count; ++i) { Assert.Equal(testTable.TableName, schemaTable.Rows[i]["BaseTableName"]); Assert.Equal(ds.DataSetName, schemaTable.Rows[i]["BaseCatalogName"]); Assert.Equal(DBNull.Value, schemaTable.Rows[i]["BaseSchemaName"]); Assert.Equal(schemaTable.Rows[i]["BaseColumnName"], schemaTable.Rows[i]["ColumnName"]); Assert.False((bool)schemaTable.Rows[i]["IsRowVersion"]); } Assert.Equal("col_string", schemaTable.Rows[0]["ColumnName"]); Assert.Equal(typeof(string), schemaTable.Rows[0]["DataType"]); Assert.Equal(-1, schemaTable.Rows[0]["ColumnSize"]); Assert.Equal(0, schemaTable.Rows[0]["ColumnOrdinal"]); // ms.net contradicts documented behavior Assert.False((bool)schemaTable.Rows[0]["IsLong"]); Assert.Equal("col_string_fixed", schemaTable.Rows[1]["ColumnName"]); Assert.Equal(typeof(string), schemaTable.Rows[1]["DataType"]); Assert.Equal(10, schemaTable.Rows[1]["ColumnSize"]); Assert.Equal(1, schemaTable.Rows[1]["ColumnOrdinal"]); Assert.False((bool)schemaTable.Rows[1]["IsLong"]); Assert.Equal("col_int", schemaTable.Rows[2]["ColumnName"]); Assert.Equal(typeof(int), schemaTable.Rows[2]["DataType"]); Assert.Equal(DBNull.Value, schemaTable.Rows[2]["NumericPrecision"]); Assert.Equal(DBNull.Value, schemaTable.Rows[2]["NumericScale"]); Assert.Equal(-1, schemaTable.Rows[2]["ColumnSize"]); Assert.Equal(2, schemaTable.Rows[2]["ColumnOrdinal"]); Assert.Equal("col_decimal", schemaTable.Rows[3]["ColumnName"]); Assert.Equal(typeof(decimal), schemaTable.Rows[3]["DataType"]); // When are the Precision and Scale Values set ? Assert.Equal(DBNull.Value, schemaTable.Rows[3]["NumericPrecision"]); Assert.Equal(DBNull.Value, schemaTable.Rows[3]["NumericScale"]); Assert.Equal(-1, schemaTable.Rows[3]["ColumnSize"]); Assert.Equal(3, schemaTable.Rows[3]["ColumnOrdinal"]); Assert.Equal("col_datetime", schemaTable.Rows[4]["ColumnName"]); Assert.Equal(typeof(DateTime), schemaTable.Rows[4]["DataType"]); Assert.Equal(4, schemaTable.Rows[4]["ColumnOrdinal"]); Assert.Equal("col_float", schemaTable.Rows[5]["ColumnName"]); Assert.Equal(typeof(float), schemaTable.Rows[5]["DataType"]); Assert.Equal(5, schemaTable.Rows[5]["ColumnOrdinal"]); Assert.Equal(DBNull.Value, schemaTable.Rows[5]["NumericPrecision"]); Assert.Equal(DBNull.Value, schemaTable.Rows[5]["NumericScale"]); Assert.Equal(-1, schemaTable.Rows[5]["ColumnSize"]); Assert.Equal("col_readonly", schemaTable.Rows[6]["ColumnName"]); Assert.True((bool)schemaTable.Rows[6]["IsReadOnly"]); Assert.Equal("col_autoincrement", schemaTable.Rows[7]["ColumnName"]); Assert.True((bool)schemaTable.Rows[7]["IsAutoIncrement"]); Assert.Equal(10L, schemaTable.Rows[7]["AutoIncrementSeed"]); Assert.Equal(5L, schemaTable.Rows[7]["AutoIncrementStep"]); Assert.False((bool)schemaTable.Rows[7]["IsReadOnly"]); Assert.Equal("col_pk", schemaTable.Rows[8]["ColumnName"]); Assert.True((bool)schemaTable.Rows[8]["IsKey"]); Assert.True((bool)schemaTable.Rows[8]["IsUnique"]); Assert.Equal("col_unique", schemaTable.Rows[9]["ColumnName"]); Assert.True((bool)schemaTable.Rows[9]["IsUnique"]); Assert.Equal("col_defaultvalue", schemaTable.Rows[10]["ColumnName"]); Assert.Equal("DefaultValue", schemaTable.Rows[10]["DefaultValue"]); Assert.Equal("col_expression_local", schemaTable.Rows[11]["ColumnName"]); Assert.Equal("col_int*5", schemaTable.Rows[11]["Expression"]); Assert.True((bool)schemaTable.Rows[11]["IsReadOnly"]); // if expression depends on an external col, then set Expression as null.. Assert.Equal("col_expression_ext", schemaTable.Rows[12]["ColumnName"]); Assert.Equal(DBNull.Value, schemaTable.Rows[12]["Expression"]); Assert.True((bool)schemaTable.Rows[12]["IsReadOnly"]); Assert.Equal("col_namespace", schemaTable.Rows[13]["ColumnName"]); Assert.Equal("TableNamespace", schemaTable.Rows[13]["BaseTableNamespace"]); Assert.Equal("TableNamespace", schemaTable.Rows[12]["BaseColumnNamespace"]); Assert.Equal("ColumnNamespace", schemaTable.Rows[13]["BaseColumnNamespace"]); Assert.Equal("col_mapping", schemaTable.Rows[14]["ColumnName"]); Assert.Equal(MappingType.Element, (MappingType)schemaTable.Rows[13]["ColumnMapping"]); Assert.Equal(MappingType.Attribute, (MappingType)schemaTable.Rows[14]["ColumnMapping"]); } [Fact] public void TestExceptionIfSchemaChanges() { DataTable table = new DataTable(); table.Columns.Add("col1"); DataTableReader rdr = table.CreateDataReader(); Assert.Equal(1, rdr.GetSchemaTable().Rows.Count); table.Columns[0].ColumnName = "newcol1"; try { rdr.GetSchemaTable(); Assert.False(true); } catch (InvalidOperationException) { // Never premise English. //Assert.Equal ("Schema of current DataTable '" + table.TableName + // "' in DataTableReader has changed, DataTableReader is invalid.", e.Message, "#1"); } rdr = table.CreateDataReader(); rdr.GetSchemaTable(); //no exception table.Columns.Add("col2"); try { rdr.GetSchemaTable(); Assert.False(true); } catch (InvalidOperationException) { // Never premise English. //Assert.Equal ("Schema of current DataTable '" + table.TableName + // "' in DataTableReader has changed, DataTableReader is invalid.", e.Message, "#1"); } } [Fact] public void EnumeratorTest() { DataTable table = new DataTable(); table.Columns.Add("col1", typeof(int)); table.Rows.Add(new object[] { 0 }); table.Rows.Add(new object[] { 1 }); DataTableReader rdr = table.CreateDataReader(); IEnumerator enmr = rdr.GetEnumerator(); table.Rows.Add(new object[] { 2 }); table.Rows.RemoveAt(0); //Test if the Enumerator is stable int i = 1; while (enmr.MoveNext()) { DbDataRecord rec = (DbDataRecord)enmr.Current; Assert.Equal(i, rec.GetInt32(0)); i++; } } [Fact] public void GetCharsTest() { _dt.Columns.Add("col2", typeof(char[])); _dt.Rows.Clear(); _dt.Rows.Add(new object[] { 1, "string", "string".ToCharArray() }); _dt.Rows.Add(new object[] { 2, "string1", null }); DataTableReader rdr = _dt.CreateDataReader(); rdr.Read(); try { rdr.GetChars(1, 0, null, 0, 10); Assert.False(true); } catch (InvalidCastException e) { // Never premise English. //Assert.Equal ("Unable to cast object of type 'System.String'" + // " to type 'System.Char[]'.", e.Message, "#1"); } char[] char_arr = null; long len = 0; len = rdr.GetChars(2, 0, null, 0, 0); Assert.Equal(6, len); char_arr = new char[len]; len = rdr.GetChars(2, 0, char_arr, 0, 0); Assert.Equal(0, len); len = rdr.GetChars(2, 0, null, 0, 0); char_arr = new char[len + 2]; len = rdr.GetChars(2, 0, char_arr, 2, 100); Assert.Equal(6, len); char[] val = (char[])rdr.GetValue(2); for (int i = 0; i < len; ++i) Assert.Equal(val[i], char_arr[i + 2]); } [Fact] public void GetProviderSpecificTests() { DataTableReader rdr = _dt.CreateDataReader(); while (rdr.Read()) { object[] values = new object[rdr.FieldCount]; object[] pvalues = new object[rdr.FieldCount]; rdr.GetValues(values); rdr.GetProviderSpecificValues(pvalues); for (int i = 0; i < rdr.FieldCount; ++i) { Assert.Equal(values[i], pvalues[i]); Assert.Equal(rdr.GetValue(i), rdr.GetProviderSpecificValue(i)); Assert.Equal(rdr.GetFieldType(i), rdr.GetProviderSpecificFieldType(i)); } } } [Fact] public void GetNameTest() { DataTableReader rdr = _dt.CreateDataReader(); for (int i = 0; i < _dt.Columns.Count; ++i) Assert.Equal(_dt.Columns[i].ColumnName, rdr.GetName(i)); } } }
#region Apache License v2.0 //Copyright 2014 Stephen Yu //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. #endregion namespace StarMQ.Consume { using Core; using Exception; using Message; using Microsoft.CSharp.RuntimeBinder; using Model; using RabbitMQ.Client; using RabbitMQ.Client.Events; using RabbitMQ.Client.Exceptions; using System; using System.Collections.Concurrent; using System.IO; using System.Threading; using System.Threading.Tasks; using IConnection = Core.IConnection; public interface IConsumer : IBasicConsumer, IDisposable { Task Consume(Queue queue, Action<IHandlerRegistrar> configure = null, IBasicConsumer consumer = null); } internal abstract class BaseConsumer : IConsumer { protected readonly IConnection Connection; protected readonly IHandlerManager HandlerManager; protected readonly ILog Log; private readonly IPipeline _pipeline; private readonly BlockingCollection<Action> _queue = new BlockingCollection<Action>(); private readonly ManualResetEvent _signal = new ManualResetEvent(true); private readonly ISerializationStrategy _serializationStrategy; private bool _disposed; public event ConsumerCancelledEventHandler ConsumerCancelled; public string ConsumerTag { get; private set; } public IModel Model { get; protected set; } protected BaseConsumer(IConnection connection, IHandlerManager handlerManager, ILog log, INamingStrategy namingStrategy, IPipeline pipeline, ISerializationStrategy serializationStrategy) { Connection = connection; ConsumerTag = namingStrategy.GetConsumerTag(); HandlerManager = handlerManager; Log = log; _pipeline = pipeline; _serializationStrategy = serializationStrategy; Connection.OnDisconnected += ClearQueue; Dispatch(); } private void Dispatch() { Task.Run(() => { foreach (var action in _queue.GetConsumingEnumerable()) { Task.Run(action).Wait(); _signal.WaitOne(-1); } }); } private void ClearQueue() { Action action; _signal.Reset(); while (_queue.TryTake(out action)) Log.Info("Message discarded."); _signal.Set(); } public abstract Task Consume(Queue queue, Action<IHandlerRegistrar> configure = null, IBasicConsumer consumer = null); public virtual void HandleBasicCancel(string consumerTag) { if (ConsumerTag != consumerTag) throw new StarMqException("Consumer tag mismatch."); // TODO: remove if impossible ClearQueue(); var consumerCancelled = ConsumerCancelled; if (consumerCancelled != null) consumerCancelled(this, new ConsumerEventArgs(consumerTag)); Log.Info(String.Format("Broker cancelled consumer '{0}'.", consumerTag)); } public void HandleBasicCancelOk(string consumerTag) { if (ConsumerTag != consumerTag) throw new StarMqException("Consumer tag mismatch."); // TODO: remove if impossible Log.Info(String.Format("Cancel confirmed for consumer '{0}'.", consumerTag)); } public void HandleBasicConsumeOk(string consumerTag) { if (consumerTag == null) throw new ArgumentNullException("consumerTag"); ConsumerTag = consumerTag; Log.Info(String.Format("Consume confirmed for consumer '{0}'.", consumerTag)); } public void HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body) { if (ConsumerTag != consumerTag) throw new StarMqException("Consumer tag mismatch."); // TODO: remove if impossible Log.Debug(String.Format("Consumer '{0}' received message #{1}.", consumerTag, deliveryTag)); try { _queue.Add(() => { BaseResponse response; var message = new Message<byte[]>(body); message.Properties.CopyFrom(properties); var context = new DeliveryContext { Redelivered = redelivered, RoutingKey = routingKey, Properties = message.Properties }; if (_disposed) return; try { var data = _pipeline.OnReceive(message); var processed = _serializationStrategy.Deserialize(data, HandlerManager.Default); var handler = HandlerManager.Get(processed.Body.GetType()); response = (BaseResponse)handler(processed.Body, context); response.DeliveryTag = deliveryTag; } catch (RuntimeBinderException ex) { response = new NackResponse { DeliveryTag = deliveryTag }; Log.Error(String.Format("No matching handler found for message #{0} - default handler failed.", deliveryTag), ex); } catch (Exception ex) { response = new NackResponse { DeliveryTag = deliveryTag }; Log.Error(String.Format("Failed to process message #{0}", deliveryTag), ex); } try { response.Send(Model, Log); if (response.Action == ResponseAction.Unsubscribe) { Model.BasicCancel(ConsumerTag); Dispose(); } } catch (AlreadyClosedException ex) { Log.Info(String.Format("Unable to send response. Lost connection to broker - {0}.", ex.GetType().Name)); } catch (IOException ex) { Log.Info(String.Format("Unable to send response. Lost connection to broker - {0}.", ex.GetType().Name)); } catch (NotSupportedException ex) { Log.Info(String.Format("Unable to send response. Lost connection to broker - {0}.", ex.GetType().Name)); } }); } catch (InvalidOperationException) { /* thrown if fired after dispose */ } } public void HandleModelShutdown(IModel model, ShutdownEventArgs args) { Log.Info(String.Format("Consumer '{0}' shutdown by {1}. Reason: '{2}'", ConsumerTag, args.Initiator, args.Cause)); } public void Dispose() { if (_disposed) return; _disposed = true; ClearQueue(); _queue.CompleteAdding(); if (Model != null) Model.Dispose(); Log.Info("Dispose completed."); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void PermuteVarSingle() { var test = new SimpleBinaryOpTest__PermuteVarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__PermuteVarSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Int32[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Single> _fld1; public Vector256<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 1; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__PermuteVarSingle testClass) { var result = Avx.PermuteVar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__PermuteVarSingle testClass) { fixed (Vector256<Single>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx.PermuteVar( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector256<Single> _clsVar1; private static Vector256<Int32> _clsVar2; private Vector256<Single> _fld1; private Vector256<Int32> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__PermuteVarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 1; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); } public SimpleBinaryOpTest__PermuteVarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 1; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = 1; } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.PermuteVar( Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.PermuteVar( Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.PermuteVar( Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.PermuteVar), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.PermuteVar), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.PermuteVar), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Int32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.PermuteVar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Single>* pClsVar1 = &_clsVar1) fixed (Vector256<Int32>* pClsVar2 = &_clsVar2) { var result = Avx.PermuteVar( Avx.LoadVector256((Single*)(pClsVar1)), Avx.LoadVector256((Int32*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int32>>(_dataTable.inArray2Ptr); var result = Avx.PermuteVar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx.PermuteVar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int32*)(_dataTable.inArray2Ptr)); var result = Avx.PermuteVar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__PermuteVarSingle(); var result = Avx.PermuteVar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__PermuteVarSingle(); fixed (Vector256<Single>* pFld1 = &test._fld1) fixed (Vector256<Int32>* pFld2 = &test._fld2) { var result = Avx.PermuteVar( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.PermuteVar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Single>* pFld1 = &_fld1) fixed (Vector256<Int32>* pFld2 = &_fld2) { var result = Avx.PermuteVar( Avx.LoadVector256((Single*)(pFld1)), Avx.LoadVector256((Int32*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.PermuteVar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx.PermuteVar( Avx.LoadVector256((Single*)(&test._fld1)), Avx.LoadVector256((Int32*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Single> op1, Vector256<Int32> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Int32[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(left[1]) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (i > 3 ? (BitConverter.SingleToInt32Bits(left[5]) != BitConverter.SingleToInt32Bits(result[i])) : (BitConverter.SingleToInt32Bits(left[1]) != BitConverter.SingleToInt32Bits(result[i]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.PermuteVar)}<Single>(Vector256<Single>, Vector256<Int32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// // 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 Microsoft.WindowsAzure; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// Parameters returned from the Create Virtual Machine Image operation. /// </summary> public partial class VirtualMachineImageUpdateResponse : OperationResponse { private string _category; /// <summary> /// The repository classification of the image. All user images have /// the category User. /// </summary> public string Category { get { return this._category; } set { this._category = value; } } private string _description; /// <summary> /// Specifies the description of the OS image. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } private string _eula; /// <summary> /// Specifies the End User License Agreement that is associated with /// the image. The value for this element is a string, but it is /// recommended that the value be a URL that points to a EULA. /// </summary> public string Eula { get { return this._eula; } set { this._eula = value; } } private Uri _iconUri; /// <summary> /// Specifies the Uri to the icon that is displayed for the image in /// the Management Portal. /// </summary> public Uri IconUri { get { return this._iconUri; } set { this._iconUri = value; } } private string _imageFamily; /// <summary> /// Specifies a value that can be used to group OS images. /// </summary> public string ImageFamily { get { return this._imageFamily; } set { this._imageFamily = value; } } private bool? _isPremium; /// <summary> /// Indicates if the image contains software or associated services /// that will incur charges above the core price for the virtual /// machine. /// </summary> public bool? IsPremium { get { return this._isPremium; } set { this._isPremium = value; } } private string _label; /// <summary> /// Specifies the friendly name of the image. /// </summary> public string Label { get { return this._label; } set { this._label = value; } } private string _language; /// <summary> /// Specifies the language of the image. The Language element is only /// available using version 2013-03-01 or higher. /// </summary> public string Language { get { return this._language; } set { this._language = value; } } private string _location; /// <summary> /// The geo-location in which this media is located. The Location value /// is derived from storage account that contains the blob in which /// the media is located. If the storage account belongs to an /// affinity group the value is NULL. If the version is set to /// 2012-08-01 or later, the locations are returned for platform /// images; otherwise, this value is NULL for platform images. /// </summary> public string Location { get { return this._location; } set { this._location = value; } } private double _logicalSizeInGB; /// <summary> /// The size, in GB, of the image. /// </summary> public double LogicalSizeInGB { get { return this._logicalSizeInGB; } set { this._logicalSizeInGB = value; } } private Uri _mediaLinkUri; /// <summary> /// Specifies the location of the blob in Windows Azure storage. The /// blob location must belong to a storage account in the subscription /// specified by the SubscriptionId value in the operation call. /// Example: http://example.blob.core.windows.net/disks/mydisk.vhd /// </summary> public Uri MediaLinkUri { get { return this._mediaLinkUri; } set { this._mediaLinkUri = value; } } private string _name; /// <summary> /// Specifies a name that Windows Azure uses to identify the image when /// creating one or more virtual machines. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _operatingSystemType; /// <summary> /// The operating system type of the OS image. Possible values are: /// Linux, Windows. /// </summary> public string OperatingSystemType { get { return this._operatingSystemType; } set { this._operatingSystemType = value; } } private Uri _privacyUri; /// <summary> /// Specifies the URI that points to a document that contains the /// privacy policy related to the OS image. /// </summary> public Uri PrivacyUri { get { return this._privacyUri; } set { this._privacyUri = value; } } private System.DateTime? _publishedDate; /// <summary> /// Specifies the date when the OS image was added to the image /// repository. /// </summary> public System.DateTime? PublishedDate { get { return this._publishedDate; } set { this._publishedDate = value; } } private string _publisherName; /// <summary> /// Specifies the name of the publisher of the image. /// </summary> public string PublisherName { get { return this._publisherName; } set { this._publisherName = value; } } private string _recommendedVMSize; /// <summary> /// Specifies the size to use for the virtual machine that is created /// from the OS image. /// </summary> public string RecommendedVMSize { get { return this._recommendedVMSize; } set { this._recommendedVMSize = value; } } private bool? _showInGui; /// <summary> /// Specifies whether the image should appear in the image gallery. /// </summary> public bool? ShowInGui { get { return this._showInGui; } set { this._showInGui = value; } } private Uri _smallIconUri; /// <summary> /// Specifies the URI to the small icon that is displayed when the /// image is presented in the Windows Azure Management Portal. The /// SmallIconUri element is only available using version 2013-03-01 or /// higher. /// </summary> public Uri SmallIconUri { get { return this._smallIconUri; } set { this._smallIconUri = value; } } /// <summary> /// Initializes a new instance of the VirtualMachineImageUpdateResponse /// class. /// </summary> public VirtualMachineImageUpdateResponse() { } } }
// 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.Linq; using System.Xml; using System.Xml.Linq; using Xunit; namespace XDocumentTests.SDMSample { public class SDM_Element { /// <summary> /// Validate behavior of XElement simple creation. /// </summary> [Fact] public void CreateElementSimple() { const string ElementName = "Element"; XElement element; // Test the constructor that takes only a name. element = new XElement(ElementName); Assert.Equal(ElementName, element.Name.ToString()); Assert.Throws<ArgumentNullException>(() => new XElement((XName)null)); } /// <summary> /// Validate behavior of XElement creation with content supplied. /// </summary> [Fact] public void CreateElementWithContent() { // Test the constructor that takes a name and some content. XElement level2Element = new XElement("Level2", "TextValue"); XAttribute attribute = new XAttribute("Attribute", "AttributeValue"); XCData cdata = new XCData("abcdefgh"); string someValue = "text"; XElement element = new XElement("Level1", level2Element, cdata, someValue, attribute); Assert.Equal("Level1", element.Name.ToString()); Assert.Equal( new XNode[] { level2Element, cdata, new XText(someValue) }, element.Nodes(), XNode.EqualityComparer); Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name)); Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value)); } /// <summary> /// Validate behavior of XElement creation with copy constructor. /// </summary> [Fact] public void CreateElementCopy() { // With attributes XElement level2Element = new XElement("Level2", "TextValue"); XAttribute attribute = new XAttribute("Attribute", "AttributeValue"); XCData cdata = new XCData("abcdefgh"); string someValue = "text"; XElement element = new XElement("Level1", level2Element, cdata, someValue, attribute); XElement elementCopy = new XElement(element); Assert.Equal("Level1", element.Name.ToString()); Assert.Equal( new XNode[] { level2Element, cdata, new XText(someValue) }, elementCopy.Nodes(), XNode.EqualityComparer); Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name)); Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value)); // Without attributes element = new XElement("Level1", level2Element, cdata, someValue); elementCopy = new XElement(element); Assert.Equal("Level1", element.Name.ToString()); Assert.Equal( new XNode[] { level2Element, cdata, new XText(someValue) }, elementCopy.Nodes(), XNode.EqualityComparer); Assert.Empty(elementCopy.Attributes()); // Hsh codes of equal elements should be equal. Assert.Equal(XNode.EqualityComparer.GetHashCode(element), XNode.EqualityComparer.GetHashCode(elementCopy)); // Null element is not allowed. Assert.Throws<ArgumentNullException>(() => new XElement((XElement)null)); } /// <summary> /// Validate behavior of XElement creation from an XmlReader. /// </summary> [Fact] public void CreateElementFromReader() { string xml = "<Level1 a1='1' a2='2'><Level2><![CDATA[12345678]]>text</Level2></Level1>"; string xml2 = "<Level1 />"; string xml3 = "<x><?xml version='1.0' encoding='utf-8'?></x>"; // With attributes using (TextReader textReader = new StringReader(xml)) using (XmlReader xmlReader = XmlReader.Create(textReader)) { xmlReader.Read(); XElement element = (XElement)XNode.ReadFrom(xmlReader); Assert.Equal("Level1", element.Name.ToString()); Assert.Equal(new[] { "Level2" }, element.Elements().Select(x => x.Name.ToString())); Assert.Equal(new[] { "a1", "a2" }, element.Attributes().Select(x => x.Name.ToString())); Assert.Equal(new[] { "1", "2" }, element.Attributes().Select(x => x.Value)); Assert.Equal("12345678text", element.Element("Level2").Value); } // Without attributes using (TextReader textReader = new StringReader(xml2)) using (XmlReader xmlReader = XmlReader.Create(textReader)) { xmlReader.Read(); var element = (XElement)XNode.ReadFrom(xmlReader); Assert.Equal("Level1", element.Name.ToString()); Assert.Empty(element.Elements()); Assert.Empty(element.Attributes()); Assert.Empty(element.Value); } // XmlReader in start state results in exception using (TextReader textReader = new StringReader(xml)) using (XmlReader xmlReader = XmlReader.Create(textReader)) { Assert.Throws<InvalidOperationException>(() => (XElement)XNode.ReadFrom(xmlReader)); } // XmlReader not on an element results in exception. using (TextReader textReader = new StringReader(xml)) using (XmlReader xmlReader = XmlReader.Create(textReader)) { xmlReader.Read(); xmlReader.MoveToAttribute("a1"); Assert.Throws<InvalidOperationException>(() => (XElement)XNode.ReadFrom(xmlReader)); } // Illegal xml triggers exception that is bubbled out. using (TextReader textReader = new StringReader(xml3)) using (XmlReader xmlReader = XmlReader.Create(textReader)) { xmlReader.Read(); Assert.Throws<XmlException>(() => (XElement)XNode.ReadFrom(xmlReader)); } } /// <summary> /// Validate behavior of XElement EmptySequence method. /// </summary> [Fact] public void ElementEmptyElementSequence() { Assert.Empty(XElement.EmptySequence); Assert.Empty(XElement.EmptySequence); } /// <summary> /// Validate behavior of XElement HasAttributes/HasElements properties. /// </summary> [Fact] public void ElementHasAttributesAndElements() { XElement e1 = new XElement("x"); XElement e2 = new XElement("x", new XAttribute("a", "value")); XElement e3 = new XElement("x", new XElement("y")); XElement e4 = new XElement("x", new XCData("cdata-value")); Assert.False(e1.HasAttributes); Assert.True(e2.HasAttributes); Assert.False(e1.HasElements); Assert.False(e2.HasElements); Assert.True(e3.HasElements); Assert.False(e4.HasElements); } /// <summary> /// Validate behavior of the IsEmpty property. /// </summary> [Fact] public void ElementIsEmpty() { XElement e1 = new XElement("x"); XElement e2 = new XElement("x", 10); XElement e3 = new XElement("x", string.Empty); Assert.True(e1.IsEmpty); Assert.False(e2.IsEmpty); Assert.False(e3.IsEmpty); } /// <summary> /// Validate behavior of the Value property on XElement. /// </summary> [Fact] public void ElementValue() { XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "value"); XElement e3 = new XElement("x", 100, 200); XElement e4 = new XElement("x", 100, "value", 200); XElement e5 = new XElement("x", string.Empty); XElement e6 = new XElement("x", 1, string.Empty, 5); XElement e7 = new XElement("x", new XElement("y", "inner1", new XElement("z", "foo"), "inner2")); XElement e8 = new XElement("x", "text1", new XElement("y", "inner"), "text2"); XElement e9 = new XElement("x", "text1", new XText("abcd"), new XElement("y", "y")); XElement e10 = new XElement("x", new XComment("my comment")); Assert.Empty(e1.Value); Assert.Equal("value", e2.Value); Assert.Equal("100200", e3.Value); Assert.Equal("100value200", e4.Value); Assert.Empty(e5.Value); Assert.Equal("15", e6.Value); Assert.Equal("inner1fooinner2", e7.Value); Assert.Equal("text1innertext2", e8.Value); Assert.Equal("text1abcdy", e9.Value); Assert.Empty(e10.Value); Assert.Throws<ArgumentNullException>(() => e1.Value = null); e1.Value = string.Empty; e2.Value = "not-empty"; Assert.Empty(e1.Value); Assert.Equal("not-empty", e2.Value); } /// <summary> /// Validates the explicit string conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToString() { XElement e1 = new XElement("x"); XElement e2 = new XElement("x", string.Empty); XElement e3 = new XElement("x", "value"); Assert.Null((string)((XElement)null)); Assert.Empty((string)e1); Assert.Empty((string)e2); Assert.Equal("value", (string)e3); } /// <summary> /// Validates the explicit boolean conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToBoolean() { // Calling explicit operator with null should result in exception. Assert.Throws<ArgumentNullException>(() => (bool)((XElement)null)); // Test various values. XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "bogus"); XElement e3 = new XElement("x", "true"); XElement e4 = new XElement("x", "false"); XElement e5 = new XElement("x", "0"); XElement e6 = new XElement("x", "1"); Assert.Throws<FormatException>(() => (bool)e1); Assert.Throws<FormatException>(() => (bool)e2); Assert.True((bool)e3); Assert.False((bool)e4); Assert.False((bool)e5); Assert.True((bool)e6); } /// <summary> /// Validates the explicit int32 conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToInt32() { // Calling explicit operator with null should result in exception. Assert.Throws<ArgumentNullException>(() => (int)((XElement)null)); // Test various values. XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "bogus"); XElement e3 = new XElement("x", "2147483648"); XElement e4 = new XElement("x", "5"); Assert.Throws<FormatException>(() => (int)e1); Assert.Throws<FormatException>(() => (int)e2); Assert.Throws<OverflowException>(() => (int)e3); Assert.Equal(5, (int)e4); } /// <summary> /// Validates the explicit uint32 conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToUInt32() { // Calling explicit operator with null should result in exception. Assert.Throws<ArgumentNullException>(() => (uint)((XElement)null)); // Test various values. XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "bogus"); XElement e3 = new XElement("x", "4294967296"); XElement e4 = new XElement("x", "5"); Assert.Throws<FormatException>(() => (uint)e1); Assert.Throws<FormatException>(() => (uint)e2); Assert.Throws<OverflowException>(() => (uint)e3); Assert.Equal(5u, (uint)e4); } /// <summary> /// Validates the explicit int64 conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToInt64() { // Calling explicit operator with null should result in exception. Assert.Throws<ArgumentNullException>(() => (long)((XElement)null)); // Test various values. XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "bogus"); XElement e3 = new XElement("x", "18446744073709551616"); XElement e4 = new XElement("x", "5"); Assert.Throws<FormatException>(() => (long)e1); Assert.Throws<FormatException>(() => (long)e2); Assert.Throws<OverflowException>(() => (long)e3); Assert.Equal(5L, (long)e4); } /// <summary> /// Validates the explicit uint64 conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToUInt64() { // Calling explicit operator with null should result in exception. Assert.Throws<ArgumentNullException>(() => (ulong)((XElement)null)); // Test various values. XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "bogus"); XElement e3 = new XElement("x", "18446744073709551616"); XElement e4 = new XElement("x", "5"); Assert.Throws<FormatException>(() => (ulong)e1); Assert.Throws<FormatException>(() => (ulong)e2); Assert.Throws<OverflowException>(() => (ulong)e3); Assert.Equal(5UL, (ulong)e4); } /// <summary> /// Validates the explicit float conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToFloat() { // Calling explicit operator with null should result in exception. Assert.Throws<ArgumentNullException>(() => (float)((XElement)null)); // Test various values. XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "bogus"); XElement e4 = new XElement("x", "5.0"); Assert.Throws<FormatException>(() => (float)e1); Assert.Throws<FormatException>(() => (float)e2); Assert.Equal(5.0f, (float)e4); } /// <summary> /// Validates the explicit float conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToFloat_NotNetFramework() { XElement e3 = new XElement("x", "5e+500"); Assert.Equal(float.PositiveInfinity, (float)e3); } /// <summary> /// Validates the explicit double conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToDouble() { // Calling explicit operator with null should result in exception. Assert.Throws<ArgumentNullException>(() => (double)((XElement)null)); // Test various values. XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "bogus"); XElement e4 = new XElement("x", "5.0"); Assert.Throws<FormatException>(() => (double)e1); Assert.Throws<FormatException>(() => (double)e2); Assert.Equal(5.0, (double)e4); } /// <summary> /// Validates the explicit double conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToDouble_NotNetFramework() { XElement e3 = new XElement("x", "5e+5000"); Assert.Equal(double.PositiveInfinity, (double)e3); } /// <summary> /// Validates the explicit decimal conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToDecimal() { // Calling explicit operator with null should result in exception. Assert.Throws<ArgumentNullException>(() => (decimal)((XElement)null)); // Test various values. XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "bogus"); XElement e3 = new XElement("x", "111111111111111111111111111111111111111111111111"); XElement e4 = new XElement("x", "5.0"); Assert.Throws<FormatException>(() => (decimal)e1); Assert.Throws<FormatException>(() => (decimal)e2); Assert.Throws<OverflowException>(() => (decimal)e3); Assert.Equal(5.0m, (decimal)e4); } /// <summary> /// Validates the explicit DateTime conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToDateTime() { // Calling explicit operator with null should result in exception. Assert.Throws<ArgumentNullException>(() => (DateTime)((XElement)null)); // Test various values. XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "bogus"); XElement e3 = new XElement("x", "1968-01-07"); Assert.Throws<FormatException>(() => (DateTime)e1); Assert.Throws<FormatException>(() => (DateTime)e2); Assert.Equal(new DateTime(1968, 1, 7), (DateTime)e3); } /// <summary> /// Validates the explicit TimeSpan conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToTimeSpan() { // Calling explicit operator with null should result in exception. Assert.Throws<ArgumentNullException>(() => (TimeSpan)((XElement)null)); // Test various values. XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "bogus"); XElement e3 = new XElement("x", "PT1H2M3S"); Assert.Throws<FormatException>(() => (TimeSpan)e1); Assert.Throws<FormatException>(() => (TimeSpan)e2); Assert.Equal(new TimeSpan(1, 2, 3), (TimeSpan)e3); } /// <summary> /// Validates the explicit guid conversion operator on XElement. /// </summary> [Fact] public void ElementExplicitToGuid() { // Calling explicit operator with null should result in exception. Assert.Throws<ArgumentNullException>(() => (Guid)((XElement)null)); string guid = "2b67e9fb-97ad-4258-8590-8bc8c2d32df5"; // Test various values. XElement e1 = new XElement("x"); XElement e2 = new XElement("x", "bogus"); XElement e3 = new XElement("x", guid); Assert.Throws<FormatException>(() => (Guid)e1); Assert.Throws<FormatException>(() => (Guid)e2); Assert.Equal(new Guid(guid), (Guid)e3); } /// <summary> /// Validates the explicit conversion operators on XElement /// for nullable value types. /// </summary> [Fact] public void ElementExplicitToNullables() { string guid = "cd8d69ed-fef9-4283-aaf4-216463e4496f"; bool? b = (bool?)new XElement("x", true); int? i = (int?)new XElement("x", 5); uint? u = (uint?)new XElement("x", 5); long? l = (long?)new XElement("x", 5); ulong? ul = (ulong?)new XElement("x", 5); float? f = (float?)new XElement("x", 5); double? n = (double?)new XElement("x", 5); decimal? d = (decimal?)new XElement("x", 5); DateTime? dt = (DateTime?)new XElement("x", "1968-01-07"); TimeSpan? ts = (TimeSpan?)new XElement("x", "PT1H2M3S"); Guid? g = (Guid?)new XElement("x", guid); Assert.True(b.Value); Assert.Equal(5, i.Value); Assert.Equal(5u, u.Value); Assert.Equal(5L, l.Value); Assert.Equal(5uL, ul.Value); Assert.Equal(5.0f, f.Value); Assert.Equal(5.0, n.Value); Assert.Equal(5.0m, d.Value); Assert.Equal(new DateTime(1968, 1, 7), dt.Value); Assert.Equal(new TimeSpan(1, 2, 3), ts.Value); Assert.Equal(new Guid(guid), g.Value); b = (bool?)((XElement)null); i = (int?)((XElement)null); u = (uint?)((XElement)null); l = (long?)((XElement)null); ul = (ulong?)((XElement)null); f = (float?)((XElement)null); n = (double?)((XElement)null); d = (decimal?)((XElement)null); dt = (DateTime?)((XElement)null); ts = (TimeSpan?)((XElement)null); g = (Guid?)((XElement)null); Assert.Null(b); Assert.Null(i); Assert.Null(u); Assert.Null(l); Assert.Null(ul); Assert.Null(f); Assert.Null(n); Assert.Null(d); Assert.Null(dt); Assert.Null(ts); Assert.Null(g); } /// <summary> /// Validate enumeration of element ancestors. /// </summary> [Fact] public void ElementAncestors() { XElement level3 = new XElement("Level3"); XElement level2 = new XElement("Level2", level3); XElement level1 = new XElement("Level1", level2); XElement level0 = new XElement("Level1", level1); Assert.Equal(new XElement[] { level2, level1, level0 }, level3.Ancestors(), XNode.EqualityComparer); Assert.Equal(new XElement[] { level1, level0 }, level3.Ancestors("Level1"), XNode.EqualityComparer); Assert.Empty(level3.Ancestors(null)); Assert.Equal( new XElement[] { level3, level2, level1, level0 }, level3.AncestorsAndSelf(), XNode.EqualityComparer); Assert.Equal(new XElement[] { level3 }, level3.AncestorsAndSelf("Level3"), XNode.EqualityComparer); Assert.Empty(level3.AncestorsAndSelf(null)); } /// <summary> /// Validate enumeration of element descendents. /// </summary> [Fact] public void ElementDescendents() { XComment comment = new XComment("comment"); XElement level3 = new XElement("Level3"); XElement level2 = new XElement("Level2", level3); XElement level1 = new XElement("Level1", level2, comment); XElement level0 = new XElement("Level1", level1); Assert.Equal(new XElement[] { level1, level2, level3 }, level1.DescendantsAndSelf(), XNode.EqualityComparer); Assert.Equal( new XNode[] { level0, level1, level2, level3, comment }, level0.DescendantNodesAndSelf(), XNode.EqualityComparer); Assert.Empty(level0.DescendantsAndSelf(null)); Assert.Equal(new XElement[] { level0, level1 }, level0.DescendantsAndSelf("Level1"), XNode.EqualityComparer); } /// <summary> /// Validate enumeration of element attributes. /// </summary> [Fact] public void ElementAttributes() { XElement e1 = new XElement("x"); XElement e2 = new XElement( "x", new XAttribute("a1", "1"), new XAttribute("a2", "2"), new XAttribute("a3", "3"), new XAttribute("a4", "4"), new XAttribute("a5", "5")); XElement e3 = new XElement( "x", new XAttribute("a1", "1"), new XAttribute("a2", "2"), new XAttribute("a3", "3")); Assert.Null(e1.Attribute("foo")); Assert.Null(e2.Attribute("foo")); Assert.Equal("a3", e2.Attribute("a3").Name.ToString()); Assert.Equal("3", e2.Attribute("a3").Value); Assert.Equal(new[] { "a1", "a2", "a3", "a4", "a5" }, e2.Attributes().Select(x => x.Name.ToString())); Assert.Equal(new[] { "1", "2", "3", "4", "5" }, e2.Attributes().Select(x => x.Value)); Assert.Equal(new[] { "a1" }, e2.Attributes("a1").Select(x => x.Name.ToString())); Assert.Equal(new[] { "5" }, e2.Attributes("a5").Select(x => x.Value)); Assert.Empty(e2.Attributes(null)); e2.RemoveAttributes(); Assert.Empty(e2.Attributes()); // Removal of non-existent attribute e1.SetAttributeValue("foo", null); Assert.Empty(e1.Attributes()); // Add of non-existent attribute e1.SetAttributeValue("foo", "foo-value"); Assert.Equal("foo", e1.Attribute("foo").Name.ToString()); Assert.Equal("foo-value", e1.Attribute("foo").Value); // Overwriting of existing attribute e1.SetAttributeValue("foo", "noo-value"); Assert.Equal("foo", e1.Attribute("foo").Name.ToString()); Assert.Equal("noo-value", e1.Attribute("foo").Value); // Effective removal of existing attribute e1.SetAttributeValue("foo", null); Assert.Empty(e1.Attributes()); // These 3 are in a specific order to exercise the attribute removal code. e3.SetAttributeValue("a2", null); Assert.Equal(2, e3.Attributes().Count()); e3.SetAttributeValue("a3", null); Assert.Equal(1, e3.Attributes().Count()); e3.SetAttributeValue("a1", null); Assert.Empty(e3.Attributes()); } /// <summary> /// Validates remove methods on elements. /// </summary> [Fact] public void ElementRemove() { XElement e = new XElement( "x", new XAttribute("a1", 1), new XAttribute("a2", 2), new XText("abcd"), 10, new XElement("y", new XComment("comment")), new XElement("z")); Assert.Equal(5, e.DescendantNodesAndSelf().Count()); Assert.Equal(2, e.Attributes().Count()); e.RemoveAll(); Assert.Equal(1, e.DescendantNodesAndSelf().Count()); Assert.Empty(e.Attributes()); // Removing all from an already empty one. e.RemoveAll(); Assert.Equal(1, e.DescendantNodesAndSelf().Count()); Assert.Empty(e.Attributes()); } /// <summary> /// Validate enumeration of the SetElementValue method on element/ /// </summary> [Fact] public void ElementSetElementValue() { XElement e1 = new XElement("x"); // Removal of non-existent element e1.SetElementValue("foo", null); Assert.Empty(e1.Elements()); // Add of non-existent element e1.SetElementValue("foo", "foo-value"); Assert.Equal(new XElement[] { new XElement("foo", "foo-value") }, e1.Elements(), XNode.EqualityComparer); // Overwriting of existing element e1.SetElementValue("foo", "noo-value"); Assert.Equal(new XElement[] { new XElement("foo", "noo-value") }, e1.Elements(), XNode.EqualityComparer); // Effective removal of existing element e1.SetElementValue("foo", null); Assert.Empty(e1.Elements()); } /// <summary> /// Tests XElement.GetDefaultNamespace(). /// </summary> [Fact] public void ElementGetDefaultNamespace() { XNamespace ns = XNamespace.Get("http://test"); XElement e = new XElement(ns + "foo"); XNamespace n = e.GetDefaultNamespace(); Assert.NotNull(n); Assert.Equal(XNamespace.None, n); e.SetAttributeValue("xmlns", ns); n = e.GetDefaultNamespace(); Assert.NotNull(n); Assert.Equal(ns, n); } /// <summary> /// Tests XElement.GetNamespaceOfPrefix(). /// </summary> [Fact] public void ElementGetNamespaceOfPrefix() { XNamespace ns = XNamespace.Get("http://test"); XElement e = new XElement(ns + "foo"); Assert.Throws<ArgumentNullException>(() => e.GetNamespaceOfPrefix(null)); AssertExtensions.Throws<ArgumentException>(null, () => e.GetNamespaceOfPrefix(string.Empty)); XNamespace n = e.GetNamespaceOfPrefix("xmlns"); Assert.Equal("http://www.w3.org/2000/xmlns/", n.NamespaceName); n = e.GetNamespaceOfPrefix("xml"); Assert.Equal("http://www.w3.org/XML/1998/namespace", n.NamespaceName); n = e.GetNamespaceOfPrefix("myns"); Assert.Null(n); XDocument doc = new XDocument(e); e.SetAttributeValue("{http://www.w3.org/2000/xmlns/}myns", ns); n = e.GetNamespaceOfPrefix("myns"); Assert.NotNull(n); Assert.Equal(ns, n); } /// <summary> /// Tests XElement.GetPrefixOfNamespace(). /// </summary> [Fact] public void ElementGetPrefixOfNamespace() { Assert.Throws<ArgumentNullException>(() => new XElement("foo").GetPrefixOfNamespace(null)); XNamespace ns = XNamespace.Get("http://test"); XElement e = new XElement(ns + "foo"); string prefix = e.GetPrefixOfNamespace(ns); Assert.Null(prefix); prefix = e.GetPrefixOfNamespace(XNamespace.Xmlns); Assert.Equal("xmlns", prefix); prefix = e.GetPrefixOfNamespace(XNamespace.Xml); Assert.Equal("xml", prefix); XElement parent = new XElement("parent", e); parent.SetAttributeValue("{http://www.w3.org/2000/xmlns/}myns", ns); prefix = e.GetPrefixOfNamespace(ns); Assert.Equal("myns", prefix); e = XElement.Parse("<foo:element xmlns:foo='http://xxx'></foo:element>"); prefix = e.GetPrefixOfNamespace("http://xxx"); Assert.Equal("foo", prefix); e = XElement.Parse( "<foo:element xmlns:foo='http://foo' xmlns:bar='http://bar'><bar:element /></foo:element>"); prefix = e.GetPrefixOfNamespace("http://foo"); Assert.Equal("foo", prefix); prefix = e.Element(XName.Get("{http://bar}element")).GetPrefixOfNamespace("http://foo"); Assert.Equal("foo", prefix); prefix = e.Element(XName.Get("{http://bar}element")).GetPrefixOfNamespace("http://bar"); Assert.Equal("bar", prefix); } /// <summary> /// Tests cases where we're exporting unqualified elements that have xmlns attributes. /// In this specific scenario we expect XmlExceptions because the element itself /// is written to an XmlWriter with the empty namespace, and then when the attribute /// is written to the XmlWriter an exception occurs because the xmlns attribute /// would cause a retroactive change to the namespace of the already-written element. /// That is not allowed -- the element must be qualified. /// </summary> [Fact] public void ElementWithXmlnsAttribute() { // And with just xmlns local name XElement element = new XElement("MyElement", new XAttribute("xmlns", "http://tempuri/test")); Assert.Throws<XmlException>(() => element.ToString()); // A qualified element name works. element = new XElement("{http://tempuri/test}MyElement", new XAttribute("xmlns", "http://tempuri/test")); Assert.Equal("<MyElement xmlns=\"http://tempuri/test\" />", element.ToString()); } /// <summary> /// Tests the Equals methods on XElement. /// </summary> [Fact] public void ElementEquality() { XElement e1 = XElement.Parse("<x/>"); XElement e2 = XElement.Parse("<x/>"); XElement e3 = XElement.Parse("<x a='a'/>"); XElement e4 = XElement.Parse("<x>x</x>"); XElement e5 = XElement.Parse("<y/>"); // Internal method. Assert.True(XNode.DeepEquals(e1, e1)); Assert.True(XNode.DeepEquals(e1, e2)); Assert.False(XNode.DeepEquals(e1, e3)); Assert.False(XNode.DeepEquals(e1, e4)); Assert.False(XNode.DeepEquals(e1, e5)); // object.Equals override Assert.True(e1.Equals(e1)); Assert.False(e1.Equals(e2)); Assert.False(e1.Equals(e3)); Assert.False(e1.Equals(e4)); Assert.False(e1.Equals(e5)); Assert.False(e1.Equals(null)); Assert.False(e1.Equals("foo")); // Hash codes. The most we can say is that identical elements // should have the same hash codes. XElement e1a = XElement.Parse("<x/>"); XElement e1b = XElement.Parse("<x/>"); XElement e2a = XElement.Parse("<x>abc</x>"); XElement e2b = XElement.Parse("<x>abc</x>"); XElement e3a = XElement.Parse("<x><y/></x>"); XElement e3b = XElement.Parse("<x><y/></x>"); XElement e4a = XElement.Parse("<x><y/><!--comment--></x>"); XElement e4b = XElement.Parse("<x><!--comment--><y/></x>"); XElement e5a = XElement.Parse("<x a='a'/>"); XElement e5b = XElement.Parse("<x a='a'/>"); int hash = XNode.EqualityComparer.GetHashCode(e1a); Assert.Equal(XNode.EqualityComparer.GetHashCode(e1b), hash); hash = XNode.EqualityComparer.GetHashCode(e2a); Assert.Equal(XNode.EqualityComparer.GetHashCode(e2b), hash); hash = XNode.EqualityComparer.GetHashCode(e3a); Assert.Equal(XNode.EqualityComparer.GetHashCode(e3b), hash); hash = XNode.EqualityComparer.GetHashCode(e4a); Assert.Equal(XNode.EqualityComparer.GetHashCode(e4b), hash); hash = XNode.EqualityComparer.GetHashCode(e5a); Assert.Equal(XNode.EqualityComparer.GetHashCode(e5b), hash); // Attribute comparison e1 = XElement.Parse("<x a='a' />"); e2 = XElement.Parse("<x b='b' />"); e3 = XElement.Parse("<x a='a' b='b' />"); e4 = XElement.Parse("<x b='b' a='a' />"); e5 = XElement.Parse("<x a='b' />"); Assert.False(XNode.DeepEquals(e1, e2)); Assert.False(XNode.DeepEquals(e1, e3)); Assert.False(XNode.DeepEquals(e1, e4)); Assert.False(XNode.DeepEquals(e1, e5)); Assert.False(XNode.DeepEquals(e2, e3)); Assert.False(XNode.DeepEquals(e2, e4)); Assert.False(XNode.DeepEquals(e2, e5)); Assert.False(XNode.DeepEquals(e3, e4)); Assert.False(XNode.DeepEquals(e3, e5)); Assert.False(XNode.DeepEquals(e4, e5)); } /// <summary> /// Tests that an element appended as a child element during iteration of its new /// parent's content is returned in iteration. /// </summary> [Fact] public void ElementAppendedChildIsIterated() { XElement parent = new XElement("element", new XElement("child1"), new XElement("child2")); bool b1 = false, b2 = false, b3 = false, b4 = false; foreach (XElement child in parent.Elements()) { switch (child.Name.LocalName) { case "child1": b1 = true; parent.Add(new XElement("extra1")); break; case "child2": b2 = true; parent.Add(new XElement("extra2")); break; case "extra1": b3 = true; break; case "extra2": b4 = true; break; default: Assert.True(false, string.Format("Uexpected element '{0}'", child.Name)); break; } } Assert.True(b1 || b2 || b3 || b4, "Appended child elements not included in parent iteration"); } } }
namespace InteractiveAlert { using System; using System.Collections.Generic; using System.Linq; using CoreGraphics; using Foundation; using UIKit; // The Main Class // https://github.com/vikmeup/SCLAlertView-Swift/blob/master/SCLAlertView/SCLAlertView.swift#L309 // https://github.com/dogo/SCLAlertView public class InteractiveAlertView : UIViewController { public static event EventHandler<InteractiveAlertViewEventArgs> Presented; public static event EventHandler<InteractiveAlertViewEventArgs> Closed; // Action Types public enum SCLActionType { None, Closure } // Animation Styles public enum SCLAnimationStyle { NoAnimation, TopToBottom, BottomToTop, LeftToRight, RightToLeft } private static readonly nfloat kCircleHeightBackground = 62.0f; private readonly SCLAppearance appearance; // DynamicAnimator function private UIDynamicAnimator animator; // Members declaration private readonly UIView baseView = new UIView(); private readonly UIView circleBG = new UIView(new CGRect(0, 0, kCircleHeightBackground, kCircleHeightBackground)); private UIView circleIconView; private readonly UIView circleView = new UIView(); private readonly UIView contentView = new UIView(); private Action dismissBlock; private double duration; private NSTimer durationStatusTimer; private NSTimer durationTimer; private bool keyboardHasBeenShown; private NSObject keyboardWillHideToken; private NSObject keyboardWillShowToken; private readonly UILabel labelTitle = new UILabel(); private UISnapBehavior snapBehavior; private CGPoint? tmpCircleViewFrameOrigin; private CGPoint? tmpContentViewFrameOrigin; private readonly UITextView viewText = new UITextView(); public InteractiveAlertView(SCLAppearance appearance) : base(null, null) { this.appearance = appearance; this.Setup(); } public InteractiveAlertView(string nibNameOrNil, NSBundle bundle, SCLAppearance appearance) : base(nibNameOrNil, bundle) { this.appearance = appearance; this.Setup(); } public InteractiveAlertView(string nibNameOrNil, NSBundle bundle) : this(nibNameOrNil, bundle, new SCLAppearance()) { } public InteractiveAlertView() : this(new SCLAppearance()) { } // UI Colour public UIColor ViewColor { get; set; } // UI Options public UIColor IconTintColor { get; set; } public UIView CustomSubview { get; set; } private List<UITextField> inputs { get; } = new List<UITextField>(); private List<UITextView> input { get; } = new List<UITextView>(); private List<SCLButton> buttons { get; } = new List<SCLButton>(); private void Setup() { // Set up main view this.View.Frame = UIScreen.MainScreen.Bounds; this.View.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; this.View.BackgroundColor = new UIColor(0, 0, 0, this.appearance.DefaultShadowOpacity); this.View.AddSubview(this.baseView); // Base View this.baseView.Frame = this.View.Frame; this.baseView.AddSubview(this.contentView); // Content View this.contentView.Layer.CornerRadius = this.appearance.ContentViewCornerRadius; this.contentView.Layer.MasksToBounds = true; this.contentView.Layer.BorderWidth = 0.5f; this.contentView.AddSubview(this.labelTitle); this.contentView.AddSubview(this.viewText); // Circle View this.circleBG.BackgroundColor = this.appearance.CircleBackgroundColor; this.circleBG.Layer.CornerRadius = this.circleBG.Frame.Size.Height / 2f; this.baseView.AddSubview(this.circleBG); this.circleBG.AddSubview(this.circleView); var x = (kCircleHeightBackground - this.appearance.CircleHeight) / 2f; this.circleView.Frame = new CGRect(x, x + this.appearance.CircleTopPosition, this.appearance.CircleHeight, this.appearance.CircleHeight); this.circleView.Layer.CornerRadius = this.circleView.Frame.Size.Height / 2f; // Title this.labelTitle.Lines = 0; this.labelTitle.TextAlignment = UITextAlignment.Center; this.labelTitle.Font = this.appearance.TitleFont; if (this.appearance.TitleMinimumScaleFactor < 1) { this.labelTitle.MinimumScaleFactor = this.appearance.TitleMinimumScaleFactor; this.labelTitle.AdjustsFontSizeToFitWidth = true; } this.labelTitle.Frame = new CGRect(12, this.appearance.TitleTop, this.appearance.WindowWidth - 24, this.appearance.TitleHeight); // View text this.viewText.Editable = false; this.viewText.TextAlignment = UITextAlignment.Center; this.viewText.TextContainerInset = UIEdgeInsets.Zero; this.viewText.TextContainer.LineFragmentPadding = 0; this.viewText.Font = this.appearance.TextFont; // Colours this.contentView.BackgroundColor = this.appearance.ContentViewColor; this.viewText.BackgroundColor = this.appearance.ContentViewColor; this.labelTitle.TextColor = this.appearance.TitleColor; this.viewText.TextColor = this.appearance.TitleColor; this.contentView.Layer.BorderColor = this.appearance.ContentViewBorderColor.CGColor; //Gesture Recognizer for tapping outside the textinput if (this.appearance.DisableTapGesture == false) { var tapGesture = new UITapGestureRecognizer(this.Tapped) {NumberOfTapsRequired = 1}; this.View.AddGestureRecognizer(tapGesture); } } public void SetTitle(string title) { this.labelTitle.Text = title; } public void SetSubTitle(string subTitle) { this.viewText.Text = subTitle; } public void SetDismissBlock(Action dismissAction) { this.dismissBlock = dismissAction; } public override void ViewWillLayoutSubviews() { base.ViewWillLayoutSubviews(); var rv = UIApplication.SharedApplication.KeyWindow; var sz = rv.Frame.Size; var frame = rv.Frame; frame.Width = sz.Width; frame.Height = sz.Height; // Set background frame this.View.Frame = frame; nfloat hMargin = 12f; // get actual height of title text nfloat titleActualHeight = 0f; if (!string.IsNullOrEmpty(this.labelTitle.Text)) { titleActualHeight = SCLAlertViewExtension.heightWithConstrainedWidth(this.labelTitle.Text, this.appearance.WindowWidth - hMargin * 2f, this.labelTitle.Font) + 10f; // get the larger height for the title text titleActualHeight = titleActualHeight > this.appearance.TitleHeight ? titleActualHeight : this.appearance.TitleHeight; } // computing the right size to use for the textView var maxHeight = sz.Height - 100f; // max overall height nfloat consumedHeight = 0f; consumedHeight += titleActualHeight > 0 ? this.appearance.TitleTop + titleActualHeight : hMargin; consumedHeight += 14; consumedHeight += this.appearance.ButtonHeight * this.buttons.Count; consumedHeight += this.appearance.TextFieldHeight * this.inputs.Count; consumedHeight += this.appearance.TextViewdHeight * this.input.Count; var maxViewTextHeight = maxHeight - consumedHeight; var viewTextWidth = this.appearance.WindowWidth - hMargin * 2f; nfloat viewTextHeight; // Check if there is a custom subview and add it over the textview if (this.CustomSubview != null) { viewTextHeight = (nfloat) Math.Min(this.CustomSubview.Frame.Height, maxViewTextHeight); this.viewText.Text = string.Empty; this.viewText.AddSubview(this.CustomSubview); } else { // computing the right size to use for the textView var suggestedViewTextSize = this.viewText.SizeThatFits(new CGSize(viewTextWidth, nfloat.MaxValue)); viewTextHeight = (nfloat) Math.Min(suggestedViewTextSize.Height, maxViewTextHeight); // scroll management this.viewText.ScrollEnabled = suggestedViewTextSize.Height > maxViewTextHeight; } var windowHeight = consumedHeight + viewTextHeight; // Set frames var x = (sz.Width - this.appearance.WindowWidth) / 2f; var y = (sz.Height - windowHeight - this.appearance.CircleHeight / 8) / 2f; this.contentView.Frame = new CGRect(x, y, this.appearance.WindowWidth, windowHeight); this.contentView.Layer.CornerRadius = this.appearance.ContentViewCornerRadius; y -= kCircleHeightBackground * 0.6f; x = (sz.Width - kCircleHeightBackground) / 2f; this.circleBG.Frame = new CGRect(x, y + this.appearance.CircleBackgroundTopPosition, kCircleHeightBackground, kCircleHeightBackground); //adjust Title frame based on circularIcon show/hide flag var titleOffset = this.appearance.ShowCircularIcon ? 0.0f : -12.0f; this.labelTitle.Frame.Offset(0, titleOffset); // Subtitle y = titleActualHeight > 0f ? this.appearance.TitleTop + titleActualHeight + titleOffset : hMargin; this.viewText.Frame = new CGRect(hMargin, y, this.appearance.WindowWidth - hMargin * 2f, this.appearance.TextHeight); this.viewText.Frame = new CGRect(hMargin, y, viewTextWidth, viewTextHeight); // Text fields y += viewTextHeight + 14.0f; foreach (var txt in this.inputs) { txt.Frame = new CGRect(hMargin, y, this.appearance.WindowWidth - hMargin * 2, 30); txt.Layer.CornerRadius = this.appearance.FieldCornerRadius; y += this.appearance.TextFieldHeight; } foreach (var txt in this.input) { txt.Frame = new CGRect(hMargin, y, this.appearance.WindowWidth - hMargin * 2f, 70); //txt.layer.cornerRadius = fieldCornerRadius y += this.appearance.TextViewdHeight; } // Buttons foreach (var btn in this.buttons) { btn.Frame = new CGRect(hMargin, y, this.appearance.WindowWidth - hMargin * 2, 35); btn.Layer.CornerRadius = this.appearance.ButtonCornerRadius; y += this.appearance.ButtonHeight; } } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); this.keyboardWillShowToken = UIKeyboard.Notifications.ObserveWillShow(this.KeyboardWillShow); this.keyboardWillHideToken = UIKeyboard.Notifications.ObserveWillHide(this.KeyboardWillHide); } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); this.keyboardWillShowToken?.Dispose(); this.keyboardWillHideToken?.Dispose(); } public override void TouchesEnded(NSSet touches, UIEvent evt) { base.TouchesEnded(touches, evt); if (evt.TouchesForView(this.View)?.Count > 0) { this.View.EndEditing(true); } } public UITextField AddTextField(string title) { // Update view height this.appearance.SetWindowHeight(this.appearance.WindowHeight + this.appearance.TextFieldHeight); // Add text field var txt = new UITextField { BorderStyle = UITextBorderStyle.RoundedRect, Font = this.appearance.TextFont, AutocapitalizationType = UITextAutocapitalizationType.Words, ClearButtonMode = UITextFieldViewMode.WhileEditing }; txt.Layer.MasksToBounds = true; txt.Layer.BorderWidth = 1.0f; if (!string.IsNullOrEmpty(title)) { txt.Placeholder = title; } this.contentView.AddSubview(txt); this.inputs.Add(txt); return txt; } public UITextView AddTextView() { // Update view height this.appearance.SetWindowHeight(this.appearance.WindowHeight + this.appearance.TextViewdHeight); // Add text view var txt = new UITextView {Font = this.appearance.TextFont}; // No placeholder with UITextView but you can use KMPlaceholderTextView library //txt.autocapitalizationType = UITextAutocapitalizationType.Words //txt.clearButtonMode = UITextFieldViewMode.WhileEditing txt.Layer.MasksToBounds = true; txt.Layer.BorderWidth = 1.0f; txt.Layer.CornerRadius = 4f; this.contentView.AddSubview(txt); this.input.Add(txt); return txt; } public SCLButton AddButton(string title, Action action, UIColor backgroundColor = null, UIColor textColor = null, bool showDurationStatus = false) { var btn = this.AddButton(title, backgroundColor, textColor, showDurationStatus); btn.ActionType = SCLActionType.Closure; btn.Action = action; btn.AddTarget(this.ButtonTapped, UIControlEvent.TouchUpInside); btn.AddTarget(this.ButtonTapDown, UIControlEvent.TouchDown | UIControlEvent.TouchDragEnter); btn.AddTarget(this.ButtonRelease, UIControlEvent.TouchUpInside | UIControlEvent.TouchUpOutside | UIControlEvent.TouchCancel | UIControlEvent.TouchDragOutside); return btn; } public SCLButton AddButton(string title, UIColor backgroundColor = null, UIColor textColor = null, bool showDurationStatus = false) { // Update view height this.appearance.SetWindowHeight(this.appearance.WindowHeight + this.appearance.ButtonHeight); // Add button var btn = new SCLButton(); btn.Layer.MasksToBounds = true; btn.SetTitle(title, UIControlState.Normal); btn.TitleLabel.Font = this.appearance.ButtonFont; btn.CustomBackgroundColor = backgroundColor; btn.CustomTextColor = textColor; btn.InitialTitle = title; btn.ShowDurationStatus = showDurationStatus; this.contentView.AddSubview(btn); this.buttons.Add(btn); return btn; } private void ButtonTapped(object sender, EventArgs args) { var btn = (SCLButton) sender; if (btn.ActionType == SCLActionType.Closure) { btn.Action?.Invoke(); } else { Console.WriteLine("Unknow action type for button"); } if (this.View.Alpha != 0 && this.appearance.ShouldAutoDismiss) { this.HideView(); } } private void ButtonTapDown(object sender, EventArgs args) { var btn = (SCLButton) sender; nfloat hue = 0f; nfloat saturation = 0; nfloat brightness = 0; nfloat alpha = 0; nfloat pressBrightnessFactor = 0.85f; btn.BackgroundColor?.GetHSBA(out hue, out saturation, out brightness, out alpha); brightness = brightness * pressBrightnessFactor; btn.BackgroundColor = UIColor.FromHSBA(hue, saturation, brightness, alpha); } private void ButtonRelease(object sender, EventArgs args) { var btn = (SCLButton) sender; btn.BackgroundColor = btn.CustomBackgroundColor ?? this.ViewColor ?? btn.BackgroundColor; } private void KeyboardWillShow(object sender, UIKeyboardEventArgs args) { if (this.keyboardHasBeenShown) { return; } this.keyboardHasBeenShown = true; var endKeyBoardFrame = args.FrameEnd.GetMinY(); if (this.tmpContentViewFrameOrigin == null) { this.tmpContentViewFrameOrigin = this.contentView.Frame.Location; } if (this.tmpCircleViewFrameOrigin == null) { // todo location replace origin this.tmpCircleViewFrameOrigin = this.circleBG.Frame.Location; } var newContentViewFrameY = this.contentView.Frame.GetMaxY() - endKeyBoardFrame; if (newContentViewFrameY < 0) { newContentViewFrameY = 0; } var newBallViewFrameY = this.circleBG.Frame.Y - newContentViewFrameY; UIView.AnimateNotify(args.AnimationDuration, 0, ConvertToAnimationOptions(args.AnimationCurve), () => { var contentViewFrame = this.contentView.Frame; contentViewFrame.Y -= newContentViewFrameY; this.contentView.Frame = contentViewFrame; var circleBGFrame = this.circleBG.Frame; circleBGFrame.Y = newBallViewFrameY; this.circleBG.Frame = circleBGFrame; }, null); } private void KeyboardWillHide(object sender, UIKeyboardEventArgs args) { if (this.keyboardHasBeenShown) { UIView.AnimateNotify(args.AnimationDuration, 0, ConvertToAnimationOptions(args.AnimationCurve), () => { //This could happen on the simulator (keyboard will be hidden) if (this.tmpContentViewFrameOrigin.HasValue) { var contentViewFrame = this.contentView.Frame; contentViewFrame.Y = this.tmpContentViewFrameOrigin.Value.Y; this.contentView.Frame = contentViewFrame; this.tmpContentViewFrameOrigin = null; } if (this.tmpCircleViewFrameOrigin.HasValue) { var circleBGFrame = this.circleBG.Frame; circleBGFrame.Y = this.tmpCircleViewFrameOrigin.Value.Y; this.circleBG.Frame = circleBGFrame; this.tmpCircleViewFrameOrigin = null; } }, null); } this.keyboardHasBeenShown = false; } //Dismiss keyboard when tapped outside textfield & close SCLAlertView when hideWhenBackgroundViewIsTapped private void Tapped(UITapGestureRecognizer gestureRecognizer) { this.View.EndEditing(true); if (gestureRecognizer.View.HitTest(gestureRecognizer.LocationInView(gestureRecognizer.View), null) == this.baseView && this.appearance.HideWhenBackgroundViewIsTapped) { this.HideView(); } } public SCLAlertViewResponder ShowCustom(string title, string subTitle, UIColor color, UIImage icon, string closeButtonTitle = null, double duration = 0.0, UIColor colorStyle = null, UIColor colorTextButton = null, InteractiveAlertStyle style = InteractiveAlertStyle.Success, SCLAnimationStyle animationStyle = SCLAnimationStyle.TopToBottom) { colorStyle = colorStyle ?? GetDefaultColorStyle(style); colorTextButton = colorTextButton ?? GetDefaultColorTextButton(style) ?? UIColor.White; return this.ShowTitle(title, subTitle, duration, closeButtonTitle, style, color, colorTextButton, icon, animationStyle); } public SCLAlertViewResponder ShowAlert(InteractiveAlertStyle style, string title, string subTitle, string closeButtonTitle = null, double duration = 0.0, UIColor colorStyle = null, UIColor colorTextButton = null, UIImage circleIconImage = null, SCLAnimationStyle animationStyle = SCLAnimationStyle.TopToBottom) { colorStyle = colorStyle ?? GetDefaultColorStyle(style); colorTextButton = colorTextButton ?? GetDefaultColorTextButton(style) ?? UIColor.White; return this.ShowTitle(title, subTitle, duration, closeButtonTitle, style, colorStyle, colorTextButton, circleIconImage, animationStyle); } public SCLAlertViewResponder ShowTitle(string title, string subTitle, double duration, string completeText, InteractiveAlertStyle style, UIColor colorStyle = null, UIColor colorTextButton = null, UIImage circleIconImage = null, SCLAnimationStyle animationStyle = SCLAnimationStyle.TopToBottom) { colorStyle = colorStyle ?? UIColor.Black; colorTextButton = colorTextButton ?? UIColor.White; this.View.Alpha = 0; var rv = UIApplication.SharedApplication.KeyWindow; rv.AddSubview(this.View); this.View.Frame = rv.Bounds; this.baseView.Frame = rv.Bounds; // Alert colour/icon UIImage iconImage = null; // Icon style switch (style) { case InteractiveAlertStyle.Success: iconImage = checkCircleIconImage(circleIconImage, SCLAlertViewStyleKit.ImageOfCheckmark()); break; case InteractiveAlertStyle.Error: iconImage = checkCircleIconImage(circleIconImage, SCLAlertViewStyleKit.ImageOfCross()); break; //case InteractiveAlertStyle.Notice: //iconImage = checkCircleIconImage(circleIconImage, SCLAlertViewStyleKit.ImageOfNotice()); //break; case InteractiveAlertStyle.Warning: iconImage = checkCircleIconImage(circleIconImage, SCLAlertViewStyleKit.ImageOfWarning()); break; //case InteractiveAlertStyle.Info: //iconImage = checkCircleIconImage(circleIconImage, SCLAlertViewStyleKit.imageOfInfo()); //break; case InteractiveAlertStyle.Edit: iconImage = checkCircleIconImage(circleIconImage, SCLAlertViewStyleKit.ImageOfEdit()); break; case InteractiveAlertStyle.Wait: iconImage = null; break; //case InteractiveAlertStyle.Question: //iconImage = checkCircleIconImage(circleIconImage, SCLAlertViewStyleKit.imageOfQuestion()); //break; } // Title if (!string.IsNullOrEmpty(title)) { this.labelTitle.Text = title; var actualHeight = SCLAlertViewExtension.heightWithConstrainedWidth(title, this.appearance.WindowWidth - 24, this.labelTitle.Font); this.labelTitle.Frame = new CGRect(12, this.appearance.TitleTop, this.appearance.WindowWidth - 24, actualHeight); } // Subtitle if (!string.IsNullOrEmpty(subTitle)) { this.viewText.Text = subTitle; // Adjust text view size, if necessary var str = new NSString(subTitle); var font = this.viewText.Font; var attr = new UIStringAttributes {Font = this.viewText.Font}; var sz = new CGSize(this.appearance.WindowWidth - 24, 90); var r = str.GetBoundingRect(sz, NSStringDrawingOptions.UsesLineFragmentOrigin, attr, null); var ht = (nfloat) Math.Ceiling(r.Size.Height); if (ht < this.appearance.TextHeight) { this.appearance.WindowHeight -= this.appearance.TextHeight - ht; this.appearance.SetTextHeight(ht); } } if // Done button (this.appearance.ShowCloseButton) { title = completeText ?? "Done"; this.AddButton(title, this.HideView); } //hidden/show circular view based on the ui option this.circleView.Hidden = !this.appearance.ShowCircularIcon; this.circleBG.Hidden = !this.appearance.ShowCircularIcon; // Alert view colour and images this.circleView.BackgroundColor = colorStyle; // Spinner / icon if (style == InteractiveAlertStyle.Wait) { var indicator = new UIActivityIndicatorView(UIActivityIndicatorViewStyle.WhiteLarge); indicator.StartAnimating(); this.circleIconView = indicator; } else { if (this.IconTintColor != null) { this.circleIconView = new UIImageView(iconImage?.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)); this.circleIconView.TintColor = this.IconTintColor; } else { this.circleIconView = new UIImageView(iconImage); } } this.circleView.AddSubview(this.circleIconView); var x = (this.appearance.CircleHeight - this.appearance.CircleIconHeight) / 2f; this.circleIconView.Frame = new CGRect(x, x, this.appearance.CircleIconHeight, this.appearance.CircleIconHeight); this.circleIconView.Layer.CornerRadius = this.circleIconView.Bounds.Height / 2f; this.circleIconView.Layer.MasksToBounds = true; foreach (var txt in this.inputs) { txt.Layer.BorderColor = colorStyle.CGColor; } foreach (var txt in this.input) { txt.Layer.BorderColor = colorStyle.CGColor; } foreach (var btn in this.buttons) { btn.BackgroundColor = btn.CustomBackgroundColor ?? colorStyle; btn.SetTitleColor(btn.CustomTextColor ?? colorTextButton ?? UIColor.White, UIControlState.Normal); } // Adding duration if (duration > 0) { this.duration = duration; this.durationTimer?.Invalidate(); this.durationTimer = NSTimer.CreateScheduledTimer(this.duration, false, obj => { this.HideView(); }); this.durationStatusTimer?.Invalidate(); this.durationStatusTimer = NSTimer.CreateScheduledTimer(1.0d, true, obj => { this.UpdateDurationStatus(); }); } // Animate in the alert view this.ShowAnimation(animationStyle); OnPresented(this, new InteractiveAlertViewEventArgs(this)); // Chainable objects return new SCLAlertViewResponder(this); } // Show animation in the alert view private void ShowAnimation( SCLAnimationStyle animationStyle = SCLAnimationStyle.TopToBottom, float animationStartOffset = -400.0f, float boundingAnimationOffset = 15.0f, double animationDuration = 0.2f) { var rv = UIApplication.SharedApplication.KeyWindow; var animationStartOrigin = this.baseView.Frame; var animationCenter = rv.Center; switch (animationStyle) { case SCLAnimationStyle.NoAnimation: this.View.Alpha = 1.0f; break; case SCLAnimationStyle.TopToBottom: animationStartOrigin.Location = new CGPoint(animationStartOrigin.X, this.baseView.Frame.Y + animationStartOffset); animationCenter = new CGPoint(animationCenter.X, animationCenter.Y + boundingAnimationOffset); break; case SCLAnimationStyle.BottomToTop: animationStartOrigin.Location = new CGPoint(animationStartOrigin.X, this.baseView.Frame.Y - animationStartOffset); animationCenter = new CGPoint(animationCenter.X, animationCenter.Y - boundingAnimationOffset); break; case SCLAnimationStyle.LeftToRight: animationStartOrigin.Location = new CGPoint(this.baseView.Frame.X + animationStartOffset, animationStartOrigin.Y); animationCenter = new CGPoint(animationCenter.X + boundingAnimationOffset, animationCenter.Y); break; case SCLAnimationStyle.RightToLeft: animationStartOrigin.Location = new CGPoint(this.baseView.Frame.X - animationStartOffset, animationStartOrigin.Y); animationCenter = new CGPoint(animationCenter.X - boundingAnimationOffset, animationCenter.Y); break; } var baseViewFrame = animationStartOrigin; this.baseView.Frame = baseViewFrame; if (this.appearance.DynamicAnimatorActive) { UIView.AnimateNotify(animationDuration, () => { this.View.Alpha = 1; }, null); this.Animate(this.baseView, rv.Center); } else { UIView.AnimateNotify(animationDuration, () => { this.View.Alpha = 1; this.baseView.Center = animationCenter; }, completion => { UIView.AnimateNotify(animationDuration, () => { this.View.Alpha = 1; this.baseView.Center = rv.Center; }, null); }); } } private void Animate(UIView item, CGPoint center) { if (this.snapBehavior != null) { this.animator?.RemoveBehavior(this.snapBehavior); } this.animator = new UIDynamicAnimator(this.View); var tempSnapBehavior = new UISnapBehavior(item, center); this.animator?.AddBehavior(tempSnapBehavior); this.snapBehavior = tempSnapBehavior; } private void UpdateDurationStatus() { this.duration = this.duration - 1; foreach (var btn in this.buttons.Where(x => x.ShowDurationStatus)) { var txt = $"{btn.InitialTitle} {this.duration}"; btn.SetTitle(txt, UIControlState.Normal); } } // Close SCLAlertView public void HideView() { UIView.AnimateNotify(0.2, () => { this.View.Alpha = 0; }, completion => { //Stop durationTimer so alertView does not attempt to hide itself and fire it's dimiss block a second time when close button is tapped this.durationTimer?.Invalidate(); // Stop StatusTimer this.durationStatusTimer?.Invalidate(); // Call completion handler when the alert is dismissed this.dismissBlock?.Invoke(); // This is necessary for SCLAlertView to be de-initialized, preventing a strong reference cycle with the viewcontroller calling SCLAlertView. foreach (var button in this.buttons) { button.Action = null; } this.View.RemoveFromSuperview(); OnClosed(this, new InteractiveAlertViewEventArgs(this)); }); } protected static UIImage checkCircleIconImage(UIImage circleIconImage, UIImage defaultImage) { return circleIconImage ?? defaultImage; } private static UIViewAnimationOptions ConvertToAnimationOptions(UIViewAnimationCurve curve) { // Looks like a hack. But it is correct. // UIViewAnimationCurve and UIViewAnimationOptions are shifted by 16 bits // http://stackoverflow.com/questions/18870447/how-to-use-the-default-ios7-uianimation-curve/18873820#18873820 return (UIViewAnimationOptions) ((int) curve << 16); } private static UIColor GetDefaultColorTextButton(InteractiveAlertStyle style) { switch (style) { case InteractiveAlertStyle.Success: case InteractiveAlertStyle.Error: //case InteractiveAlertStyle.Notice: //case InteractiveAlertStyle.Info: case InteractiveAlertStyle.Wait: case InteractiveAlertStyle.Edit: //case InteractiveAlertStyle.Question: return UIColor.White; case InteractiveAlertStyle.Warning: return UIColor.Black; default: return UIColor.White; } } private static UIColor GetDefaultColorStyle(InteractiveAlertStyle style) { switch (style) { case InteractiveAlertStyle.Success: // 0x22B573 return UIColor.FromRGB(34, 181, 115); case InteractiveAlertStyle.Error: // 0xC1272D return UIColor.FromRGB(193, 39, 45); //case InteractiveAlertStyle.Notice: //// 0x727375 //return UIColor.FromRGB(114, 115, 117); case InteractiveAlertStyle.Warning: // 0xFFD110 return UIColor.FromRGB(255, 209, 16); //case InteractiveAlertStyle.Info: //// 0x2866BF //return UIColor.FromRGB(40, 102, 191); case InteractiveAlertStyle.Edit: // 0xA429FF return UIColor.FromRGB(164, 41, 255); case InteractiveAlertStyle.Wait: // 0xD62DA5 return UIColor.FromRGB(204, 45, 165); //case InteractiveAlertStyle.Question: //// 0x727375 //return UIColor.FromRGB(114, 115, 117); default: return UIColor.White; } } public class SCLAppearance { public nfloat DefaultShadowOpacity { get; set; } = 0.7f; public nfloat CircleTopPosition { get; set; } = 0.0f; public nfloat CircleBackgroundTopPosition { get; set; } = 6.0f; public nfloat CircleHeight { get; set; } = 56.0f; public nfloat CircleIconHeight { get; set; } = 20.0f; public nfloat TitleTop { get; set; } = 30.0f; public nfloat TitleHeight { get; set; } = 25.0f; public nfloat TitleMinimumScaleFactor { get; set; } = 1.0f; public nfloat WindowWidth { get; set; } = 240.0f; public nfloat WindowHeight { get; set; } = 178.0f; public nfloat TextHeight { get; set; } = 90.0f; public nfloat TextFieldHeight { get; set; } = 45.0f; public nfloat TextViewdHeight { get; set; } = 80.0f; public nfloat ButtonHeight { get; set; } = 45.0f; public UIColor CircleBackgroundColor { get; set; } = UIColor.White; public UIColor ContentViewColor { get; set; } = UIColor.White; // 0xCCCCCC public UIColor ContentViewBorderColor { get; set; } = UIColor.FromRGB(204, 204, 204); // 0x4D4D4D public UIColor TitleColor { get; set; } = UIColor.FromRGB(77, 77, 77); // Fonts public UIFont TitleFont { get; set; } = UIFont.SystemFontOfSize(20); public UIFont TextFont { get; set; } = UIFont.SystemFontOfSize(14); public UIFont ButtonFont { get; set; } = UIFont.SystemFontOfSize(14); // UI Options public bool DisableTapGesture { get; set; } public bool ShowCloseButton { get; set; } = true; public bool ShowCircularIcon { get; set; } = true; // Set this false to 'Disable' Auto hideView when SCLButton is tapped public bool ShouldAutoDismiss { get; set; } = true; public nfloat ContentViewCornerRadius { get; set; } = 5.0f; public nfloat FieldCornerRadius { get; set; } = 3.0f; public nfloat ButtonCornerRadius { get; set; } = 3.0f; public bool DynamicAnimatorActive { get; set; } = false; // Actions public bool HideWhenBackgroundViewIsTapped { get; set; } public void SetWindowHeight(nfloat kWindowHeight) { this.WindowHeight = kWindowHeight; } public void SetTextHeight(nfloat kTextHeight) { this.TextHeight = kTextHeight; } } // Button sub-class public class SCLButton : UIButton { public SCLButton() : base(CGRect.Empty) { } public SCLButton(CGRect rect) : base(rect) { } public SCLActionType ActionType { get; set; } = SCLActionType.None; public UIColor CustomBackgroundColor { get; set; } public UIColor CustomTextColor { get; set; } public string InitialTitle { get; set; } public bool ShowDurationStatus { get; set; } public Action Action { get; set; } } protected static class SCLAlertViewExtension { public static nfloat heightWithConstrainedWidth(string text, nfloat width, UIFont font) { var constraintRect = new CGSize(width, nfloat.MaxValue); var boundingBox = new NSString(text).GetBoundingRect(constraintRect, NSStringDrawingOptions.UsesLineFragmentOrigin, new UIStringAttributes {Font = font}, null); return boundingBox.Height; } } // ------------------------------------ // Icon drawing // Code generated by PaintCode // ------------------------------------ protected class SCLAlertViewStyleKit : NSObject { public static UIImage ImageOfCheckmark() { return RendererandCacheImage(drawCheckmark, ref Cache.imageOfCheckmarkImage); } public static UIImage ImageOfCross() { return RendererandCacheImage(drawCross, ref Cache.imageOfCrossImage); } public static UIImage ImageOfNotice() { return RendererandCacheImage(drawNotice, ref Cache.imageOfNoticeImage); } public static UIImage ImageOfWarning() { return RendererandCacheImage(drawWarning, ref Cache.imageOfWarningImage); } public static UIImage ImageOfInfo() { return RendererandCacheImage(drawInfo, ref Cache.imageOfInfoImage); } public static UIImage ImageOfEdit() { return RendererandCacheImage(drawEdit, ref Cache.imageOfEditImage); } public static UIImage ImageOfQuestion() { return RendererandCacheImage(drawQuestion, ref Cache.imageOfQuestionImage); } private static UIImage RendererandCacheImage(Action rendererAction, ref UIImage image) { if (image != null) { return image; } UIGraphics.BeginImageContextWithOptions(new CGSize(80, 80), false, 0); rendererAction.Invoke(); image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); return image; } // Drawing Methods private static void drawCheckmark() { // Checkmark Shape Drawing var checkmarkShapePath = new UIBezierPath(); checkmarkShapePath.MoveTo(new CGPoint(73.25, 14.05)); checkmarkShapePath.AddCurveToPoint(new CGPoint(64.51, 13.86), new CGPoint(70.98, 11.44), new CGPoint(66.78, 11.26)); checkmarkShapePath.AddLineTo(new CGPoint(27.46, 52)); checkmarkShapePath.AddLineTo(new CGPoint(15.75, 39.54)); checkmarkShapePath.AddCurveToPoint(new CGPoint(6.84, 39.54), new CGPoint(13.48, 36.93), new CGPoint(9.28, 36.93)); checkmarkShapePath.AddCurveToPoint(new CGPoint(6.84, 49.02), new CGPoint(4.39, 42.14), new CGPoint(4.39, 46.42)); checkmarkShapePath.AddLineTo(new CGPoint(22.91, 66.14)); checkmarkShapePath.AddCurveToPoint(new CGPoint(27.28, 68), new CGPoint(24.14, 67.44), new CGPoint(25.71, 68)); checkmarkShapePath.AddCurveToPoint(new CGPoint(31.65, 66.14), new CGPoint(28.86, 68), new CGPoint(30.43, 67.26)); checkmarkShapePath.AddLineTo(new CGPoint(73.08, 23.35)); checkmarkShapePath.AddCurveToPoint(new CGPoint(73.25, 14.05), new CGPoint(75.52, 20.75), new CGPoint(75.7, 16.65)); checkmarkShapePath.ClosePath(); checkmarkShapePath.MiterLimit = 4; UIColor.White.SetFill(); checkmarkShapePath.Fill(); } private static void drawCross() { // Cross Shape Drawing var crossShapePath = new UIBezierPath(); crossShapePath.MoveTo(new CGPoint(10, 70)); crossShapePath.AddLineTo(new CGPoint(70, 10)); crossShapePath.MoveTo(new CGPoint(10, 10)); crossShapePath.AddLineTo(new CGPoint(70, 70)); crossShapePath.LineCapStyle = CGLineCap.Round; crossShapePath.LineJoinStyle = CGLineJoin.Round; UIColor.White.SetStroke(); crossShapePath.LineWidth = 14; crossShapePath.Stroke(); } private static void drawNotice() { // Notice Shape Drawing var noticeShapePath = new UIBezierPath(); noticeShapePath.MoveTo(new CGPoint(72, 48.54)); noticeShapePath.AddLineTo(new CGPoint(72, 39.9)); noticeShapePath.AddCurveToPoint(new CGPoint(66.38, 34.01), new CGPoint(72, 36.76), new CGPoint(69.48, 34.01)); noticeShapePath.AddCurveToPoint(new CGPoint(61.53, 35.97), new CGPoint(64.82, 34.01), new CGPoint(62.69, 34.8)); noticeShapePath.AddCurveToPoint(new CGPoint(60.36, 35.78), new CGPoint(61.33, 35.97), new CGPoint(62.3, 35.78)); noticeShapePath.AddLineTo(new CGPoint(60.36, 33.22)); noticeShapePath.AddCurveToPoint(new CGPoint(54.16, 26.16), new CGPoint(60.36, 29.3), new CGPoint(57.65, 26.16)); noticeShapePath.AddCurveToPoint(new CGPoint(48.73, 29.89), new CGPoint(51.64, 26.16), new CGPoint(50.67, 27.73)); noticeShapePath.AddLineTo(new CGPoint(48.73, 28.71)); noticeShapePath.AddCurveToPoint(new CGPoint(43.49, 21.64), new CGPoint(48.73, 24.78), new CGPoint(46.98, 21.64)); noticeShapePath.AddCurveToPoint(new CGPoint(39.03, 25.37), new CGPoint(40.97, 21.64), new CGPoint(39.03, 23.01)); noticeShapePath.AddLineTo(new CGPoint(39.03, 9.07)); noticeShapePath.AddCurveToPoint(new CGPoint(32.24, 2), new CGPoint(39.03, 5.14), new CGPoint(35.73, 2)); noticeShapePath.AddCurveToPoint(new CGPoint(25.45, 9.07), new CGPoint(28.56, 2), new CGPoint(25.45, 5.14)); noticeShapePath.AddLineTo(new CGPoint(25.45, 41.47)); noticeShapePath.AddCurveToPoint(new CGPoint(24.29, 43.44), new CGPoint(25.45, 42.45), new CGPoint(24.68, 43.04)); noticeShapePath.AddCurveToPoint(new CGPoint(9.55, 43.04), new CGPoint(16.73, 40.88), new CGPoint(11.88, 40.69)); noticeShapePath.AddCurveToPoint(new CGPoint(8, 46.58), new CGPoint(8.58, 43.83), new CGPoint(8, 45.2)); noticeShapePath.AddCurveToPoint(new CGPoint(14.4, 55.81), new CGPoint(8.19, 50.31), new CGPoint(12.07, 53.84)); noticeShapePath.AddLineTo(new CGPoint(27.2, 69.56)); noticeShapePath.AddCurveToPoint(new CGPoint(42.91, 77.8), new CGPoint(30.5, 74.47), new CGPoint(35.73, 77.21)); noticeShapePath.AddCurveToPoint(new CGPoint(43.88, 77.8), new CGPoint(43.3, 77.8), new CGPoint(43.68, 77.8)); noticeShapePath.AddCurveToPoint(new CGPoint(47.18, 78), new CGPoint(45.04, 77.8), new CGPoint(46.01, 78)); noticeShapePath.AddLineTo(new CGPoint(48.34, 78)); noticeShapePath.AddLineTo(new CGPoint(48.34, 78)); noticeShapePath.AddCurveToPoint(new CGPoint(71.61, 52.08), new CGPoint(56.48, 78), new CGPoint(69.87, 75.05)); noticeShapePath.AddCurveToPoint(new CGPoint(72, 48.54), new CGPoint(71.81, 51.29), new CGPoint(72, 49.72)); noticeShapePath.ClosePath(); noticeShapePath.MiterLimit = 4; UIColor.White.SetFill(); noticeShapePath.Fill(); } private static void drawWarning() { // Color Declarations var greyColor = new UIColor(0.236f, 0.236f, 0.236f, 1.000f); // Warning Group // Warning Circle Drawing var warningCirclePath = new UIBezierPath(); warningCirclePath.MoveTo(new CGPoint(40.94, 63.39)); warningCirclePath.AddCurveToPoint(new CGPoint(36.03, 65.55), new CGPoint(39.06, 63.39), new CGPoint(37.36, 64.18)); warningCirclePath.AddCurveToPoint(new CGPoint(34.14, 70.45), new CGPoint(34.9, 66.92), new CGPoint(34.14, 68.49)); warningCirclePath.AddCurveToPoint(new CGPoint(36.22, 75.54), new CGPoint(34.14, 72.41), new CGPoint(34.9, 74.17)); warningCirclePath.AddCurveToPoint(new CGPoint(40.94, 77.5), new CGPoint(37.54, 76.91), new CGPoint(39.06, 77.5)); warningCirclePath.AddCurveToPoint(new CGPoint(45.86, 75.35), new CGPoint(42.83, 77.5), new CGPoint(44.53, 76.72)); warningCirclePath.AddCurveToPoint(new CGPoint(47.93, 70.45), new CGPoint(47.18, 74.17), new CGPoint(47.93, 72.41)); warningCirclePath.AddCurveToPoint(new CGPoint(45.86, 65.35), new CGPoint(47.93, 68.49), new CGPoint(47.18, 66.72)); warningCirclePath.AddCurveToPoint(new CGPoint(40.94, 63.39), new CGPoint(44.53, 64.18), new CGPoint(42.83, 63.39)); warningCirclePath.ClosePath(); warningCirclePath.MiterLimit = 4; greyColor.SetFill(); warningCirclePath.Fill(); // Warning Shape Drawing var warningShapePath = new UIBezierPath(); warningShapePath.MoveTo(new CGPoint(46.23, 4.26)); warningShapePath.AddCurveToPoint(new CGPoint(40.94, 2.5), new CGPoint(44.91, 3.09), new CGPoint(43.02, 2.5)); warningShapePath.AddCurveToPoint(new CGPoint(34.71, 4.26), new CGPoint(38.68, 2.5), new CGPoint(36.03, 3.09)); warningShapePath.AddCurveToPoint(new CGPoint(31.5, 8.77), new CGPoint(33.01, 5.44), new CGPoint(31.5, 7.01)); warningShapePath.AddLineTo(new CGPoint(31.5, 19.36)); warningShapePath.AddLineTo(new CGPoint(34.71, 54.44)); warningShapePath.AddCurveToPoint(new CGPoint(40.38, 58.16), new CGPoint(34.9, 56.2), new CGPoint(36.41, 58.16)); warningShapePath.AddCurveToPoint(new CGPoint(45.67, 54.44), new CGPoint(44.34, 58.16), new CGPoint(45.67, 56.01)); warningShapePath.AddLineTo(new CGPoint(48.5, 19.36)); warningShapePath.AddLineTo(new CGPoint(48.5, 8.77)); warningShapePath.AddCurveToPoint(new CGPoint(46.23, 4.26), new CGPoint(48.5, 7.01), new CGPoint(47.74, 5.44)); warningShapePath.ClosePath(); warningShapePath.MiterLimit = 4; greyColor.SetFill(); warningShapePath.Fill(); } private static void drawInfo() { // Color Declarations var color0 = new UIColor(1.000f, 1.000f, 1.000f, 1.000f); // Info Shape Drawing var infoShapePath = new UIBezierPath(); infoShapePath.MoveTo(new CGPoint(45.66, 15.96)); infoShapePath.AddCurveToPoint(new CGPoint(45.66, 5.22), new CGPoint(48.78, 12.99), new CGPoint(48.78, 8.19)); infoShapePath.AddCurveToPoint(new CGPoint(34.34, 5.22), new CGPoint(42.53, 2.26), new CGPoint(37.47, 2.26)); infoShapePath.AddCurveToPoint(new CGPoint(34.34, 15.96), new CGPoint(31.22, 8.19), new CGPoint(31.22, 12.99)); infoShapePath.AddCurveToPoint(new CGPoint(45.66, 15.96), new CGPoint(37.47, 18.92), new CGPoint(42.53, 18.92)); infoShapePath.ClosePath(); infoShapePath.MoveTo(new CGPoint(48, 69.41)); infoShapePath.AddCurveToPoint(new CGPoint(40, 77), new CGPoint(48, 73.58), new CGPoint(44.4, 77)); infoShapePath.AddLineTo(new CGPoint(40, 77)); infoShapePath.AddCurveToPoint(new CGPoint(32, 69.41), new CGPoint(35.6, 77), new CGPoint(32, 73.58)); infoShapePath.AddLineTo(new CGPoint(32, 35.26)); infoShapePath.AddCurveToPoint(new CGPoint(40, 27.67), new CGPoint(32, 31.08), new CGPoint(35.6, 27.67)); infoShapePath.AddLineTo(new CGPoint(40, 27.67)); infoShapePath.AddCurveToPoint(new CGPoint(48, 35.26), new CGPoint(44.4, 27.67), new CGPoint(48, 31.08)); infoShapePath.AddLineTo(new CGPoint(48, 69.41)); infoShapePath.ClosePath(); color0.SetFill(); infoShapePath.Fill(); } private static void drawEdit() { // Color Declarations var color = new UIColor(1.0f, 1.0f, 1.0f, 1.0f); // Edit shape Drawing var editPathPath = new UIBezierPath(); editPathPath.MoveTo(new CGPoint(71, 2.7)); editPathPath.AddCurveToPoint(new CGPoint(71.9, 15.2), new CGPoint(74.7, 5.9), new CGPoint(75.1, 11.6)); editPathPath.AddLineTo(new CGPoint(64.5, 23.7)); editPathPath.AddLineTo(new CGPoint(49.9, 11.1)); editPathPath.AddLineTo(new CGPoint(57.3, 2.6)); editPathPath.AddCurveToPoint(new CGPoint(69.7, 1.7), new CGPoint(60.4, -1.1), new CGPoint(66.1, -1.5)); editPathPath.AddLineTo(new CGPoint(71, 2.7)); editPathPath.AddLineTo(new CGPoint(71, 2.7)); editPathPath.ClosePath(); editPathPath.MoveTo(new CGPoint(47.8, 13.5)); editPathPath.AddLineTo(new CGPoint(13.4, 53.1)); editPathPath.AddLineTo(new CGPoint(15.7, 55.1)); editPathPath.AddLineTo(new CGPoint(50.1, 15.5)); editPathPath.AddLineTo(new CGPoint(47.8, 13.5)); editPathPath.AddLineTo(new CGPoint(47.8, 13.5)); editPathPath.ClosePath(); editPathPath.MoveTo(new CGPoint(17.7, 56.7)); editPathPath.AddLineTo(new CGPoint(23.8, 62.2)); editPathPath.AddLineTo(new CGPoint(58.2, 22.6)); editPathPath.AddLineTo(new CGPoint(52, 17.1)); editPathPath.AddLineTo(new CGPoint(17.7, 56.7)); editPathPath.AddLineTo(new CGPoint(17.7, 56.7)); editPathPath.ClosePath(); editPathPath.MoveTo(new CGPoint(25.8, 63.8)); editPathPath.AddLineTo(new CGPoint(60.1, 24.2)); editPathPath.AddLineTo(new CGPoint(62.3, 26.1)); editPathPath.AddLineTo(new CGPoint(28.1, 65.7)); editPathPath.AddLineTo(new CGPoint(25.8, 63.8)); editPathPath.AddLineTo(new CGPoint(25.8, 63.8)); editPathPath.ClosePath(); editPathPath.MoveTo(new CGPoint(25.9, 68.1)); editPathPath.AddLineTo(new CGPoint(4.2, 79.5)); editPathPath.AddLineTo(new CGPoint(11.3, 55.5)); editPathPath.AddLineTo(new CGPoint(25.9, 68.1)); editPathPath.ClosePath(); editPathPath.MiterLimit = 4; editPathPath.UsesEvenOddFillRule = true; color.SetFill(); editPathPath.Fill(); } private static void drawQuestion() { // Color Declarations var color = new UIColor(1.0f, 1.0f, 1.0f, 1.0f); // Questionmark Shape Drawing var questionShapePath = new UIBezierPath(); questionShapePath.MoveTo(new CGPoint(33.75, 54.1)); questionShapePath.AddLineTo(new CGPoint(44.15, 54.1)); questionShapePath.AddLineTo(new CGPoint(44.15, 47.5)); questionShapePath.AddCurveToPoint(new CGPoint(51.85, 37.2), new CGPoint(44.15, 42.9), new CGPoint(46.75, 41.2)); questionShapePath.AddCurveToPoint(new CGPoint(61.95, 19.9), new CGPoint(59.05, 31.6), new CGPoint(61.95, 28.5)); questionShapePath.AddCurveToPoint(new CGPoint(41.45, 2.8), new CGPoint(61.95, 7.6), new CGPoint(52.85, 2.8)); questionShapePath.AddCurveToPoint(new CGPoint(25.05, 5.8), new CGPoint(34.75, 2.8), new CGPoint(29.65, 3.8)); questionShapePath.AddLineTo(new CGPoint(25.05, 14.4)); questionShapePath.AddCurveToPoint(new CGPoint(38.15, 12.3), new CGPoint(29.15, 13.2), new CGPoint(32.35, 12.3)); questionShapePath.AddCurveToPoint(new CGPoint(49.65, 20.8), new CGPoint(45.65, 12.3), new CGPoint(49.65, 14.4)); questionShapePath.AddCurveToPoint(new CGPoint(43.65, 31.7), new CGPoint(49.65, 26), new CGPoint(47.95, 28.4)); questionShapePath.AddCurveToPoint(new CGPoint(33.75, 46.6), new CGPoint(37.15, 36.9), new CGPoint(33.75, 39.7)); questionShapePath.AddLineTo(new CGPoint(33.75, 54.1)); questionShapePath.ClosePath(); questionShapePath.MoveTo(new CGPoint(33.15, 75.4)); questionShapePath.AddLineTo(new CGPoint(45.35, 75.4)); questionShapePath.AddLineTo(new CGPoint(45.35, 63.7)); questionShapePath.AddLineTo(new CGPoint(33.15, 63.7)); questionShapePath.AddLineTo(new CGPoint(33.15, 75.4)); questionShapePath.ClosePath(); color.SetFill(); questionShapePath.Fill(); } // Cache private static class Cache { public static UIImage imageOfCheckmarkImage; public static UIImage imageOfCrossImage; public static UIImage imageOfNoticeImage; public static UIImage imageOfWarningImage; public static UIImage imageOfInfoImage; public static UIImage imageOfEditImage; public static UIImage imageOfQuestionImage; } } private static void OnPresented(object sender, InteractiveAlertViewEventArgs e) { Presented?.Invoke(sender, e); } private static void OnClosed(object sender,InteractiveAlertViewEventArgs e) { Closed?.Invoke(sender, e); } } // Allow alerts to be closed/renamed in a chainable manner // Example: SCLAlertView().showSuccess(self, title: "Test", subTitle: "Value").close() public class SCLAlertViewResponder { // Initialisation and Title/Subtitle/Close functions public SCLAlertViewResponder(InteractiveAlertView alertview) { this.Alertview = alertview; } protected InteractiveAlertView Alertview { get; } public void SetTitle(string title) { this.Alertview.SetTitle(title); } public void SetSubTitle(string subTitle) { this.Alertview.SetSubTitle(subTitle); } public void Close() { this.Alertview.HideView(); } public void SetDismissBlock(Action dismissBlock) { this.Alertview.SetDismissBlock(dismissBlock); } } public class InteractiveAlertViewEventArgs : EventArgs { public InteractiveAlertViewEventArgs(InteractiveAlertView alertView) { this.AlertView = alertView; } public InteractiveAlertView AlertView { get; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class VHWayPointNavigator : MonoBehaviour { #region Constants public enum PathLoopType { // when you reach the end of a path... Loop, // return to the path start point and do it again PingPong, // go back the way you came Stop, // just stop once you've reached the final waypoint } public enum PathFollowingType { // how you move along the path Lerp, SmoothStep, } public delegate void OnPathCompleted(List<Vector3> pathFollowed); public delegate void OnWayPointReached(VHWayPointNavigator navaigator, Vector3 wp, int wpId, int totalNumWPs); #endregion #region Variables [SerializeField] float m_Speed = 10; [SerializeField] float m_AngularVelocity = 90; [SerializeField] bool m_TurnTowardsTargetPosition = true; [SerializeField] bool m_IgnoreHeight = false; [SerializeField] bool m_ImmediatelyStartPathing = true; [SerializeField] PathLoopType m_LoopType = PathLoopType.Stop; [SerializeField] PathFollowingType m_FollowingType = PathFollowingType.Lerp; [SerializeField] GameObject m_Pather; [SerializeField] GameObject[] WayPoints; List<Vector3> m_WayPoints = new List<Vector3>(); int m_nPrevWP = -1; // the waypoint that you're coming from int m_nNextWP = 0; // the waypoint that you are moving towards float m_fTimeToReachTarget; float m_fCurrentTime = 0; bool m_bInReverse = false; bool m_bIsPathing = false; //Vector3 m_PathDirection = new Vector3(); protected OnPathCompleted m_PathCompletedCallback; protected OnWayPointReached m_WayPointReachedCallback; #endregion #region Properties public Vector3 PreviousPosition { get { return m_WayPoints[m_nPrevWP]; } } public Vector3 TargetPosition { get { return m_WayPoints[m_nNextWP]; } } public int PrevWP { get { return m_nPrevWP; } } public int NextWP { get { return m_nNextWP; } } public bool IsPathing { get { return m_bIsPathing; } } public int NumWayPoints { get { return m_WayPoints.Count; } } public bool TurnTowardsTargetPosition { get { return m_TurnTowardsTargetPosition; } set { m_TurnTowardsTargetPosition = value; } } public bool ImmediatelyStartPathing { get { return m_ImmediatelyStartPathing; } set { m_ImmediatelyStartPathing = value; } } public GameObject Pather { get { return m_Pather; } set { m_Pather = value; } } public float AngularVelocity { get { return m_AngularVelocity; } set { m_AngularVelocity = value; } } public Vector3 TurnTarget { get { return m_IgnoreHeight ? new Vector3(TargetPosition.x, m_Pather.transform.position.y, TargetPosition.z) : TargetPosition; } } public PathFollowingType FollowingType { get { return m_FollowingType; } set { m_FollowingType = value; } } #endregion #region Functions public void SetIsPathing(bool isPathing) { if (isPathing && m_LoopType == PathLoopType.Stop && (m_nPrevWP >= m_WayPoints.Count || m_nNextWP >= m_WayPoints.Count)) { // they've already completed their path, so there's nowhere to path to Debug.Log("Can't start moving again. You've completed your path and your loop type is \'Stop\'"); return; } m_bIsPathing = isPathing; } public void Start() { if (m_Pather == null) { m_Pather = gameObject; } if (m_ImmediatelyStartPathing) { NavigatePath(true); } } List<Vector3> ConvertWayPointGOsToPositions(GameObject[] waypoints) { List<Vector3> waypointPositions = new List<Vector3>(); for (int i = 0; i < waypoints.Length; i++) { waypointPositions.Add(waypoints[i].transform.position); } return waypointPositions; } public void ResetPathNavigator() { m_nPrevWP = -1; m_nNextWP = 0; m_WayPoints.Clear(); } public void NavigatePath(bool forcePositionToFirstPoint) { NavigatePath(ConvertWayPointGOsToPositions(WayPoints), forcePositionToFirstPoint); } /// <summary> /// Start navigating the given waypoints /// </summary> /// <param name="wayPoints"></param> public void NavigatePath(List<Vector3> wayPoints, bool forcePositionToFirstPoint) { if (wayPoints == null || wayPoints.Count < 2) { Debug.LogError("Bad path passed into NavigatePath"); return; } if (forcePositionToFirstPoint) { m_Pather.transform.position = wayPoints[0]; m_Pather.transform.forward = (wayPoints[1] - wayPoints[0]).normalized; } SetPath(wayPoints, true); m_nPrevWP = -1; m_nNextWP = 0; SetIsPathing(true); MoveToNextWayPoint(); TurnTowardsTarget(TargetPosition, 360); } protected virtual void TurnTowardsTarget(Vector3 targetPos, float turnRateDegrees) { VHMath.TurnTowardsTarget(this, m_Pather, targetPos, turnRateDegrees); } /// <summary> /// This doesn't reset the current and next wp indices /// </summary> /// <param name="wayPoints"></param> public void SetPath(List<Vector3> wayPoints, bool bContinuePath) { m_WayPoints.Clear(); m_WayPoints.AddRange(wayPoints); if (m_nPrevWP > wayPoints.Count - 1) { Debug.LogError("you're new path is shorter than what you have already traversed"); } SetIsPathing(true); if(!bContinuePath) MoveToNextWayPoint(); } //public override void VHUpdate() public void Update() { if (!IsPathing) { return; } //m_PathDirection = MovementDirection(); m_Pather.transform.position = InterpolatePosition(PreviousPosition, TargetPosition, m_fCurrentTime / m_fTimeToReachTarget); if (m_fCurrentTime >= m_fTimeToReachTarget) { // they reached the next point, clamp their position to what their target was MoveToNextWayPoint(); } m_fCurrentTime += Time.deltaTime; } virtual protected Vector3 InterpolatePosition(Vector3 prevPos, Vector3 targetPos, float t) { Vector3 interpolatedPos = Vector3.zero; switch (m_FollowingType) { case PathFollowingType.SmoothStep: interpolatedPos.x = Mathf.SmoothStep(prevPos.x, targetPos.x, t); interpolatedPos.y = Mathf.SmoothStep(prevPos.y, targetPos.y, t); interpolatedPos.z = Mathf.SmoothStep(prevPos.z, targetPos.z, t); break; case PathFollowingType.Lerp: interpolatedPos = Vector3.Lerp(prevPos, targetPos, t); break; } return interpolatedPos; } void MoveToNextWayPoint() { // clamp their position to where they were going m_Pather.transform.position = m_IgnoreHeight ? new Vector3(TargetPosition.x, m_Pather.transform.position.y, TargetPosition.z) : TargetPosition; m_fCurrentTime = 0; bool bPathComplete = false; switch (m_LoopType) { case PathLoopType.Loop: if (++m_nPrevWP >= m_WayPoints.Count) { m_nPrevWP = 0; } if (++m_nNextWP >= m_WayPoints.Count) { m_nNextWP = 0; bPathComplete = true; } break; case PathLoopType.PingPong: if (m_bInReverse) { if (--m_nPrevWP < 0) m_nPrevWP = 0; if (--m_nNextWP < 0) { m_nNextWP = 1; m_bInReverse = false; bPathComplete = true; } } else { if (++m_nPrevWP >= m_WayPoints.Count) m_nPrevWP = m_WayPoints.Count - 1; if (++m_nNextWP >= m_WayPoints.Count) { m_nNextWP = m_WayPoints.Count - 2; m_bInReverse = true; bPathComplete = true; } } //m_fTimeToReachTarget = Utils.GetTimeToReachPosition(PreviousPosition, TargetPosition, m_Speed); break; case PathLoopType.Stop: ++m_nPrevWP; ++m_nNextWP; if (m_nPrevWP >= m_WayPoints.Count || m_nNextWP >= m_WayPoints.Count) { // they reached the end of the path SetIsPathing(false); bPathComplete = true; } break; } if (IsPathing) { // calculate time to reach next wp m_fTimeToReachTarget = VHMath.GetTimeToReachPosition(PreviousPosition, TargetPosition, m_Speed); if (m_TurnTowardsTargetPosition) { StopCoroutine("Internal_TurnTowardsTarget"); TurnTowardsTarget(TurnTarget, m_AngularVelocity); } } if (m_WayPointReachedCallback != null) { m_WayPointReachedCallback(this, PreviousPosition, PrevWP, m_WayPoints.Count); } if (bPathComplete && m_PathCompletedCallback != null) { m_PathCompletedCallback(m_WayPoints); } } /// <summary> /// Setups a callback that will be called when the path has been completely traversed /// </summary> /// <param name="cb"></param> public void AddPathCompletedCallback(OnPathCompleted cb) { m_PathCompletedCallback += cb; } public void AddWayPointReachedCallback(OnWayPointReached cb) { m_WayPointReachedCallback += cb; } /// <summary> /// Set how fast you move along your path /// </summary> /// <param name="speed"></param> virtual public void SetSpeed(float speed) { if (Mathf.Abs(m_Speed - speed) <= Mathf.Epsilon) return; m_Speed = speed; SetIsPathing(speed != 0); } public Vector3 MovementDirection() { Vector3 direction = (TargetPosition - m_Pather.transform.position); if (m_IgnoreHeight) { direction.y = 0; } direction.Normalize(); return direction; } public float GetTotalPathLength() { if (m_WayPoints.Count == 0) { m_WayPoints = ConvertWayPointGOsToPositions(WayPoints); } float totalPathLength = 0; for (int i = 1; i < m_WayPoints.Count; i++) { totalPathLength += Vector3.Distance(m_WayPoints[i], m_WayPoints[i - 1]); } return totalPathLength; } #endregion }
using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Util; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; using BitSet = J2N.Collections.BitSet; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReader = Lucene.Net.Index.AtomicReader; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using Directory = Lucene.Net.Store.Directory; using DocIdBitSet = Lucene.Net.Util.DocIdBitSet; using DocsEnum = Lucene.Net.Index.DocsEnum; using Document = Documents.Document; using Field = Field; using FilterStrategy = Lucene.Net.Search.FilteredQuery.FilterStrategy; using IBits = Lucene.Net.Util.IBits; using IndexReader = Lucene.Net.Index.IndexReader; using IOUtils = Lucene.Net.Util.IOUtils; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; using TestUtil = Lucene.Net.Util.TestUtil; /// <summary> /// FilteredQuery JUnit tests. /// /// <p>Created: Apr 21, 2004 1:21:46 PM /// /// /// @since 1.4 /// </summary> [TestFixture] public class TestFilteredQuery : LuceneTestCase { private IndexSearcher searcher; private IndexReader reader; private Directory directory; private Query query; private Filter filter; [SetUp] public override void SetUp() { base.SetUp(); directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy())); Document doc = new Document(); doc.Add(NewTextField("field", "one two three four five", Field.Store.YES)); doc.Add(NewTextField("sorter", "b", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("field", "one two three four", Field.Store.YES)); doc.Add(NewTextField("sorter", "d", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("field", "one two three y", Field.Store.YES)); doc.Add(NewTextField("sorter", "a", Field.Store.YES)); writer.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("field", "one two x", Field.Store.YES)); doc.Add(NewTextField("sorter", "c", Field.Store.YES)); writer.AddDocument(doc); // tests here require single segment (eg try seed // 8239472272678419952L), because SingleDocTestFilter(x) // blindly accepts that docID in any sub-segment writer.ForceMerge(1); reader = writer.GetReader(); writer.Dispose(); searcher = NewSearcher(reader); query = new TermQuery(new Term("field", "three")); filter = NewStaticFilterB(); } // must be static for serialization tests private static Filter NewStaticFilterB() { return new FilterAnonymousInnerClassHelper(); } private class FilterAnonymousInnerClassHelper : Filter { public FilterAnonymousInnerClassHelper() { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { if (acceptDocs == null) { acceptDocs = new Bits.MatchAllBits(5); } BitSet bitset = new BitSet(5); if (acceptDocs.Get(1)) { bitset.Set(1); } if (acceptDocs.Get(3)) { bitset.Set(3); } return new DocIdBitSet(bitset); } } [TearDown] public override void TearDown() { reader.Dispose(); directory.Dispose(); base.TearDown(); } [Test] public virtual void TestFilteredQuery_Mem() { // force the filter to be executed as bits TFilteredQuery(true); // force the filter to be executed as iterator TFilteredQuery(false); } private void TFilteredQuery(bool useRandomAccess) { Query filteredquery = new FilteredQuery(query, filter, RandomFilterStrategy(Random, useRandomAccess)); ScoreDoc[] hits = searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(1, hits[0].Doc); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, filteredquery, searcher); hits = searcher.Search(filteredquery, null, 1000, new Sort(new SortField("sorter", SortFieldType.STRING))).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(1, hits[0].Doc); filteredquery = new FilteredQuery(new TermQuery(new Term("field", "one")), filter, RandomFilterStrategy(Random, useRandomAccess)); hits = searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, filteredquery, searcher); filteredquery = new FilteredQuery(new MatchAllDocsQuery(), filter, RandomFilterStrategy(Random, useRandomAccess)); hits = searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, filteredquery, searcher); filteredquery = new FilteredQuery(new TermQuery(new Term("field", "x")), filter, RandomFilterStrategy(Random, useRandomAccess)); hits = searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); Assert.AreEqual(3, hits[0].Doc); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, filteredquery, searcher); filteredquery = new FilteredQuery(new TermQuery(new Term("field", "y")), filter, RandomFilterStrategy(Random, useRandomAccess)); hits = searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, filteredquery, searcher); // test boost Filter f = NewStaticFilterA(); float boost = 2.5f; BooleanQuery bq1 = new BooleanQuery(); TermQuery tq = new TermQuery(new Term("field", "one")); tq.Boost = boost; bq1.Add(tq, Occur.MUST); bq1.Add(new TermQuery(new Term("field", "five")), Occur.MUST); BooleanQuery bq2 = new BooleanQuery(); tq = new TermQuery(new Term("field", "one")); filteredquery = new FilteredQuery(tq, f, RandomFilterStrategy(Random, useRandomAccess)); filteredquery.Boost = boost; bq2.Add(filteredquery, Occur.MUST); bq2.Add(new TermQuery(new Term("field", "five")), Occur.MUST); AssertScoreEquals(bq1, bq2); Assert.AreEqual(boost, filteredquery.Boost, 0); Assert.AreEqual(1.0f, tq.Boost, 0); // the boost value of the underlying query shouldn't have changed } // must be static for serialization tests private static Filter NewStaticFilterA() { return new FilterAnonymousInnerClassHelper2(); } private class FilterAnonymousInnerClassHelper2 : Filter { public FilterAnonymousInnerClassHelper2() { } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { Assert.IsNull(acceptDocs, "acceptDocs should be null, as we have an index without deletions"); BitSet bitset = new BitSet(5); bitset.Set(0, 5); return new DocIdBitSet(bitset); } } /// <summary> /// Tests whether the scores of the two queries are the same. /// </summary> public virtual void AssertScoreEquals(Query q1, Query q2) { ScoreDoc[] hits1 = searcher.Search(q1, null, 1000).ScoreDocs; ScoreDoc[] hits2 = searcher.Search(q2, null, 1000).ScoreDocs; Assert.AreEqual(hits1.Length, hits2.Length); for (int i = 0; i < hits1.Length; i++) { Assert.AreEqual(hits1[i].Score, hits2[i].Score, 0.000001f); } } /// <summary> /// this tests FilteredQuery's rewrite correctness /// </summary> [Test] public virtual void TestRangeQuery() { // force the filter to be executed as bits TRangeQuery(true); TRangeQuery(false); } private void TRangeQuery(bool useRandomAccess) { TermRangeQuery rq = TermRangeQuery.NewStringRange("sorter", "b", "d", true, true); Query filteredquery = new FilteredQuery(rq, filter, RandomFilterStrategy(Random, useRandomAccess)); ScoreDoc[] hits = searcher.Search(filteredquery, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, filteredquery, searcher); } [Test] public virtual void TestBooleanMUST() { // force the filter to be executed as bits TBooleanMUST(true); // force the filter to be executed as iterator TBooleanMUST(false); } private void TBooleanMUST(bool useRandomAccess) { BooleanQuery bq = new BooleanQuery(); Query query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(0), RandomFilterStrategy(Random, useRandomAccess)); bq.Add(query, Occur.MUST); query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(1), RandomFilterStrategy(Random, useRandomAccess)); bq.Add(query, Occur.MUST); ScoreDoc[] hits = searcher.Search(bq, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, query, searcher); } [Test] public virtual void TestBooleanSHOULD() { // force the filter to be executed as bits TBooleanSHOULD(true); // force the filter to be executed as iterator TBooleanSHOULD(false); } private void TBooleanSHOULD(bool useRandomAccess) { BooleanQuery bq = new BooleanQuery(); Query query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(0), RandomFilterStrategy(Random, useRandomAccess)); bq.Add(query, Occur.SHOULD); query = new FilteredQuery(new TermQuery(new Term("field", "one")), new SingleDocTestFilter(1), RandomFilterStrategy(Random, useRandomAccess)); bq.Add(query, Occur.SHOULD); ScoreDoc[] hits = searcher.Search(bq, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, query, searcher); } // Make sure BooleanQuery, which does out-of-order // scoring, inside FilteredQuery, works [Test] public virtual void TestBoolean2() { // force the filter to be executed as bits TBoolean2(true); // force the filter to be executed as iterator TBoolean2(false); } private void TBoolean2(bool useRandomAccess) { BooleanQuery bq = new BooleanQuery(); Query query = new FilteredQuery(bq, new SingleDocTestFilter(0), RandomFilterStrategy(Random, useRandomAccess)); bq.Add(new TermQuery(new Term("field", "one")), Occur.SHOULD); bq.Add(new TermQuery(new Term("field", "two")), Occur.SHOULD); ScoreDoc[] hits = searcher.Search(query, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, query, searcher); } [Test] public virtual void TestChainedFilters() { // force the filter to be executed as bits TChainedFilters(true); // force the filter to be executed as iterator TChainedFilters(false); } private void TChainedFilters(bool useRandomAccess) { Query query = new FilteredQuery(new FilteredQuery(new MatchAllDocsQuery(), new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("field", "three")))), RandomFilterStrategy(Random, useRandomAccess)), new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("field", "four")))), RandomFilterStrategy(Random, useRandomAccess)); ScoreDoc[] hits = searcher.Search(query, 10).ScoreDocs; Assert.AreEqual(2, hits.Length); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, query, searcher); // one more: query = new FilteredQuery(query, new CachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("field", "five")))), RandomFilterStrategy(Random, useRandomAccess)); hits = searcher.Search(query, 10).ScoreDocs; Assert.AreEqual(1, hits.Length); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, query, searcher); } [Test] public virtual void TestEqualsHashcode() { // some tests before, if the used queries and filters work: Assert.AreEqual(new PrefixFilter(new Term("field", "o")), new PrefixFilter(new Term("field", "o"))); Assert.IsFalse((new PrefixFilter(new Term("field", "a"))).Equals(new PrefixFilter(new Term("field", "o")))); QueryUtils.CheckHashEquals(new TermQuery(new Term("field", "one"))); QueryUtils.CheckUnequal(new TermQuery(new Term("field", "one")), new TermQuery(new Term("field", "two")) ); // now test FilteredQuery equals/hashcode: QueryUtils.CheckHashEquals(new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o")))); QueryUtils.CheckUnequal(new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o"))), new FilteredQuery(new TermQuery(new Term("field", "two")), new PrefixFilter(new Term("field", "o"))) ); QueryUtils.CheckUnequal(new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "a"))), new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o"))) ); } [Test] public virtual void TestInvalidArguments() { try { new FilteredQuery(null, null); Assert.Fail("Should throw IllegalArgumentException"); } #pragma warning disable 168 catch (ArgumentException iae) #pragma warning restore 168 { // pass } try { new FilteredQuery(new TermQuery(new Term("field", "one")), null); Assert.Fail("Should throw IllegalArgumentException"); } #pragma warning disable 168 catch (ArgumentException iae) #pragma warning restore 168 { // pass } try { new FilteredQuery(null, new PrefixFilter(new Term("field", "o"))); Assert.Fail("Should throw IllegalArgumentException"); } #pragma warning disable 168 catch (ArgumentException iae) #pragma warning restore 168 { // pass } } private FilterStrategy RandomFilterStrategy() { return RandomFilterStrategy(Random, true); } private void AssertRewrite(FilteredQuery fq, Type clazz) { // assign crazy boost to FQ float boost = (float)Random.NextDouble() * 100.0f; fq.Boost = boost; // assign crazy boost to inner float innerBoost = (float)Random.NextDouble() * 100.0f; fq.Query.Boost = innerBoost; // check the class and boosts of rewritten query Query rewritten = searcher.Rewrite(fq); Assert.IsTrue(clazz.IsInstanceOfType(rewritten), "is not instance of " + clazz.Name); if (rewritten is FilteredQuery) { Assert.AreEqual(boost, rewritten.Boost, 1E-5f); Assert.AreEqual(innerBoost, ((FilteredQuery)rewritten).Query.Boost, 1E-5f); Assert.AreEqual(fq.Strategy, ((FilteredQuery)rewritten).Strategy); } else { Assert.AreEqual(boost * innerBoost, rewritten.Boost, 1E-5f); } // check that the original query was not modified Assert.AreEqual(boost, fq.Boost, 1E-5f); Assert.AreEqual(innerBoost, fq.Query.Boost, 1E-5f); } [Test] public virtual void TestRewrite() { AssertRewrite(new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o")), RandomFilterStrategy()), typeof(FilteredQuery)); AssertRewrite(new FilteredQuery(new PrefixQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o")), RandomFilterStrategy()), typeof(FilteredQuery)); } [Test] public virtual void TestGetFilterStrategy() { FilterStrategy randomFilterStrategy = RandomFilterStrategy(); FilteredQuery filteredQuery = new FilteredQuery(new TermQuery(new Term("field", "one")), new PrefixFilter(new Term("field", "o")), randomFilterStrategy); Assert.AreSame(randomFilterStrategy, filteredQuery.Strategy); } private static FilteredQuery.FilterStrategy RandomFilterStrategy(Random random, bool useRandomAccess) { if (useRandomAccess) { return new RandomAccessFilterStrategyAnonymousInnerClassHelper(); } return TestUtil.RandomFilterStrategy(random); } private class RandomAccessFilterStrategyAnonymousInnerClassHelper : FilteredQuery.RandomAccessFilterStrategy { public RandomAccessFilterStrategyAnonymousInnerClassHelper() { } protected override bool UseRandomAccess(IBits bits, int firstFilterDoc) { return true; } } /* * Test if the QueryFirst strategy calls the bits only if the document has * been matched by the query and not otherwise */ [Test] public virtual void TestQueryFirstFilterStrategy() { Directory directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); int numDocs = AtLeast(50); int totalDocsWithZero = 0; for (int i = 0; i < numDocs; i++) { Document doc = new Document(); int num = Random.Next(5); if (num == 0) { totalDocsWithZero++; } doc.Add(NewTextField("field", "" + num, Field.Store.YES)); writer.AddDocument(doc); } IndexReader reader = writer.GetReader(); writer.Dispose(); IndexSearcher searcher = NewSearcher(reader); Query query = new FilteredQuery(new TermQuery(new Term("field", "0")), new FilterAnonymousInnerClassHelper3(this, reader), FilteredQuery.QUERY_FIRST_FILTER_STRATEGY); TopDocs search = searcher.Search(query, 10); Assert.AreEqual(totalDocsWithZero, search.TotalHits); IOUtils.Dispose(reader, writer, directory); } private class FilterAnonymousInnerClassHelper3 : Filter { private readonly TestFilteredQuery outerInstance; private IndexReader reader; public FilterAnonymousInnerClassHelper3(TestFilteredQuery outerInstance, IndexReader reader) { this.outerInstance = outerInstance; this.reader = reader; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { bool nullBitset = Random.Next(10) == 5; AtomicReader reader = context.AtomicReader; DocsEnum termDocsEnum = reader.GetTermDocsEnum(new Term("field", "0")); if (termDocsEnum == null) { return null; // no docs -- return null } BitSet bitSet = new BitSet(reader.MaxDoc); int d; while ((d = termDocsEnum.NextDoc()) != DocsEnum.NO_MORE_DOCS) { bitSet.Set(d); } return new DocIdSetAnonymousInnerClassHelper(this, nullBitset, reader, bitSet); } private class DocIdSetAnonymousInnerClassHelper : DocIdSet { private readonly FilterAnonymousInnerClassHelper3 outerInstance; private readonly bool nullBitset; private readonly AtomicReader reader; private readonly BitSet bitSet; public DocIdSetAnonymousInnerClassHelper(FilterAnonymousInnerClassHelper3 outerInstance, bool nullBitset, AtomicReader reader, BitSet bitSet) { this.outerInstance = outerInstance; this.nullBitset = nullBitset; this.reader = reader; this.bitSet = bitSet; } public override IBits Bits { get { if (nullBitset) { return null; } return new BitsAnonymousInnerClassHelper(this); } } private class BitsAnonymousInnerClassHelper : IBits { private readonly DocIdSetAnonymousInnerClassHelper outerInstance; public BitsAnonymousInnerClassHelper(DocIdSetAnonymousInnerClassHelper outerInstance) { this.outerInstance = outerInstance; } public bool Get(int index) { Assert.IsTrue(outerInstance.bitSet.Get(index), "filter was called for a non-matching doc"); return outerInstance.bitSet.Get(index); } public int Length => outerInstance.bitSet.Length; } public override DocIdSetIterator GetIterator() { Assert.IsTrue(nullBitset, "iterator should not be called if bitset is present"); return reader.GetTermDocsEnum(new Term("field", "0")); } } } /* * Test if the leapfrog strategy works correctly in terms * of advancing / next the right thing first */ [Test] public virtual void TestLeapFrogStrategy() { Directory directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); int numDocs = AtLeast(50); int totalDocsWithZero = 0; for (int i = 0; i < numDocs; i++) { Document doc = new Document(); int num = Random.Next(10); if (num == 0) { totalDocsWithZero++; } doc.Add(NewTextField("field", "" + num, Field.Store.YES)); writer.AddDocument(doc); } IndexReader reader = writer.GetReader(); writer.Dispose(); bool queryFirst = Random.NextBoolean(); IndexSearcher searcher = NewSearcher(reader); Query query = new FilteredQuery(new TermQuery(new Term("field", "0")), new FilterAnonymousInnerClassHelper4(this, queryFirst), queryFirst ? FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY : Random .NextBoolean() ? FilteredQuery.RANDOM_ACCESS_FILTER_STRATEGY : FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY); // if filterFirst, we can use random here since bits are null TopDocs search = searcher.Search(query, 10); Assert.AreEqual(totalDocsWithZero, search.TotalHits); IOUtils.Dispose(reader, writer, directory); } private class FilterAnonymousInnerClassHelper4 : Filter { private readonly TestFilteredQuery outerInstance; private readonly bool queryFirst; public FilterAnonymousInnerClassHelper4(TestFilteredQuery outerInstance, bool queryFirst) { this.outerInstance = outerInstance; this.queryFirst = queryFirst; } public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs) { return new DocIdSetAnonymousInnerClassHelper2(this, context); } private class DocIdSetAnonymousInnerClassHelper2 : DocIdSet { private readonly FilterAnonymousInnerClassHelper4 outerInstance; private readonly AtomicReaderContext context; public DocIdSetAnonymousInnerClassHelper2(FilterAnonymousInnerClassHelper4 outerInstance, AtomicReaderContext context) { this.outerInstance = outerInstance; this.context = context; } public override IBits Bits => null; public override DocIdSetIterator GetIterator() { DocsEnum termDocsEnum = ((AtomicReader)context.Reader).GetTermDocsEnum(new Term("field", "0")); if (termDocsEnum == null) { return null; } return new DocIdSetIteratorAnonymousInnerClassHelper(this, termDocsEnum); } private class DocIdSetIteratorAnonymousInnerClassHelper : DocIdSetIterator { private readonly DocIdSetAnonymousInnerClassHelper2 outerInstance; private readonly DocsEnum termDocsEnum; public DocIdSetIteratorAnonymousInnerClassHelper(DocIdSetAnonymousInnerClassHelper2 outerInstance, DocsEnum termDocsEnum) { this.outerInstance = outerInstance; this.termDocsEnum = termDocsEnum; } internal bool nextCalled; internal bool advanceCalled; public override int NextDoc() { Assert.IsTrue(nextCalled || advanceCalled ^ !outerInstance.outerInstance.queryFirst, "queryFirst: " + outerInstance.outerInstance.queryFirst + " advanced: " + advanceCalled + " next: " + nextCalled); nextCalled = true; return termDocsEnum.NextDoc(); } public override int DocID => termDocsEnum.DocID; public override int Advance(int target) { Assert.IsTrue(advanceCalled || nextCalled ^ outerInstance.outerInstance.queryFirst, "queryFirst: " + outerInstance.outerInstance.queryFirst + " advanced: " + advanceCalled + " next: " + nextCalled); advanceCalled = true; return termDocsEnum.Advance(target); } public override long GetCost() { return termDocsEnum.GetCost(); } } } } } }
// Copyright (C) 2014 dot42 // // Original filename: Task.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Runtime.CompilerServices; using Android.App; using Android.Util; using Java.Util.Concurrent; using Java.Util.Concurrent.Atomic; using Dot42.Internal; using Dot42.Threading.Tasks; namespace System.Threading.Tasks { //[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)] public class Task : IAsyncResult, IDisposable { private static readonly AtomicInteger lastId = new AtomicInteger(1); private static readonly TaskFactory defaultFactory = new TaskFactory(); // With this attribute each thread has its own value so that it's correct for our Schedule code and for Parent property. //[ThreadStatic] private static readonly Java.Lang.ThreadLocal<Task> current = new Java.Lang.ThreadLocal<Task>(); private readonly int id; private readonly TaskCreationOptions creationOptions; private TaskStatus status; private object state; private TaskActionInvoker invoker; internal AtomicBoolean executing = new AtomicBoolean(false); private readonly TaskCompletionQueue<IContinuation> continuations = new TaskCompletionQueue<IContinuation>(); private readonly CancellationToken cancellationToken; private CancellationTokenRegistration? cancellationTokenRegistration; internal TaskScheduler scheduler; private TaskExceptionSlot exSlot; private const TaskCreationOptions MaxTaskCreationOptions = TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent; internal const TaskCreationOptions WorkerTaskNotSupportedOptions = TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness; #region Constuctors public Task(Action action) : this(action, TaskCreationOptions.None) { } public Task(Action action, TaskCreationOptions creationOptions) : this(action, CancellationToken.None, creationOptions) { } public Task(Action action, CancellationToken cancellationToken) : this(action, cancellationToken, TaskCreationOptions.None) { } public Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : this(TaskActionInvoker.Create(action), null, cancellationToken, creationOptions, current.Get()) { if (action == null) throw new ArgumentNullException("action"); if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None) throw new ArgumentOutOfRangeException("creationOptions"); } public Task(Action<object> action, object state) : this(action, state, TaskCreationOptions.None) { } public Task(Action<object> action, object state, TaskCreationOptions creationOptions) : this(action, state, CancellationToken.None, creationOptions) { } public Task(Action<object> action, object state, CancellationToken cancellationToken) : this(action, state, cancellationToken, TaskCreationOptions.None) { } public Task(Action<object> action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : this(TaskActionInvoker.Create(action), state, cancellationToken, creationOptions, current.Get()) { if (action == null) throw new ArgumentNullException("action"); if (creationOptions > MaxTaskCreationOptions || creationOptions < TaskCreationOptions.None) throw new ArgumentOutOfRangeException("creationOptions"); } internal Task(TaskActionInvoker invoker, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, Task parent = null, Task contAncestor = null, bool ignoreCancellation = false) { if (SynchronizationContext.Current == null) SynchronizationContext.SetSynchronizationContext(new AndroidSynchronizationContext()); this.invoker = invoker; this.creationOptions = creationOptions; this.state = state; this.id = lastId.GetAndIncrement(); this.cancellationToken = cancellationToken; //this.parent = parent = parent == null ? current : parent; // this.contAncestor = contAncestor; this.status = cancellationToken.IsCancellationRequested && !ignoreCancellation ? TaskStatus.Canceled : TaskStatus.Created; // Process creationOptions //if (parent != null && HasFlag(creationOptions, TaskCreationOptions.AttachedToParent)) // parent.AddChild(); if (cancellationToken.CanBeCanceled && !ignoreCancellation) cancellationTokenRegistration = cancellationToken.Register(l => ((Task)l).CancelReal(), this); } //static bool HasFlag(TaskCreationOptions opt, TaskCreationOptions member) //{ // return (opt & member) == member; //} #endregion #region Properties internal CancellationToken CancellationToken { get { return cancellationToken; } } /// <summary> /// Gets the state object supplied when the Task was created, or null if none was supplied. /// </summary> public object AsyncState { get { throw new NotImplementedException("System.Threading.Tasks.Task.AsyncState"); } } /// <summary> /// Gets a WaitHandle that can be used to wait for the task to complete. /// </summary> WaitHandle IAsyncResult.AsyncWaitHandle { get { throw new NotImplementedException("System.Threading.Tasks.Task.IAsyncResult.AsyncWaitHandle"); } } /// <summary> /// Gets an indication of whether the operation completed synchronously. /// </summary> bool IAsyncResult.CompletedSynchronously { get { throw new NotImplementedException("System.Threading.Tasks.Task.IAsyncResult.CompletedSynchronously"); } } /// <summary> /// Gets the TaskCreationOptions used to create this task. /// </summary> public TaskCreationOptions CreationOptions { get { return creationOptions; } } // <summary> // Returns the unique ID of the currently executing Task. // </summary> public static int? CurrentId { get { Task t = current.Get(); return t == null ? (int?)null : t.Id; } } /// <summary> /// Gets the AggregateException that caused the Task to end prematurely. /// If the Task completed successfully or has not yet thrown any exceptions, this will return null. /// </summary> public AggregateException Exception { get { return exSlot != null ? exSlot.Exception : null; } } /// <summary> /// Provides access to factory methods for creating Task and Task&lt;TResult&gt; instances. /// </summary> public static TaskFactory Factory { get { return defaultFactory; } } /// <summary> /// Gets a unique ID for this Task instance. /// </summary> public int Id { get { return id; } } /// <summary> /// Gets whether this Task instance has completed execution due to being canceled. /// </summary> public bool IsCanceled { get { return status == TaskStatus.Canceled; } } /// <summary> /// Gets whether this Task has completed. /// </summary> public bool IsCompleted { get { return status == TaskStatus.RanToCompletion || status == TaskStatus.Faulted || status == TaskStatus.Canceled; } } /// <summary> /// Gets whether the Task completed due to an unhandled exception. /// </summary> public bool IsFaulted { get { return status == TaskStatus.Faulted; } } /// <summary> /// Gets the TaskStatus of this task. /// </summary> public TaskStatus Status { get { return status; } internal set { status = value; } } TaskExceptionSlot ExceptionSlot { get { if (exSlot != null) return exSlot; lock (this) { if (exSlot == null) exSlot = new TaskExceptionSlot(this); return exSlot; } } } #endregion #region Methods #region Start public void Start() { Start(TaskScheduler.Current); } public void Start(TaskScheduler scheduler) { if (scheduler == null) throw new ArgumentNullException("scheduler"); if (status >= TaskStatus.WaitingToRun) throw new InvalidOperationException("The Task is not in a valid state to be started."); //if (IsContinuation) // throw new InvalidOperationException("Start may not be called on a continuation task"); SetupScheduler(scheduler); Schedule(); } internal void SetupScheduler(TaskScheduler scheduler) { this.scheduler = scheduler; status = TaskStatus.WaitingForActivation; } public void RunSynchronously() { RunSynchronously(TaskScheduler.Current); } public void RunSynchronously(TaskScheduler scheduler) { if (scheduler == null) throw new ArgumentNullException("scheduler"); if (Status > TaskStatus.WaitingForActivation) throw new InvalidOperationException("The task is not in a valid state to be started"); //if (IsContinuation) // throw new InvalidOperationException("RunSynchronously may not be called on a continuation task"); RunSynchronouslyCore(scheduler); } internal void RunSynchronouslyCore(TaskScheduler scheduler) { SetupScheduler(scheduler); var saveStatus = status; Status = TaskStatus.WaitingToRun; try { if (scheduler.RunInline(this, false)) return; } catch (Exception inner) { throw new TaskSchedulerException(inner); } Status = saveStatus; Start(scheduler); Wait(); } internal void Schedule() { status = TaskStatus.WaitingToRun; scheduler.QueueTask(this); } void ThreadStart() { /* Allow scheduler to break fairness of deque ordering without * breaking its semantic (the task can be executed twice but the * second time it will return immediately */ if (executing.GetAndSet(true)) return; // Disable CancellationToken direct cancellation if (cancellationTokenRegistration != null) { cancellationTokenRegistration.Value.Dispose(); cancellationTokenRegistration = null; } // If Task are ran inline on the same thread we might trash these values var saveCurrent = current.Get(); var saveScheduler = TaskScheduler.Current; current.Set(this); #if NET_4_5 TaskScheduler.Current = HasFlag (creationOptions, TaskCreationOptions.HideScheduler) ? TaskScheduler.Default : scheduler; #else TaskScheduler.Current = scheduler; #endif if (!cancellationToken.IsCancellationRequested) { status = TaskStatus.Running; try { InnerInvoke(); } catch (OperationCanceledException oce) { if (cancellationToken != CancellationToken.None && oce.CancellationToken == cancellationToken) CancelReal(); else HandleGenericException(oce); } catch (Exception e) { HandleGenericException(e); } } else { CancelReal(); } if (saveCurrent != null) current.Set(saveCurrent); if (saveScheduler != null) TaskScheduler.Current = saveScheduler; Finish(); } internal bool TrySetCanceled() { if (IsCompleted) return false; //if (!executing.TryRelaxedSet()) //{ // var sw = new SpinWait(); // while (!IsCompleted) // sw.SpinOnce(); // return false; //} CancelReal(); return true; } internal bool TrySetException(AggregateException aggregate) { if (IsCompleted) return false; //if (!executing.TryRelaxedSet()) //{ // var sw = new SpinWait(); // while (!IsCompleted) // sw.SpinOnce(); // return false; //} HandleGenericException(aggregate); return true; } internal bool TrySetExceptionObserved() { if (exSlot != null) { exSlot.Observed = true; return true; } return false; } internal void Execute() { ThreadStart(); } internal void CancelReal() { Status = TaskStatus.Canceled; ProcessCompleteDelegates(); } void HandleGenericException(Exception e) { HandleGenericException(new AggregateException(e)); } void HandleGenericException(AggregateException e) { ExceptionSlot.Exception = e; //Thread.MemoryBarrier(); Status = TaskStatus.Faulted; ProcessCompleteDelegates(); } void InnerInvoke() { //if (IsContinuation) //{ // invoker.Invoke(contAncestor, state, this); //} //else //{ invoker.Invoke(this, state, this); //} } internal void Finish() { /* // If there was children created and they all finished, we set the countdown if (childTasks != null) { if (childTasks.Signal()) ProcessChildExceptions(true); } */ // Don't override Canceled or Faulted if (status == TaskStatus.Running) { //if (childTasks == null || childTasks.IsSet) Status = TaskStatus.RanToCompletion; //else // Status = TaskStatus.WaitingForChildrenToComplete; } /* // Tell parent that we are finished if (parent != null && HasFlag(creationOptions, TaskCreationOptions.AttachedToParent) && #if NET_4_5 !HasFlag (parent.CreationOptions, TaskCreationOptions.DenyChildAttach) && #endif status != TaskStatus.WaitingForChildrenToComplete) { parent.ChildCompleted(this.Exception); } */ // Completions are already processed when task is canceled or faulted if (status == TaskStatus.RanToCompletion) ProcessCompleteDelegates(); // Reset the current thingies if (current.Get() == this) current.Set(null); if (TaskScheduler.Current == scheduler) TaskScheduler.Current = null; if (cancellationTokenRegistration.HasValue) cancellationTokenRegistration.Value.Dispose(); } void ProcessCompleteDelegates() { if (continuations.HasElements) { IContinuation continuation; while (continuations.TryGetNextCompletion(out continuation)) { //TODO: remove line below if case 828 has been solved if (continuation == null) break; continuation.Execute(); } } } #endregion public void Wait() { Wait(Timeout.Infinite, CancellationToken.None); } public void Wait(CancellationToken cancellationToken) { Wait(Timeout.Infinite, cancellationToken); } public bool Wait(TimeSpan timeout) { return Wait(CheckTimeout(timeout), CancellationToken.None); } public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, CancellationToken.None); } public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException("millisecondsTimeout"); bool result = WaitCore(millisecondsTimeout, cancellationToken); if (IsCanceled) throw new AggregateException(new TaskCanceledException(this)); var exception = Exception; if (exception != null) throw exception; return result; } internal bool WaitCore(int millisecondsTimeout, CancellationToken cancellationToken) { if (IsCompleted) return true; // If the task is ready to be run and we were supposed to wait on it indefinitely without cancellation, just run it if (Status == TaskStatus.WaitingToRun && millisecondsTimeout == Timeout.Infinite && scheduler != null && !cancellationToken.CanBeCanceled) scheduler.RunInline(this, true); bool result = true; if (!IsCompleted) { var continuation = new ManualResetContinuation(); try { ContinueWith(continuation); result = continuation.Wait(millisecondsTimeout, cancellationToken); } finally { if (!result) RemoveContinuation(continuation); continuation.Dispose(); } } return result; } public static void WaitAll(params Task[] tasks) { WaitAll(tasks, Timeout.Infinite, CancellationToken.None); } public static void WaitAll(Task[] tasks, CancellationToken cancellationToken) { WaitAll(tasks, Timeout.Infinite, cancellationToken); } public static bool WaitAll(Task[] tasks, TimeSpan timeout) { return WaitAll(tasks, CheckTimeout(timeout), CancellationToken.None); } public static bool WaitAll(Task[] tasks, int millisecondsTimeout) { return WaitAll(tasks, millisecondsTimeout, CancellationToken.None); } public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) { if (tasks == null) throw new ArgumentNullException("tasks"); bool result = true; foreach (var t in tasks) { if (t == null) throw new ArgumentException("tasks", "the tasks argument contains a null element"); result &= t.Status == TaskStatus.RanToCompletion; } if (!result) { var continuation = new CountdownContinuation(tasks.Length); try { foreach (var t in tasks) t.ContinueWith(continuation); result = continuation.Wait(millisecondsTimeout, cancellationToken); } finally { List<Exception> exceptions = null; foreach (var t in tasks) { if (result) { if (t.Status == TaskStatus.RanToCompletion) continue; if (exceptions == null) exceptions = new List<Exception>(); if (t.Exception != null) exceptions.AddRange(t.Exception.InnerExceptions); else exceptions.Add(new TaskCanceledException(t)); } else { t.RemoveContinuation(continuation); } } continuation.Dispose(); if (exceptions != null) throw new AggregateException(exceptions); } } return result; } public static int WaitAny(params Task[] tasks) { return WaitAny(tasks, Timeout.Infinite, CancellationToken.None); } public static int WaitAny(Task[] tasks, TimeSpan timeout) { return WaitAny(tasks, CheckTimeout(timeout)); } public static int WaitAny(Task[] tasks, int millisecondsTimeout) { return WaitAny(tasks, millisecondsTimeout, CancellationToken.None); } public static int WaitAny(Task[] tasks, CancellationToken cancellationToken) { return WaitAny(tasks, Timeout.Infinite, cancellationToken); } public static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) { if (tasks == null) throw new ArgumentNullException("tasks"); if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException("millisecondsTimeout"); CheckForNullTasks(tasks); if (tasks.Length > 0) { var continuation = new ManualResetContinuation(); bool result = false; try { for (int i = 0; i < tasks.Length; i++) { var t = tasks[i]; if (t.IsCompleted) return i; t.ContinueWith(continuation); } result = continuation.Wait(millisecondsTimeout, cancellationToken); if (!result) return -1; } finally { if (!result) foreach (var t in tasks) t.RemoveContinuation(continuation); continuation.Dispose(); } } int firstFinished = -1; for (int i = 0; i < tasks.Length; i++) { var t = tasks[i]; if (t.IsCompleted) { firstFinished = i; break; } } return firstFinished; } public static Task Run(Action action) { return Run(action, CancellationToken.None); } public static Task Run(Action action, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return TaskConstants.Canceled; return Task.Factory.StartNew(action, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } public static Task<TResult> Run<TResult>(Func<TResult> function) { return Run(function, CancellationToken.None); } public static Task<TResult> Run<TResult>(Func<TResult> function, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return TaskConstants<TResult>.Canceled; return Task.Factory.StartNew(function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } internal void ContinueWith(IContinuation continuation) { if (IsCompleted) { continuation.Execute(); return; } continuations.Add(continuation); // Retry in case completion was achieved but event adding was too late if (IsCompleted && continuations.Remove(continuation)) continuation.Execute(); } internal void RemoveContinuation(IContinuation continuation) { continuations.Remove(continuation); } private static int CheckTimeout(TimeSpan timeout) { try { return checked((int)timeout.TotalMilliseconds); } catch (System.OverflowException) { throw new ArgumentOutOfRangeException("timeout"); } } private static void CheckForNullTasks(Task[] tasks) { foreach (var t in tasks) if (t == null) throw new ArgumentException("tasks", "the tasks argument contains a null element"); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (!IsCompleted) throw new InvalidOperationException("A task may only be disposed if it is in a completion state"); // Set action to null so that the GC can collect the delegate and thus // any big object references that the user might have captured in a anonymous method if (disposing) { invoker = null; state = null; if (cancellationTokenRegistration != null) cancellationTokenRegistration.Value.Dispose(); } } public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredTaskAwaitable(this, continueOnCapturedContext, null); } public ConfiguredTaskAwaitable ConfigureAwait(Activity activity) { return ConfigureAwait(new InstanceReference(activity)); } #if ANDROID_11P public ConfiguredTaskAwaitable ConfigureAwait(Fragment fragment) { return ConfigureAwait(new InstanceReference(fragment)); } #endif public ConfiguredTaskAwaitable ConfigureAwait(InstanceReference instanceReference) { return new ConfiguredTaskAwaitable(this, true, instanceReference); } /// <summary> /// Gets an awaiter used to await this Task. /// </summary> /// <remarks> /// This method is intended for compiler user rather than use directly in code. /// </remarks> public TaskAwaiter GetAwaiter() { return new TaskAwaiter(this); } public static Task Delay (int millisecondsDelay) { return Delay (millisecondsDelay, CancellationToken.None); } public static Task Delay (TimeSpan delay) { return Delay (CheckTimeout (delay), CancellationToken.None); } public static Task Delay (TimeSpan delay, CancellationToken cancellationToken) { return Delay (CheckTimeout (delay), cancellationToken); } public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken) { var source = new TaskCompletionSource<object>(); var delayed = TaskMonitorService.GetService().Delay((long)millisecondsDelay, source); if (cancellationToken != CancellationToken.None) { cancellationToken.Register(() => { delayed.Cancel(false); source.SetCanceled(); }); } return source.Task; } #endregion } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Medical Conditions Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KCMDataSet : EduHubDataSet<KCM> { /// <inheritdoc /> public override string Name { get { return "KCM"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KCMDataSet(EduHubContext Context) : base(Context) { Index_KCMKEY = new Lazy<Dictionary<string, KCM>>(() => this.ToDictionary(i => i.KCMKEY)); Index_LW_DATE = new Lazy<NullDictionary<DateTime?, IReadOnlyList<KCM>>>(() => this.ToGroupedNullDictionary(i => i.LW_DATE)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KCM" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KCM" /> fields for each CSV column header</returns> internal override Action<KCM, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KCM, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KCMKEY": mapper[i] = (e, v) => e.KCMKEY = v; break; case "DESCRIPTION": mapper[i] = (e, v) => e.DESCRIPTION = v; break; case "DISABILITY": mapper[i] = (e, v) => e.DISABILITY = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KCM" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KCM" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KCM" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KCM}"/> of entities</returns> internal override IEnumerable<KCM> ApplyDeltaEntities(IEnumerable<KCM> Entities, List<KCM> DeltaEntities) { HashSet<string> Index_KCMKEY = new HashSet<string>(DeltaEntities.Select(i => i.KCMKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KCMKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KCMKEY.Remove(entity.KCMKEY); if (entity.KCMKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, KCM>> Index_KCMKEY; private Lazy<NullDictionary<DateTime?, IReadOnlyList<KCM>>> Index_LW_DATE; #endregion #region Index Methods /// <summary> /// Find KCM by KCMKEY field /// </summary> /// <param name="KCMKEY">KCMKEY value used to find KCM</param> /// <returns>Related KCM entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCM FindByKCMKEY(string KCMKEY) { return Index_KCMKEY.Value[KCMKEY]; } /// <summary> /// Attempt to find KCM by KCMKEY field /// </summary> /// <param name="KCMKEY">KCMKEY value used to find KCM</param> /// <param name="Value">Related KCM entity</param> /// <returns>True if the related KCM entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKCMKEY(string KCMKEY, out KCM Value) { return Index_KCMKEY.Value.TryGetValue(KCMKEY, out Value); } /// <summary> /// Attempt to find KCM by KCMKEY field /// </summary> /// <param name="KCMKEY">KCMKEY value used to find KCM</param> /// <returns>Related KCM entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCM TryFindByKCMKEY(string KCMKEY) { KCM value; if (Index_KCMKEY.Value.TryGetValue(KCMKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find KCM by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find KCM</param> /// <returns>List of related KCM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCM> FindByLW_DATE(DateTime? LW_DATE) { return Index_LW_DATE.Value[LW_DATE]; } /// <summary> /// Attempt to find KCM by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find KCM</param> /// <param name="Value">List of related KCM entities</param> /// <returns>True if the list of related KCM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByLW_DATE(DateTime? LW_DATE, out IReadOnlyList<KCM> Value) { return Index_LW_DATE.Value.TryGetValue(LW_DATE, out Value); } /// <summary> /// Attempt to find KCM by LW_DATE field /// </summary> /// <param name="LW_DATE">LW_DATE value used to find KCM</param> /// <returns>List of related KCM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCM> TryFindByLW_DATE(DateTime? LW_DATE) { IReadOnlyList<KCM> value; if (Index_LW_DATE.Value.TryGetValue(LW_DATE, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KCM table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KCM]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KCM]( [KCMKEY] varchar(10) NOT NULL, [DESCRIPTION] varchar(30) NULL, [DISABILITY] varchar(1) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KCM_Index_KCMKEY] PRIMARY KEY CLUSTERED ( [KCMKEY] ASC ) ); CREATE NONCLUSTERED INDEX [KCM_Index_LW_DATE] ON [dbo].[KCM] ( [LW_DATE] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCM]') AND name = N'KCM_Index_LW_DATE') ALTER INDEX [KCM_Index_LW_DATE] ON [dbo].[KCM] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCM]') AND name = N'KCM_Index_LW_DATE') ALTER INDEX [KCM_Index_LW_DATE] ON [dbo].[KCM] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KCM"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KCM"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KCM> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_KCMKEY = new List<string>(); foreach (var entity in Entities) { Index_KCMKEY.Add(entity.KCMKEY); } builder.AppendLine("DELETE [dbo].[KCM] WHERE"); // Index_KCMKEY builder.Append("[KCMKEY] IN ("); for (int index = 0; index < Index_KCMKEY.Count; index++) { if (index != 0) builder.Append(", "); // KCMKEY var parameterKCMKEY = $"@p{parameterIndex++}"; builder.Append(parameterKCMKEY); command.Parameters.Add(parameterKCMKEY, SqlDbType.VarChar, 10).Value = Index_KCMKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCM data set</returns> public override EduHubDataSetDataReader<KCM> GetDataSetDataReader() { return new KCMDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCM data set</returns> public override EduHubDataSetDataReader<KCM> GetDataSetDataReader(List<KCM> Entities) { return new KCMDataReader(new EduHubDataSetLoadedReader<KCM>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KCMDataReader : EduHubDataSetDataReader<KCM> { public KCMDataReader(IEduHubDataSetReader<KCM> Reader) : base (Reader) { } public override int FieldCount { get { return 6; } } public override object GetValue(int i) { switch (i) { case 0: // KCMKEY return Current.KCMKEY; case 1: // DESCRIPTION return Current.DESCRIPTION; case 2: // DISABILITY return Current.DISABILITY; case 3: // LW_DATE return Current.LW_DATE; case 4: // LW_TIME return Current.LW_TIME; case 5: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // DESCRIPTION return Current.DESCRIPTION == null; case 2: // DISABILITY return Current.DISABILITY == null; case 3: // LW_DATE return Current.LW_DATE == null; case 4: // LW_TIME return Current.LW_TIME == null; case 5: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KCMKEY return "KCMKEY"; case 1: // DESCRIPTION return "DESCRIPTION"; case 2: // DISABILITY return "DISABILITY"; case 3: // LW_DATE return "LW_DATE"; case 4: // LW_TIME return "LW_TIME"; case 5: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KCMKEY": return 0; case "DESCRIPTION": return 1; case "DISABILITY": return 2; case "LW_DATE": return 3; case "LW_TIME": return 4; case "LW_USER": return 5; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the importexport-2010-06-01.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.ImportExport.Model; using Amazon.ImportExport.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.ImportExport { /// <summary> /// Implementation for accessing ImportExport /// /// AWS Import/Export Service AWS Import/Export accelerates transferring large amounts /// of data between the AWS cloud and portable storage devices that you mail to us. AWS /// Import/Export transfers data directly onto and off of your storage devices using Amazon's /// high-speed internal network and bypassing the Internet. For large data sets, AWS Import/Export /// is often faster than Internet transfer and more cost effective than upgrading your /// connectivity. /// </summary> public partial class AmazonImportExportClient : AmazonServiceClient, IAmazonImportExport { #region Constructors /// <summary> /// Constructs AmazonImportExportClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonImportExportClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonImportExportConfig()) { } /// <summary> /// Constructs AmazonImportExportClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonImportExportClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonImportExportConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonImportExportClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonImportExportClient Configuration Object</param> public AmazonImportExportClient(AmazonImportExportConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonImportExportClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonImportExportClient(AWSCredentials credentials) : this(credentials, new AmazonImportExportConfig()) { } /// <summary> /// Constructs AmazonImportExportClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonImportExportClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonImportExportConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonImportExportClient with AWS Credentials and an /// AmazonImportExportClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonImportExportClient Configuration Object</param> public AmazonImportExportClient(AWSCredentials credentials, AmazonImportExportConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonImportExportClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonImportExportClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonImportExportConfig()) { } /// <summary> /// Constructs AmazonImportExportClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonImportExportClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonImportExportConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonImportExportClient with AWS Access Key ID, AWS Secret Key and an /// AmazonImportExportClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonImportExportClient Configuration Object</param> public AmazonImportExportClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonImportExportConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonImportExportClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonImportExportClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonImportExportConfig()) { } /// <summary> /// Constructs AmazonImportExportClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonImportExportClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonImportExportConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonImportExportClient with AWS Access Key ID, AWS Secret Key and an /// AmazonImportExportClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonImportExportClient Configuration Object</param> public AmazonImportExportClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonImportExportConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new QueryStringSigner(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region CancelJob /// <summary> /// This operation cancels a specified job. Only the job owner can cancel it. The operation /// fails if the job has already started or is complete. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CancelJob service method.</param> /// /// <returns>The response from the CancelJob service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.CanceledJobIdException"> /// The specified job ID has been canceled and is no longer valid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.ExpiredJobIdException"> /// Indicates that the specified job has expired out of the system. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidJobIdException"> /// The JOBID was missing, not found, or not associated with the AWS account. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.UnableToCancelJobIdException"> /// AWS Import/Export cannot cancel the job /// </exception> public CancelJobResponse CancelJob(CancelJobRequest request) { var marshaller = new CancelJobRequestMarshaller(); var unmarshaller = CancelJobResponseUnmarshaller.Instance; return Invoke<CancelJobRequest,CancelJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CancelJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CancelJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CancelJobResponse> CancelJobAsync(CancelJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CancelJobRequestMarshaller(); var unmarshaller = CancelJobResponseUnmarshaller.Instance; return InvokeAsync<CancelJobRequest,CancelJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateJob /// <summary> /// This operation initiates the process of scheduling an upload or download of your data. /// You include in the request a manifest that describes the data transfer specifics. /// The response to the request includes a job ID, which you can use in other operations, /// a signature that you use to identify your storage device, and the address where you /// should ship your storage device. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateJob service method.</param> /// /// <returns>The response from the CreateJob service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.BucketPermissionException"> /// The account specified does not have the appropriate bucket permissions. /// </exception> /// <exception cref="Amazon.ImportExport.Model.CreateJobQuotaExceededException"> /// Each account can create only a certain number of jobs per day. If you need to create /// more than this, please contact awsimportexport@amazon.com to explain your particular /// use case. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAddressException"> /// The address specified in the manifest is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidCustomsException"> /// One or more customs parameters was invalid. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidFileSystemException"> /// File system specified in export manifest is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidJobIdException"> /// The JOBID was missing, not found, or not associated with the AWS account. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidManifestFieldException"> /// One or more manifest fields was invalid. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidParameterException"> /// One or more parameters had an invalid value. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MalformedManifestException"> /// Your manifest is not well-formed. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingCustomsException"> /// One or more required customs parameters was missing from the manifest. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingManifestFieldException"> /// One or more required fields were missing from the manifest file. Please correct and /// resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingParameterException"> /// One or more required parameters was missing from the request. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MultipleRegionsException"> /// Your manifest file contained buckets from multiple regions. A job is restricted to /// buckets from one region. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.NoSuchBucketException"> /// The specified bucket does not exist. Create the specified bucket or change the manifest's /// bucket, exportBucket, or logBucket field to a bucket that the account, as specified /// by the manifest's Access Key ID, has write permissions to. /// </exception> public CreateJobResponse CreateJob(CreateJobRequest request) { var marshaller = new CreateJobRequestMarshaller(); var unmarshaller = CreateJobResponseUnmarshaller.Instance; return Invoke<CreateJobRequest,CreateJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateJobResponse> CreateJobAsync(CreateJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateJobRequestMarshaller(); var unmarshaller = CreateJobResponseUnmarshaller.Instance; return InvokeAsync<CreateJobRequest,CreateJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetShippingLabel /// <summary> /// This operation returns information about a job, including where the job is in the /// processing pipeline, the status of the results, and the signature value associated /// with the job. You can only return information about jobs you own. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetShippingLabel service method.</param> /// /// <returns>The response from the GetShippingLabel service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.CanceledJobIdException"> /// The specified job ID has been canceled and is no longer valid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.ExpiredJobIdException"> /// Indicates that the specified job has expired out of the system. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAddressException"> /// The address specified in the manifest is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidJobIdException"> /// The JOBID was missing, not found, or not associated with the AWS account. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidParameterException"> /// One or more parameters had an invalid value. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> public GetShippingLabelResponse GetShippingLabel(GetShippingLabelRequest request) { var marshaller = new GetShippingLabelRequestMarshaller(); var unmarshaller = GetShippingLabelResponseUnmarshaller.Instance; return Invoke<GetShippingLabelRequest,GetShippingLabelResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetShippingLabel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetShippingLabel operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetShippingLabelResponse> GetShippingLabelAsync(GetShippingLabelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetShippingLabelRequestMarshaller(); var unmarshaller = GetShippingLabelResponseUnmarshaller.Instance; return InvokeAsync<GetShippingLabelRequest,GetShippingLabelResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region GetStatus /// <summary> /// This operation returns information about a job, including where the job is in the /// processing pipeline, the status of the results, and the signature value associated /// with the job. You can only return information about jobs you own. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetStatus service method.</param> /// /// <returns>The response from the GetStatus service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.CanceledJobIdException"> /// The specified job ID has been canceled and is no longer valid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.ExpiredJobIdException"> /// Indicates that the specified job has expired out of the system. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidJobIdException"> /// The JOBID was missing, not found, or not associated with the AWS account. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> public GetStatusResponse GetStatus(GetStatusRequest request) { var marshaller = new GetStatusRequestMarshaller(); var unmarshaller = GetStatusResponseUnmarshaller.Instance; return Invoke<GetStatusRequest,GetStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the GetStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<GetStatusResponse> GetStatusAsync(GetStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new GetStatusRequestMarshaller(); var unmarshaller = GetStatusResponseUnmarshaller.Instance; return InvokeAsync<GetStatusRequest,GetStatusResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListJobs /// <summary> /// This operation returns the jobs associated with the requester. AWS Import/Export lists /// the jobs in reverse chronological order based on the date of creation. For example /// if Job Test1 was created 2009Dec30 and Test2 was created 2010Feb05, the ListJobs operation /// would return Test2 followed by Test1. /// </summary> /// /// <returns>The response from the ListJobs service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidParameterException"> /// One or more parameters had an invalid value. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> public ListJobsResponse ListJobs() { return ListJobs(new ListJobsRequest()); } /// <summary> /// This operation returns the jobs associated with the requester. AWS Import/Export lists /// the jobs in reverse chronological order based on the date of creation. For example /// if Job Test1 was created 2009Dec30 and Test2 was created 2010Feb05, the ListJobs operation /// would return Test2 followed by Test1. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListJobs service method.</param> /// /// <returns>The response from the ListJobs service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidParameterException"> /// One or more parameters had an invalid value. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> public ListJobsResponse ListJobs(ListJobsRequest request) { var marshaller = new ListJobsRequestMarshaller(); var unmarshaller = ListJobsResponseUnmarshaller.Instance; return Invoke<ListJobsRequest,ListJobsResponse>(request, marshaller, unmarshaller); } /// <summary> /// This operation returns the jobs associated with the requester. AWS Import/Export lists /// the jobs in reverse chronological order based on the date of creation. For example /// if Job Test1 was created 2009Dec30 and Test2 was created 2010Feb05, the ListJobs operation /// would return Test2 followed by Test1. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListJobs service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidParameterException"> /// One or more parameters had an invalid value. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> public Task<ListJobsResponse> ListJobsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return ListJobsAsync(new ListJobsRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the ListJobs operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListJobs operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListJobsResponse> ListJobsAsync(ListJobsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListJobsRequestMarshaller(); var unmarshaller = ListJobsResponseUnmarshaller.Instance; return InvokeAsync<ListJobsRequest,ListJobsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdateJob /// <summary> /// You use this operation to change the parameters specified in the original manifest /// file by supplying a new manifest file. The manifest file attached to this request /// replaces the original manifest file. You can only use the operation after a CreateJob /// request but before the data transfer starts and you can only use it on jobs you own. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateJob service method.</param> /// /// <returns>The response from the UpdateJob service method, as returned by ImportExport.</returns> /// <exception cref="Amazon.ImportExport.Model.BucketPermissionException"> /// The account specified does not have the appropriate bucket permissions. /// </exception> /// <exception cref="Amazon.ImportExport.Model.CanceledJobIdException"> /// The specified job ID has been canceled and is no longer valid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.ExpiredJobIdException"> /// Indicates that the specified job has expired out of the system. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAccessKeyIdException"> /// The AWS Access Key ID specified in the request did not match the manifest's accessKeyId /// value. The manifest and the request authentication must use the same AWS Access Key /// ID. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidAddressException"> /// The address specified in the manifest is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidCustomsException"> /// One or more customs parameters was invalid. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidFileSystemException"> /// File system specified in export manifest is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidJobIdException"> /// The JOBID was missing, not found, or not associated with the AWS account. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidManifestFieldException"> /// One or more manifest fields was invalid. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidParameterException"> /// One or more parameters had an invalid value. /// </exception> /// <exception cref="Amazon.ImportExport.Model.InvalidVersionException"> /// The client tool version is invalid. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MalformedManifestException"> /// Your manifest is not well-formed. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingCustomsException"> /// One or more required customs parameters was missing from the manifest. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingManifestFieldException"> /// One or more required fields were missing from the manifest file. Please correct and /// resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MissingParameterException"> /// One or more required parameters was missing from the request. /// </exception> /// <exception cref="Amazon.ImportExport.Model.MultipleRegionsException"> /// Your manifest file contained buckets from multiple regions. A job is restricted to /// buckets from one region. Please correct and resubmit. /// </exception> /// <exception cref="Amazon.ImportExport.Model.NoSuchBucketException"> /// The specified bucket does not exist. Create the specified bucket or change the manifest's /// bucket, exportBucket, or logBucket field to a bucket that the account, as specified /// by the manifest's Access Key ID, has write permissions to. /// </exception> /// <exception cref="Amazon.ImportExport.Model.UnableToUpdateJobIdException"> /// AWS Import/Export cannot update the job /// </exception> public UpdateJobResponse UpdateJob(UpdateJobRequest request) { var marshaller = new UpdateJobRequestMarshaller(); var unmarshaller = UpdateJobResponseUnmarshaller.Instance; return Invoke<UpdateJobRequest,UpdateJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdateJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdateJobResponse> UpdateJobAsync(UpdateJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdateJobRequestMarshaller(); var unmarshaller = UpdateJobResponseUnmarshaller.Instance; return InvokeAsync<UpdateJobRequest,UpdateJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #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.Text; using System.IO; using System.Xml; using Microsoft.Test.ModuleCore; using XmlCoreTest.Common; public enum NodeFlags { None = 0, EmptyElement = 1, HasValue = 2, SingleQuote = 4, DefaultAttribute = 8, UnparsedEntities = 16, IsWhitespace = 32, DocumentRoot = 64, AttributeTextNode = 128, MixedContent = 256, Indent = 512 } abstract public class CXmlBase { protected XmlNodeType pnType; protected string pstrName; protected string pstrLocalName; protected string pstrPrefix; protected string pstrNamespace; internal int pnDepth; internal NodeFlags peFlags = NodeFlags.None; internal CXmlBase prNextNode = null; internal CXmlBase prParentNode = null; internal CXmlBase prFirstChildNode = null; internal CXmlBase prLastChildNode = null; internal int pnChildNodes = 0; // // Constructors // public CXmlBase(string strPrefix, string strName, string strLocalName, XmlNodeType NodeType, string strNamespace) { pstrPrefix = strPrefix; pstrName = strName; pstrLocalName = strLocalName; pnType = NodeType; pstrNamespace = strNamespace; } public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType, string strNamespace) : this(strPrefix, strName, strName, NodeType, strNamespace) { } public CXmlBase(string strPrefix, string strName, XmlNodeType NodeType) : this(strPrefix, strName, strName, NodeType, "") { } public CXmlBase(string strName, XmlNodeType NodeType) : this("", strName, strName, NodeType, "") { } // // Virtual Methods and Properties // abstract public void Write(XmlWriter rXmlWriter); abstract public string Xml { get; } abstract public void WriteXml(TextWriter rTW); abstract public string Value { get; } // // Public Methods and Properties // public string Name { get { return pstrName; } } public string LocalName { get { return pstrLocalName; } } public string Prefix { get { return pstrPrefix; } } public string Namespace { get { return pstrNamespace; } } public int Depth { get { return pnDepth; } } public XmlNodeType NodeType { get { return pnType; } } public NodeFlags Flags { get { return peFlags; } } public int ChildNodeCount { get { return pnChildNodes; } } public void InsertNode(CXmlBase rNode) { if (prFirstChildNode == null) { prFirstChildNode = prLastChildNode = rNode; } else { prLastChildNode.prNextNode = rNode; prLastChildNode = rNode; } if ((this.peFlags & NodeFlags.IsWhitespace) == 0) pnChildNodes++; rNode.prParentNode = this; } // // Internal Methods and Properties // internal CXmlBase _Child(int n) { int i; int j; CXmlBase rChild = prFirstChildNode; for (i = 0, j = 0; rChild != null; i++, rChild = rChild.prNextNode) { if ((rChild.peFlags & NodeFlags.IsWhitespace) == 0) { if (j++ == n) break; } } return rChild; } internal CXmlBase _Child(string str) { CXmlBase rChild; for (rChild = prFirstChildNode; rChild != null; rChild = rChild.prNextNode) if (rChild.Name == str) break; return rChild; } } public class CXmlAttribute : CXmlBase { // // Constructor // public CXmlAttribute(XmlReader rXmlReader) : base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI) { if (rXmlReader.IsDefault) peFlags |= NodeFlags.DefaultAttribute; } // // Public Methods and Properties (Override) // override public void Write(XmlWriter rXmlWriter) { CXmlBase rNode; if ((this.peFlags & NodeFlags.DefaultAttribute) == 0) { rXmlWriter.WriteStartAttribute(this.Prefix, this.LocalName, this.Namespace); for (rNode = this.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) { rNode.Write(rXmlWriter); } rXmlWriter.WriteEndAttribute(); } } override public string Xml { get { CXmlCache._rBufferWriter.Dispose(); WriteXml(CXmlCache._rBufferWriter); return CXmlCache._rBufferWriter.ToString(); } } override public void WriteXml(TextWriter rTW) { if ((this.peFlags & NodeFlags.DefaultAttribute) == 0) { CXmlBase rNode; rTW.Write(' ' + this.Name + '=' + this.Quote); for (rNode = this.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) { rNode.WriteXml(rTW); } rTW.Write(this.Quote); } } // // Public Methods and Properties // override public string Value { get { CXmlNode rNode; string strValue = string.Empty; for (rNode = (CXmlNode)this.prFirstChildNode; rNode != null; rNode = rNode.NextNode) strValue += rNode.Value; return strValue; } } public CXmlAttribute NextAttribute { get { return (CXmlAttribute)this.prNextNode; } } public char Quote { get { return ((base.peFlags & NodeFlags.SingleQuote) != 0 ? '\'' : '"'); } set { if (value == '\'') base.peFlags |= NodeFlags.SingleQuote; else base.peFlags &= ~NodeFlags.SingleQuote; } } public CXmlNode FirstChild { get { return (CXmlNode)base.prFirstChildNode; } } public CXmlNode Child(int n) { return (CXmlNode)base._Child(n); } public CXmlNode Child(string str) { return (CXmlNode)base._Child(str); } } public class CXmlNode : CXmlBase { internal string _strValue = null; private CXmlAttribute _rFirstAttribute = null; private CXmlAttribute _rLastAttribute = null; private int _nAttributeCount = 0; // // Constructors // public CXmlNode(string strPrefix, string strName, XmlNodeType NodeType) : base(strPrefix, strName, NodeType) { } public CXmlNode(XmlReader rXmlReader) : base(rXmlReader.Prefix, rXmlReader.Name, rXmlReader.LocalName, rXmlReader.NodeType, rXmlReader.NamespaceURI) { peFlags |= CXmlCache._eDefaultFlags; if (NodeType == XmlNodeType.Whitespace || NodeType == XmlNodeType.SignificantWhitespace) { peFlags |= NodeFlags.IsWhitespace; } if (rXmlReader.IsEmptyElement) { peFlags |= NodeFlags.EmptyElement; } if (rXmlReader.HasValue) { peFlags |= NodeFlags.HasValue; _strValue = rXmlReader.Value; } } // // Public Methods and Properties (Override) // override public void Write(XmlWriter rXmlWriter) { CXmlBase rNode; CXmlAttribute rAttribute; string DocTypePublic = null; string DocTypeSystem = null; switch (this.NodeType) { case XmlNodeType.CDATA: rXmlWriter.WriteCData(_strValue); break; case XmlNodeType.Comment: rXmlWriter.WriteComment(_strValue); break; case XmlNodeType.DocumentType: for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { if (rAttribute.Name == "PUBLIC") { DocTypePublic = rAttribute.Value; } if (rAttribute.Name == "SYSTEM") { DocTypeSystem = rAttribute.Value; } } rXmlWriter.WriteDocType(this.Name, DocTypePublic, DocTypeSystem, _strValue); break; case XmlNodeType.EntityReference: rXmlWriter.WriteEntityRef(this.Name); break; case XmlNodeType.ProcessingInstruction: rXmlWriter.WriteProcessingInstruction(this.Name, _strValue); break; case XmlNodeType.Text: if (this.Name == string.Empty) { if ((this.Flags & NodeFlags.UnparsedEntities) == 0) { rXmlWriter.WriteString(_strValue); } else { rXmlWriter.WriteRaw(_strValue.ToCharArray(), 0, _strValue.Length); } } else { if (this.pstrName[0] == '#') rXmlWriter.WriteCharEntity(_strValue[0]); else rXmlWriter.WriteEntityRef(this.Name); } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: if ((this.prParentNode.peFlags & NodeFlags.DocumentRoot) != 0) rXmlWriter.WriteRaw(_strValue.ToCharArray(), 0, _strValue.Length); else rXmlWriter.WriteString(_strValue); break; case XmlNodeType.Element: rXmlWriter.WriteStartElement(this.Prefix, this.LocalName, null); for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { rAttribute.Write(rXmlWriter); } if ((this.Flags & NodeFlags.EmptyElement) == 0) rXmlWriter.WriteString(string.Empty); for (rNode = base.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) { rNode.Write(rXmlWriter); } // Should only produce empty tag if the original document used empty tag if ((this.Flags & NodeFlags.EmptyElement) == 0) rXmlWriter.WriteFullEndElement(); else rXmlWriter.WriteEndElement(); break; case XmlNodeType.XmlDeclaration: rXmlWriter.WriteRaw("<?xml " + _strValue + "?>"); break; default: throw (new Exception("Node.Write: Unhandled node type " + this.NodeType.ToString())); } } override public string Xml { get { CXmlCache._rBufferWriter.Dispose(); WriteXml(CXmlCache._rBufferWriter); return CXmlCache._rBufferWriter.ToString(); } } override public void WriteXml(TextWriter rTW) { string strXml; CXmlAttribute rAttribute; CXmlBase rNode; switch (this.pnType) { case XmlNodeType.Text: if (this.pstrName == "") { rTW.Write(_strValue); } else { if (this.pstrName.StartsWith("#")) { rTW.Write("&" + Convert.ToString(Convert.ToInt32(_strValue[0])) + ";"); } else { rTW.Write("&" + this.Name + ";"); } } break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.DocumentType: rTW.Write(_strValue); break; case XmlNodeType.Element: strXml = this.Name; rTW.Write('<' + strXml); //Put in all the Attributes for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { rAttribute.WriteXml(rTW); } //If there is children, put those in, otherwise close the tag. if ((base.peFlags & NodeFlags.EmptyElement) == 0) { rTW.Write('>'); for (rNode = base.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) { rNode.WriteXml(rTW); } rTW.Write("</" + strXml + ">"); } else { rTW.Write(" />"); } break; case XmlNodeType.EntityReference: rTW.Write("&" + this.pstrName + ";"); break; case XmlNodeType.Notation: rTW.Write("<!NOTATION " + _strValue + ">"); break; case XmlNodeType.CDATA: rTW.Write("<![CDATA[" + _strValue + "]]>"); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: rTW.Write("<?" + this.pstrName + " " + _strValue + "?>"); break; case XmlNodeType.Comment: rTW.Write("<!--" + _strValue + "-->"); break; default: throw (new Exception("Unhandled NodeType " + this.pnType.ToString())); } } // // Public Methods and Properties // public string NodeValue { get { return _strValue; } } override public string Value { get { string strValue = ""; CXmlNode rChild; if ((this.peFlags & NodeFlags.HasValue) != 0) { char chEnt; int nIndexAmp = 0; int nIndexSem = 0; if ((this.peFlags & NodeFlags.UnparsedEntities) == 0) return _strValue; strValue = _strValue; while ((nIndexAmp = strValue.IndexOf('&', nIndexAmp)) != -1) { nIndexSem = strValue.IndexOf(';', nIndexAmp); chEnt = ResolveCharEntity(strValue.Substring(nIndexAmp + 1, nIndexSem - nIndexAmp - 1)); if (chEnt != char.MinValue) { strValue = strValue.Substring(0, nIndexAmp) + chEnt + strValue.Substring(nIndexSem + 1); nIndexAmp++; } else nIndexAmp = nIndexSem; } return strValue; } for (rChild = (CXmlNode)this.prFirstChildNode; rChild != null; rChild = (CXmlNode)rChild.prNextNode) { strValue = strValue + rChild.Value; } return strValue; } } public CXmlNode NextNode { get { CXmlBase rNode = this.prNextNode; while (rNode != null && (rNode.Flags & NodeFlags.IsWhitespace) != 0) rNode = rNode.prNextNode; return (CXmlNode)rNode; } } public CXmlNode FirstChild { get { CXmlBase rNode = this.prFirstChildNode; while (rNode != null && (rNode.Flags & NodeFlags.IsWhitespace) != 0) rNode = rNode.prNextNode; return (CXmlNode)rNode; } } public CXmlNode Child(int n) { int i; CXmlNode rChild; i = 0; for (rChild = FirstChild; rChild != null; rChild = rChild.NextNode) if (i++ == n) break; return rChild; } public CXmlNode Child(string str) { return (CXmlNode)base._Child(str); } public int Type { get { return Convert.ToInt32(base.pnType); } } public CXmlAttribute FirstAttribute { get { return _rFirstAttribute; } } public int AttributeCount { get { return _nAttributeCount; } } public CXmlAttribute Attribute(int n) { int i; CXmlAttribute rAttribute; i = 0; for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) if (i++ == n) break; return rAttribute; } public CXmlAttribute Attribute(string str) { CXmlAttribute rAttribute; for (rAttribute = _rFirstAttribute; rAttribute != null; rAttribute = rAttribute.NextAttribute) { if (rAttribute.Name == str) break; } return rAttribute; } public void AddAttribute(CXmlAttribute rAttribute) { if (_rFirstAttribute == null) { _rFirstAttribute = rAttribute; } else { _rLastAttribute.prNextNode = rAttribute; } _rLastAttribute = rAttribute; _nAttributeCount++; } private char ResolveCharEntity(string strName) { if (strName[0] == '#') if (strName[1] == 'x') return Convert.ToChar(Convert.ToInt32(strName.Substring(2), 16)); else return Convert.ToChar(Convert.ToInt32(strName.Substring(1))); if (strName == "lt") return '<'; if (strName == "gt") return '>'; if (strName == "amp") return '&'; if (strName == "apos") return '\''; if (strName == "quot") return '"'; return char.MinValue; } } public class CXmlCache { //CXmlCache Properties private bool _fTrace = false; private bool _fThrow = true; private bool _fReadNode = true; private int _hr = 0; private Encoding _eEncoding = System.Text.Encoding.UTF8; private string _strParseError = ""; //XmlReader Properties private bool _fNamespaces = true; private bool _fValidationCallback = false; private bool _fExpandAttributeValues = false; //Internal stuff protected XmlReader prXmlReader = null; protected CXmlNode prDocumentRootNode; protected CXmlNode prRootNode = null; internal static NodeFlags _eDefaultFlags = NodeFlags.None; internal static BufferWriter _rBufferWriter = new BufferWriter(); // // Constructor // public CXmlCache() { } // // Public Methods and Properties // public virtual bool Load(XmlReader rXmlReader) { //Hook up your reader as my reader prXmlReader = rXmlReader; //Process the Document try { prDocumentRootNode = new CXmlNode("", "", XmlNodeType.Element); prDocumentRootNode.peFlags = NodeFlags.DocumentRoot | NodeFlags.Indent; Process(prDocumentRootNode); for (prRootNode = prDocumentRootNode.FirstChild; prRootNode != null && prRootNode.NodeType != XmlNodeType.Element; prRootNode = prRootNode.NextNode) ; } catch (Exception e) { //Unhook your reader prXmlReader = null; _strParseError = e.ToString(); if (_fThrow) { throw (e); } if (_hr == 0) _hr = -1; return false; } //Unhook your reader prXmlReader = null; return true; } public bool Load(string strFileName) { XmlReader rXmlTextReader; bool fRet; rXmlTextReader = XmlReader.Create(FilePathUtil.getStream(strFileName)); fRet = Load(rXmlTextReader); return fRet; } public void Save(string strName) { Save(strName, false, _eEncoding); } public void Save(string strName, bool fOverWrite) { Save(strName, fOverWrite, _eEncoding); } public void Save(string strName, bool fOverWrite, System.Text.Encoding Encoding) { CXmlBase rNode; XmlWriter rXmlTextWriter = null; try { rXmlTextWriter = XmlWriter.Create(FilePathUtil.getStream(strName)); for (rNode = prDocumentRootNode.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) { rNode.Write(rXmlTextWriter); } rXmlTextWriter.Dispose(); } catch (Exception e) { DebugTrace(e.ToString()); if (rXmlTextWriter != null) rXmlTextWriter.Dispose(); throw (e); } } virtual public string Xml { get { _rBufferWriter.Dispose(); WriteXml(_rBufferWriter); return _rBufferWriter.ToString(); } } public void WriteXml(TextWriter rTW) { CXmlBase rNode; //Spit out the document for (rNode = prDocumentRootNode.prFirstChildNode; rNode != null; rNode = rNode.prNextNode) rNode.WriteXml(rTW); } public CXmlNode RootNode { get { return prRootNode; } } public string ParseError { get { return _strParseError; } } public int ParseErrorCode { get { return _hr; } } // // XmlReader Properties // public bool Namespaces { set { _fNamespaces = value; } get { return _fNamespaces; } } public bool UseValidationCallback { set { _fValidationCallback = value; } get { return _fValidationCallback; } } public bool ExpandAttributeValues { set { _fExpandAttributeValues = value; } get { return _fExpandAttributeValues; } } // // Internal Properties // public bool Throw { get { return _fThrow; } set { _fThrow = value; } } public bool Trace { set { _fTrace = value; } get { return _fTrace; } } // //Private Methods // private void DebugTrace(string str) { DebugTrace(str, 0); } private void DebugTrace(string str, int nDepth) { if (_fTrace) { int i; for (i = 0; i < nDepth; i++) TestLog.Write(" "); TestLog.WriteLine(str); } } private void DebugTrace(XmlReader rXmlReader) { if (_fTrace) { string str; str = rXmlReader.NodeType.ToString() + ", Depth=" + rXmlReader.Depth + " Name="; if (rXmlReader.Prefix != "") { str += rXmlReader.Prefix + ":"; } str += rXmlReader.LocalName; if (rXmlReader.HasValue) str += " Value=" + rXmlReader.Value; DebugTrace(str, rXmlReader.Depth); } } protected void Process(CXmlBase rParentNode) { CXmlNode rNewNode; while (true) { //We want to pop if Read() returns false, aka EOF if (_fReadNode) { if (!prXmlReader.Read()) { DebugTrace("Read() == false"); return; } } else { if (!prXmlReader.ReadAttributeValue()) { DebugTrace("ReadAttributeValue() == false"); return; } } DebugTrace(prXmlReader); //We also want to pop if we get an EndElement or EndEntity if (prXmlReader.NodeType == XmlNodeType.EndElement || prXmlReader.NodeType == XmlNodeType.EndEntity) { DebugTrace("NodeType == EndElement or EndEntity"); return; } rNewNode = GetNewNode(prXmlReader); rNewNode.pnDepth = prXmlReader.Depth; // Test for MixedContent and set Indent if necessary if ((rParentNode.Flags & NodeFlags.MixedContent) != 0) { rNewNode.peFlags |= NodeFlags.MixedContent; // Indent is off for all new nodes } else { rNewNode.peFlags |= NodeFlags.Indent; // Turn on Indent for current Node } // Set all Depth 0 nodes to No Mixed Content and Indent True if (prXmlReader.Depth == 0) { rNewNode.peFlags |= NodeFlags.Indent; // Turn on Indent rNewNode.peFlags &= ~NodeFlags.MixedContent; // Turn off MixedContent } rParentNode.InsertNode(rNewNode); //Do some special stuff based on NodeType switch (prXmlReader.NodeType) { case XmlNodeType.Element: if (prXmlReader.MoveToFirstAttribute()) { do { CXmlAttribute rNewAttribute = new CXmlAttribute(prXmlReader); rNewNode.AddAttribute(rNewAttribute); if (_fExpandAttributeValues) { DebugTrace("Attribute: " + prXmlReader.Name); _fReadNode = false; Process(rNewAttribute); _fReadNode = true; } else { CXmlNode rValueNode = new CXmlNode("", "", XmlNodeType.Text); rValueNode.peFlags = _eDefaultFlags | NodeFlags.HasValue; rValueNode._strValue = prXmlReader.Value; DebugTrace(" Value=" + rValueNode.Value, prXmlReader.Depth + 1); rNewAttribute.InsertNode(rValueNode); } } while (prXmlReader.MoveToNextAttribute()); } if ((rNewNode.Flags & NodeFlags.EmptyElement) == 0) Process(rNewNode); break; case XmlNodeType.XmlDeclaration: string strValue = rNewNode.NodeValue; int nPos = strValue.IndexOf("encoding"); if (nPos != -1) { int nEnd; nPos = strValue.IndexOf("=", nPos); //Find the = sign nEnd = strValue.IndexOf("\"", nPos) + 1; //Find the next " character nPos = strValue.IndexOf("'", nPos) + 1; //Find the next ' character if (nEnd == 0 || (nPos < nEnd && nPos > 0)) //Pick the one that's closer to the = sign { nEnd = strValue.IndexOf("'", nPos); } else { nPos = nEnd; nEnd = strValue.IndexOf("\"", nPos); } string sEncodeName = strValue.Substring(nPos, nEnd - nPos); DebugTrace("XMLDecl contains encoding " + sEncodeName); if (sEncodeName.ToUpper() == "UCS-2") { sEncodeName = "unicode"; } _eEncoding = System.Text.Encoding.GetEncoding(sEncodeName); } break; case XmlNodeType.ProcessingInstruction: break; case XmlNodeType.Text: if (!_fReadNode) { rNewNode.peFlags = _eDefaultFlags | NodeFlags.AttributeTextNode; } rNewNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node rNewNode.peFlags &= ~NodeFlags.Indent; // turn off Indent for current node rParentNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: rNewNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for current node rNewNode.peFlags &= ~NodeFlags.Indent; // turn off Indent for current node rParentNode.peFlags |= NodeFlags.MixedContent; // turn on Mixed Content for Parent Node break; case XmlNodeType.Comment: case XmlNodeType.Notation: break; case XmlNodeType.DocumentType: if (prXmlReader.MoveToFirstAttribute()) { do { CXmlAttribute rNewAttribute = new CXmlAttribute(prXmlReader); rNewNode.AddAttribute(rNewAttribute); CXmlNode rValueNode = new CXmlNode(prXmlReader); rValueNode._strValue = prXmlReader.Value; rNewAttribute.InsertNode(rValueNode); } while (prXmlReader.MoveToNextAttribute()); } break; default: TestLog.WriteLine("UNHANDLED TYPE, " + prXmlReader.NodeType.ToString() + " IN Process()!"); break; } } } protected virtual CXmlNode GetNewNode(XmlReader rXmlReader) { return new CXmlNode(rXmlReader); } } public class ChecksumWriter : TextWriter { private int _nPosition = 0; private decimal _dResult = 0; private Encoding _encoding; // -------------------------------------------------------------------------------------------------- // Constructor // -------------------------------------------------------------------------------------------------- public ChecksumWriter() { _encoding = Encoding.UTF8; } // -------------------------------------------------------------------------------------------------- // Properties // -------------------------------------------------------------------------------------------------- public decimal CheckSum { get { return _dResult; } } public override Encoding Encoding { get { return _encoding; } } // -------------------------------------------------------------------------------------------------- // Public methods // -------------------------------------------------------------------------------------------------- override public void Write(string str) { int i; int m; m = str.Length; for (i = 0; i < m; i++) { Write(str[i]); } } override public void Write(char[] rgch) { int i; int m; m = rgch.Length; for (i = 0; i < m; i++) { Write(rgch[i]); } } override public void Write(char[] rgch, int iOffset, int iCount) { int i; int m; m = iOffset + iCount; for (i = iOffset; i < m; i++) { Write(rgch[i]); } } override public void Write(char ch) { _dResult += Math.Round((decimal)(ch / (_nPosition + 1.0)), 10); _nPosition++; } public new void Dispose() { _nPosition = 0; _dResult = 0; } } public class BufferWriter : TextWriter { private int _nBufferSize = 0; private int _nBufferUsed = 0; private int _nBufferGrow = 1024; private char[] _rgchBuffer = null; private Encoding _encoding; // -------------------------------------------------------------------------------------------------- // Constructor // -------------------------------------------------------------------------------------------------- public BufferWriter() { _encoding = Encoding.UTF8; } // -------------------------------------------------------------------------------------------------- // Properties // -------------------------------------------------------------------------------------------------- override public string ToString() { return new string(_rgchBuffer, 0, _nBufferUsed); } public override Encoding Encoding { get { return _encoding; } } // -------------------------------------------------------------------------------------------------- // Public methods // -------------------------------------------------------------------------------------------------- override public void Write(string str) { int i; int m; m = str.Length; for (i = 0; i < m; i++) { Write(str[i]); } } override public void Write(char[] rgch) { int i; int m; m = rgch.Length; for (i = 0; i < m; i++) { Write(rgch[i]); } } override public void Write(char[] rgch, int iOffset, int iCount) { int i; int m; m = iOffset + iCount; for (i = iOffset; i < m; i++) { Write(rgch[i]); } } override public void Write(char ch) { if (_nBufferUsed == _nBufferSize) { char[] rgchTemp = new char[_nBufferSize + _nBufferGrow]; for (_nBufferUsed = 0; _nBufferUsed < _nBufferSize; _nBufferUsed++) rgchTemp[_nBufferUsed] = _rgchBuffer[_nBufferUsed]; _rgchBuffer = rgchTemp; _nBufferSize += _nBufferGrow; if (_nBufferGrow < (1024 * 1024)) _nBufferGrow *= 2; } _rgchBuffer[_nBufferUsed++] = ch; } public new void Dispose() { //Set nBufferUsed to 0, so we start writing from the beginning of the buffer. _nBufferUsed = 0; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Newtonsoft.Json; using Orleans.Configuration; using Orleans.Persistence.DynamoDB; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans.Storage { /// <summary> /// Dynamo DB storage Provider. /// Persist Grain State in a DynamoDB table either in Json or Binary format. /// </summary> public class DynamoDBGrainStorage : IGrainStorage, ILifecycleParticipant<ISiloLifecycle> { private const int MAX_DATA_SIZE = 400 * 1024; private const string GRAIN_REFERENCE_PROPERTY_NAME = "GrainReference"; private const string STRING_STATE_PROPERTY_NAME = "StringState"; private const string BINARY_STATE_PROPERTY_NAME = "BinaryState"; private const string GRAIN_TYPE_PROPERTY_NAME = "GrainType"; private const string ETAG_PROPERTY_NAME = "ETag"; private const string CURRENT_ETAG_ALIAS = ":currentETag"; private readonly DynamoDBStorageOptions options; private readonly SerializationManager serializationManager; private readonly ILoggerFactory loggerFactory; private readonly ILogger logger; private readonly IGrainFactory grainFactory; private readonly ITypeResolver typeResolver; private readonly string name; private DynamoDBStorage storage; private JsonSerializerSettings jsonSettings; /// <summary> /// Default Constructor /// </summary> public DynamoDBGrainStorage(string name, DynamoDBStorageOptions options, SerializationManager serializationManager, IGrainFactory grainFactory, ITypeResolver typeResolver, ILoggerFactory loggerFactory) { this.name = name; this.loggerFactory = loggerFactory; var loggerName = $"{typeof(DynamoDBGrainStorage).FullName}.{name}"; this.logger = loggerFactory.CreateLogger(loggerName); this.options = options; this.serializationManager = serializationManager; this.grainFactory = grainFactory; this.typeResolver = typeResolver; } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe(OptionFormattingUtilities.Name<DynamoDBGrainStorage>(this.name), this.options.InitStage, Init, Close); } /// <summary> Initialization function for this storage provider. </summary> public async Task Init(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); try { var initMsg = string.Format("Init: Name={0} ServiceId={1} Table={2} DeleteStateOnClear={3}", this.name, this.options.ServiceId, this.options.TableName, this.options.DeleteStateOnClear); this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings( OrleansJsonSerializer.GetDefaultSerializerSettings(this.typeResolver, this.grainFactory), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling); this.logger.LogInformation((int)ErrorCode.StorageProviderBase, $"AWS DynamoDB Grain Storage {this.name} is initializing: {initMsg}"); this.storage = new DynamoDBStorage(this.loggerFactory, this.options.Service, this.options.AccessKey, this.options.SecretKey, this.options.ReadCapacityUnits, this.options.WriteCapacityUnits); await storage.InitializeTable(this.options.TableName, new List<KeySchemaElement> { new KeySchemaElement { AttributeName = GRAIN_REFERENCE_PROPERTY_NAME, KeyType = KeyType.HASH }, new KeySchemaElement { AttributeName = GRAIN_TYPE_PROPERTY_NAME, KeyType = KeyType.RANGE } }, new List<AttributeDefinition> { new AttributeDefinition { AttributeName = GRAIN_REFERENCE_PROPERTY_NAME, AttributeType = ScalarAttributeType.S }, new AttributeDefinition { AttributeName = GRAIN_TYPE_PROPERTY_NAME, AttributeType = ScalarAttributeType.S } }); stopWatch.Stop(); this.logger.LogInformation((int)ErrorCode.StorageProviderBase, $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds."); } catch (Exception exc) { stopWatch.Stop(); this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", exc); throw; } } /// <summary> Shutdown this storage provider. </summary> public Task Close(CancellationToken ct) => Task.CompletedTask; /// <summary> Read state data function for this storage provider. </summary> /// <see cref="IGrainStorage.ReadStateAsync"/> public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (this.storage == null) throw new ArgumentException("GrainState-Table property not initialized"); string partitionKey = GetKeyString(grainReference); if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace(ErrorCode.StorageProviderBase, "Reading: GrainType={0} Pk={1} Grainid={2} from Table={3}", grainType, partitionKey, grainReference, this.options.TableName); string rowKey = AWSUtils.ValidateDynamoDBRowKey(grainType); var record = await this.storage.ReadSingleEntryAsync(this.options.TableName, new Dictionary<string, AttributeValue> { { GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue(partitionKey) }, { GRAIN_TYPE_PROPERTY_NAME, new AttributeValue(rowKey) } }, (fields) => { return new GrainStateRecord { GrainType = fields[GRAIN_TYPE_PROPERTY_NAME].S, GrainReference = fields[GRAIN_REFERENCE_PROPERTY_NAME].S, ETag = int.Parse(fields[ETAG_PROPERTY_NAME].N), BinaryState = fields.ContainsKey(BINARY_STATE_PROPERTY_NAME) ? fields[BINARY_STATE_PROPERTY_NAME].B.ToArray() : null, StringState = fields.ContainsKey(STRING_STATE_PROPERTY_NAME) ? fields[STRING_STATE_PROPERTY_NAME].S : string.Empty }; }).ConfigureAwait(false); if (record != null) { var loadedState = ConvertFromStorageFormat(record); grainState.State = loadedState ?? Activator.CreateInstance(grainState.Type); grainState.ETag = record.ETag.ToString(); } // Else leave grainState in previous default condition } /// <summary> Write state data function for this storage provider. </summary> /// <see cref="IGrainStorage.WriteStateAsync"/> public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (this.storage == null) throw new ArgumentException("GrainState-Table property not initialized"); string partitionKey = GetKeyString(grainReference); string rowKey = AWSUtils.ValidateDynamoDBRowKey(grainType); var record = new GrainStateRecord { GrainReference = partitionKey, GrainType = rowKey }; try { ConvertToStorageFormat(grainState.State, record); await WriteStateInternal(grainState, record); } catch (ConditionalCheckFailedException exc) { throw new InconsistentStateException("Invalid grain state", exc); } catch (Exception exc) { this.logger.Error(ErrorCode.StorageProviderBase, string.Format("Error Writing: GrainType={0} Grainid={1} ETag={2} to Table={3} Exception={4}", grainType, grainReference, grainState.ETag, this.options.TableName, exc.Message), exc); throw; } } private async Task WriteStateInternal(IGrainState grainState, GrainStateRecord record, bool clear = false) { var fields = new Dictionary<string, AttributeValue>(); if (record.BinaryState != null && record.BinaryState.Length > 0) { fields.Add(BINARY_STATE_PROPERTY_NAME, new AttributeValue { B = new MemoryStream(record.BinaryState) }); } else if (!string.IsNullOrWhiteSpace(record.StringState)) { fields.Add(STRING_STATE_PROPERTY_NAME, new AttributeValue(record.StringState)); } int newEtag = 0; if (clear) { fields.Add(GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue(record.GrainReference)); fields.Add(GRAIN_TYPE_PROPERTY_NAME, new AttributeValue(record.GrainType)); int currentEtag = 0; int.TryParse(grainState.ETag, out currentEtag); newEtag = currentEtag; fields.Add(ETAG_PROPERTY_NAME, new AttributeValue { N = newEtag++.ToString() }); await this.storage.PutEntryAsync(this.options.TableName, fields).ConfigureAwait(false); } else if (string.IsNullOrWhiteSpace(grainState.ETag)) { fields.Add(GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue(record.GrainReference)); fields.Add(GRAIN_TYPE_PROPERTY_NAME, new AttributeValue(record.GrainType)); fields.Add(ETAG_PROPERTY_NAME, new AttributeValue { N = "0" }); var expression = $"attribute_not_exists({GRAIN_REFERENCE_PROPERTY_NAME}) AND attribute_not_exists({GRAIN_TYPE_PROPERTY_NAME})"; await this.storage.PutEntryAsync(this.options.TableName, fields, expression).ConfigureAwait(false); } else { var keys = new Dictionary<string, AttributeValue>(); keys.Add(GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue(record.GrainReference)); keys.Add(GRAIN_TYPE_PROPERTY_NAME, new AttributeValue(record.GrainType)); int currentEtag = 0; int.TryParse(grainState.ETag, out currentEtag); newEtag = currentEtag; newEtag++; fields.Add(ETAG_PROPERTY_NAME, new AttributeValue { N = newEtag.ToString() }); var conditionalValues = new Dictionary<string, AttributeValue> { { CURRENT_ETAG_ALIAS, new AttributeValue { N = currentEtag.ToString() } } }; var expression = $"{ETAG_PROPERTY_NAME} = {CURRENT_ETAG_ALIAS}"; await this.storage.UpsertEntryAsync(this.options.TableName, keys, fields, expression, conditionalValues).ConfigureAwait(false); } grainState.ETag = newEtag.ToString(); } /// <summary> Clear / Delete state data function for this storage provider. </summary> /// <remarks> /// If the <c>DeleteStateOnClear</c> is set to <c>true</c> then the table row /// for this grain will be deleted / removed, otherwise the table row will be /// cleared by overwriting with default / null values. /// </remarks> /// <see cref="IGrainStorage.ClearStateAsync"/> public async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (this.storage == null) throw new ArgumentException("GrainState-Table property not initialized"); string partitionKey = GetKeyString(grainReference); if (this.logger.IsEnabled(LogLevel.Trace)) { this.logger.Trace(ErrorCode.StorageProviderBase, "Clearing: GrainType={0} Pk={1} Grainid={2} ETag={3} DeleteStateOnClear={4} from Table={5}", grainType, partitionKey, grainReference, grainState.ETag, this.options.DeleteStateOnClear, this.options.TableName); } string rowKey = AWSUtils.ValidateDynamoDBRowKey(grainType); var record = new GrainStateRecord { GrainReference = partitionKey, ETag = string.IsNullOrWhiteSpace(grainState.ETag) ? 0 : int.Parse(grainState.ETag), GrainType = rowKey }; var operation = "Clearing"; try { if (this.options.DeleteStateOnClear) { operation = "Deleting"; var keys = new Dictionary<string, AttributeValue>(); keys.Add(GRAIN_REFERENCE_PROPERTY_NAME, new AttributeValue(record.GrainReference)); keys.Add(GRAIN_TYPE_PROPERTY_NAME, new AttributeValue(record.GrainType)); await this.storage.DeleteEntryAsync(this.options.TableName, keys).ConfigureAwait(false); grainState.ETag = string.Empty; } else { await WriteStateInternal(grainState, record, true); } } catch (Exception exc) { this.logger.Error(ErrorCode.StorageProviderBase, string.Format("Error {0}: GrainType={1} Grainid={2} ETag={3} from Table={4} Exception={5}", operation, grainType, grainReference, grainState.ETag, this.options.TableName, exc.Message), exc); throw; } } internal class GrainStateRecord { public string GrainReference { get; set; } = ""; public string GrainType { get; set; } = ""; public byte[] BinaryState { get; set; } public string StringState { get; set; } public int ETag { get; set; } } private string GetKeyString(GrainReference grainReference) { var key = string.Format("{0}_{1}", this.options.ServiceId, grainReference.ToKeyString()); return AWSUtils.ValidateDynamoDBPartitionKey(key); } internal object ConvertFromStorageFormat(GrainStateRecord entity) { var binaryData = entity.BinaryState; var stringData = entity.StringState; object dataValue = null; try { if (binaryData?.Length > 0) { // Rehydrate dataValue = this.serializationManager.DeserializeFromByteArray<object>(binaryData); } else if (!string.IsNullOrEmpty(stringData)) { dataValue = JsonConvert.DeserializeObject<object>(stringData, this.jsonSettings); } // Else, no data found } catch (Exception exc) { var sb = new StringBuilder(); if (binaryData?.Length > 0) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.Data={0}", binaryData); } else if (!string.IsNullOrEmpty(stringData)) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.StringData={0}", stringData); } if (dataValue != null) { sb.AppendFormat("Data Value={0} Type={1}", dataValue, dataValue.GetType()); } this.logger.Error(0, sb.ToString(), exc); throw new AggregateException(sb.ToString(), exc); } return dataValue; } internal void ConvertToStorageFormat(object grainState, GrainStateRecord entity) { int dataSize; if (this.options.UseJson) { // http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm entity.StringState = JsonConvert.SerializeObject(grainState, this.jsonSettings); dataSize = STRING_STATE_PROPERTY_NAME.Length + entity.StringState.Length; if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace("Writing JSON data size = {0} for grain id = Partition={1} / Row={2}", dataSize, entity.GrainReference, entity.GrainType); } else { // Convert to binary format entity.BinaryState = this.serializationManager.SerializeToByteArray(grainState); dataSize = BINARY_STATE_PROPERTY_NAME.Length + entity.BinaryState.Length; if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace("Writing binary data size = {0} for grain id = Partition={1} / Row={2}", dataSize, entity.GrainReference, entity.GrainType); } var pkSize = GRAIN_REFERENCE_PROPERTY_NAME.Length + entity.GrainReference.Length; var rkSize = GRAIN_TYPE_PROPERTY_NAME.Length + entity.GrainType.Length; var versionSize = ETAG_PROPERTY_NAME.Length + entity.ETag.ToString().Length; if ((pkSize + rkSize + versionSize + dataSize) > MAX_DATA_SIZE) { var msg = string.Format("Data too large to write to DynamoDB table. Size={0} MaxSize={1}", dataSize, MAX_DATA_SIZE); throw new ArgumentOutOfRangeException("GrainState.Size", msg); } } } public static class DynamoDBGrainStorageFactory { public static IGrainStorage Create(IServiceProvider services, string name) { var optionsMonitor = services.GetRequiredService<IOptionsMonitor<DynamoDBStorageOptions>>(); return ActivatorUtilities.CreateInstance<DynamoDBGrainStorage>(services, optionsMonitor.Get(name), name); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Samples.Chirper.GrainInterfaces; namespace Orleans.Samples.Chirper.Network.Loader { /// <summary> /// Read a GraphML data file for the Chirper network and create appropriate Orleans grains to represent that data. /// </summary> public class ChirperNetworkLoader { private const int ProgressInterval = 1000; private const int DefaultPipelineSize = 20; public int PipelineSize { get; set; } public FileInfo FileToLoad { get; set; } public Dictionary<long, IChirperAccount> Users { get; private set; } private int numUsers; private int numRelationships; private int numErrors; private int duplicateNodes = 0; private AsyncPipeline pipeline; private NetworkDataReader loader; private List<Task> promises; private readonly Stopwatch runtimeStopwatch = new Stopwatch(); private readonly Stopwatch edgeStopwatch = new Stopwatch(); private readonly Stopwatch loadStopwatch = new Stopwatch(); public ChirperNetworkLoader(AsyncPipeline pipeline = null) { this.pipeline = pipeline; this.Users = new Dictionary<long, IChirperAccount>(); this.PipelineSize = (pipeline == null) ? DefaultPipelineSize : pipeline.Capacity; if (!GrainClient.IsInitialized) { var config = ClientConfiguration.LocalhostSilo(); GrainClient.Initialize(config); } runtimeStopwatch.Start(); } public async Task<int> Run() { LogMessage("********************************************************"); LogMessage("{0}\t{1:G}", "Network Load Starting at:", DateTime.Now); LoadData(); LogMessage("Pipeline={0}", this.PipelineSize); if (pipeline == null) this.pipeline = new AsyncPipeline(this.PipelineSize); try { loadStopwatch.Start(); LogMessage("Creating {0} user nodes...", loader.Nodes.Count); List<Task> work = CreateUserNodes(); LogMessage("Waiting for {0} promises to complete.", work.Count); await Task.WhenAll(work); LogMessage("Finished creating {0} users in {1}", numUsers, runtimeStopwatch.Elapsed); LogMessage("Creating {0} user relationship links...", loader.Edges.Count); edgeStopwatch.Start(); LogMessage("Processing user relationship links group #1"); work = CreateRelationshipEdges(true); LogMessage("Waiting for {0} promises to complete.", work.Count); await Task.WhenAll(work); LogMessage("Processing user relationship links group #2"); work = CreateRelationshipEdges(false); LogMessage("Waiting for {0} promises to complete.", work.Count); await Task.WhenAll(work); edgeStopwatch.Stop(); LogMessage("Finished creating {0} user relationship links in {1}", numRelationships, runtimeStopwatch.Elapsed); } catch(Exception exc) { ReportError("Error creating Chirper data network", exc); throw exc.GetBaseException(); } loadStopwatch.Stop(); runtimeStopwatch.Stop(); LogMessage(string.Empty); LogMessage("Loading Completed:"); LogMessage("\t{0} users ({1} duplicates, {2} new)", this.numUsers, this.duplicateNodes, this.numUsers - this.duplicateNodes); LogMessage("\t{0} relationship links", this.numRelationships); LogMessage("\t{0} errors", this.numErrors); LogMessage(string.Empty); LogMessage("\tNode Processing Time:\t{0}", loadStopwatch.Elapsed - edgeStopwatch.Elapsed); LogMessage("\tEdge Processing Time:\t{0}", edgeStopwatch.Elapsed); LogMessage("\tTotal Load Time:\t{0}", loadStopwatch.Elapsed); LogMessage(string.Empty); LogMessage("Execution Time:\t\t{0}", runtimeStopwatch.Elapsed); LogMessage("Network Load Finished at:\t{0:G}", DateTime.Now); LogMessage(string.Empty); return 0; } public void LoadData() { if (FileToLoad == null) throw new ArgumentNullException("FileToLoad", "No load file specified"); if (!FileToLoad.Exists) throw new FileNotFoundException("Cannot find file to load: " + this.FileToLoad.FullName); LogMessage("Loading GraphML file:\t" + FileToLoad.FullName); loader = new NetworkDataReader(); loader.ProgressInterval = ProgressInterval; loader.LoadData(FileToLoad); } public void WaitForCompletion() { Console.WriteLine("---Press any key to exit---"); Console.ReadKey(); LogMessage("Loading Completed: {0} users, {1} relationship links, {2} errors", this.numUsers, this.numRelationships, this.numErrors); } public bool ParseArguments(string[] args) { bool ok = true; int argPos = 1; for (int i = 0; i < args.Length; i++) { string a = args[i]; if (a.StartsWith("-") || a.StartsWith("/")) { a = a.Substring(1).ToLowerInvariant(); switch (a) { case "pipeline": this.PipelineSize = Int32.Parse(args[++i]); break; case "?": case "help": default: ok = false; break; } } // unqualified arguments below else if (argPos == 1) { this.FileToLoad = new FileInfo(a); argPos++; } else { // Too many command line arguments ReportError("Too many command line arguments supplied: " + a); return false; } } return ok; } public void PrintUsage() { using (StringWriter usageStr = new StringWriter()) { usageStr.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + ".exe" + " [/pipeline {n}] {file}"); usageStr.WriteLine("Where:"); usageStr.WriteLine(" {file} = GraphML file to load"); usageStr.WriteLine(" /pipeline {n} = Request pipeline size [default " + DefaultPipelineSize + "]"); Console.WriteLine(usageStr.ToString()); } } public List<Task> CreateUserNodes() { TimeSpan intervalStart = runtimeStopwatch.Elapsed; promises = loader.ProcessNodes( AddChirperUser, i => { // Show progress interval breakdown TimeSpan currentRuntime = runtimeStopwatch.Elapsed; LogMessage("Users Created: {0,10} Time: {1} Cumulative: {2}", i, currentRuntime - intervalStart, currentRuntime); // Show progress intervalStart = runtimeStopwatch.Elapsed; // Don't include log writing in the interval. }, pipeline); return promises; } public List<Task> CreateRelationshipEdges(bool forward) { TimeSpan intervalStart = runtimeStopwatch.Elapsed; promises = loader.ProcessEdges((fromUserId, toUserId) => { // Segment updates into disjoint update groups, based on source / target node id bool skip = forward ? fromUserId > toUserId : fromUserId < toUserId; if (skip) { return null; // skip this edge for this time round } IChirperAccount fromUser = this.Users[fromUserId]; return AddChirperFollower(fromUser, fromUserId, toUserId); }, i => { // Show progress interval breakdown TimeSpan currentRuntime = runtimeStopwatch.Elapsed; LogMessage("Links created: {0,10} Time: {1} Cumulative: {2}", i, currentRuntime - intervalStart, currentRuntime); intervalStart = runtimeStopwatch.Elapsed; // Don't include log writing in the interval. }, pipeline); return promises; } public string DumpStatus() { int completedTasks = promises.Count(t => t.IsCompleted); int faultedTasks = promises.Count(t => t.IsFaulted); int cancelledTasks = promises.Count(t => t.IsCanceled); int totalTasks = promises.Count; int pipelineCount = pipeline.Count; string statusDump = string.Format( "Promises: Completed={0} Faulted={1} Cancelled={2} Total={3} Unfinished={4} Pipeline={5}", completedTasks, faultedTasks, cancelledTasks, totalTasks, totalTasks - completedTasks - faultedTasks - cancelledTasks, pipelineCount); Console.WriteLine(statusDump); return statusDump; } private async Task AddChirperUser(ChirperUserInfo userData) { // Create Chirper account grain for this user long userId = userData.UserId; string userAlias = userData.UserAlias; IChirperAccount grain = GrainClient.GrainFactory.GetGrain<IChirperAccount>(userId); this.Users[userId] = grain; try { // Force creation of the grain by sending it a first message to set user alias ChirperUserInfo userInfo = ChirperUserInfo.GetUserInfo(userId, userAlias); await grain.SetUserDetails(userInfo); Interlocked.Increment(ref numUsers); } catch (Exception exc) { ReportError("Error creating user id " + userId, exc); throw exc.GetBaseException(); } } private async Task AddChirperFollower(IChirperAccount fromUser, long fromUserId, long toUserId) { // Create subscriptions between two Chirper users try { await fromUser.FollowUserId(toUserId); Interlocked.Increment(ref numRelationships); } catch (Exception exc) { ReportError(string.Format("Error adding follower relationship from user id {0} to user id {1}", fromUserId, toUserId), exc); throw exc.GetBaseException(); } } #region Status message capture / logging internal void LogMessage(string message, params object[] args) { if (args.Length > 0) { message = String.Format(message, args); } message = $"[{DateTime.UtcNow:s}] {message}"; Console.WriteLine(message); } internal void ReportError(string msg, Exception exc) { msg = "*****\t" + msg + "\n --->" + exc; ReportError(msg); } internal void ReportError(string msg) { Interlocked.Increment(ref numErrors); msg = $"Error Time: {DateTime.UtcNow:s}\n\t{msg}"; Console.WriteLine(msg); } #endregion } }
using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using OmniSharp.Mef; using OmniSharp.Models; using OmniSharp.Models.SignatureHelp; namespace OmniSharp.Roslyn.CSharp.Services.Signatures { [OmniSharpHandler(OmniSharpEndpoints.SignatureHelp, LanguageNames.CSharp)] public class SignatureHelpService : IRequestHandler<SignatureHelpRequest, SignatureHelpResponse> { private readonly OmniSharpWorkspace _workspace; [ImportingConstructor] public SignatureHelpService(OmniSharpWorkspace workspace) { _workspace = workspace; } public async Task<SignatureHelpResponse> Handle(SignatureHelpRequest request) { var invocations = new List<InvocationContext>(); foreach (var document in _workspace.GetDocuments(request.FileName)) { var invocation = await GetInvocation(document, request); if (invocation != null) { invocations.Add(invocation); } } if (invocations.Count == 0) { return null; } var response = new SignatureHelpResponse(); // define active parameter by position foreach (var comma in invocations.First().ArgumentList.Arguments.GetSeparators()) { if (comma.Span.Start > invocations.First().Position) { break; } response.ActiveParameter += 1; } // process all signatures, define active signature by types var signaturesSet = new HashSet<SignatureHelpItem>(); var bestScore = int.MinValue; SignatureHelpItem bestScoredItem = null; foreach (var invocation in invocations) { var types = invocation.ArgumentList.Arguments .Select(argument => invocation.SemanticModel.GetTypeInfo(argument.Expression)); foreach (var methodOverload in GetMethodOverloads(invocation.SemanticModel, invocation.Receiver)) { var signature = BuildSignature(methodOverload); signaturesSet.Add(signature); var score = InvocationScore(methodOverload, types); if (score > bestScore) { bestScore = score; bestScoredItem = signature; } } } var signaturesList = signaturesSet.ToList(); response.Signatures = signaturesList; response.ActiveSignature = signaturesList.IndexOf(bestScoredItem); return response; } private async Task<InvocationContext> GetInvocation(Document document, Request request) { var sourceText = await document.GetTextAsync(); var position = sourceText.Lines.GetPosition(new LinePosition(request.Line, request.Column)); var tree = await document.GetSyntaxTreeAsync(); var root = await tree.GetRootAsync(); var node = root.FindToken(position).Parent; // Walk up until we find a node that we're interested in. while (node != null) { var invocation = node as InvocationExpressionSyntax; if (invocation != null && invocation.ArgumentList.Span.Contains(position)) { return new InvocationContext() { SemanticModel = await document.GetSemanticModelAsync(), Position = position, Receiver = invocation.Expression, ArgumentList = invocation.ArgumentList }; } var objectCreation = node as ObjectCreationExpressionSyntax; if (objectCreation != null && objectCreation.ArgumentList.Span.Contains(position)) { return new InvocationContext() { SemanticModel = await document.GetSemanticModelAsync(), Position = position, Receiver = objectCreation, ArgumentList = objectCreation.ArgumentList }; } node = node.Parent; } return null; } private IEnumerable<IMethodSymbol> GetMethodOverloads(SemanticModel semanticModel, SyntaxNode node) { ISymbol symbol = null; var symbolInfo = semanticModel.GetSymbolInfo(node); if (symbolInfo.Symbol != null) { symbol = symbolInfo.Symbol; } else if (!symbolInfo.CandidateSymbols.IsEmpty) { symbol = symbolInfo.CandidateSymbols.First(); } if (symbol == null || symbol.ContainingType == null) { return new IMethodSymbol[] { }; } return symbol.ContainingType.GetMembers(symbol.Name).OfType<IMethodSymbol>(); } private int InvocationScore(IMethodSymbol symbol, IEnumerable<TypeInfo> types) { var parameters = GetParameters(symbol); if (parameters.Count() < types.Count()) { return int.MinValue; } var score = 0; var invocationEnum = types.GetEnumerator(); var definitionEnum = parameters.GetEnumerator(); while (invocationEnum.MoveNext() && definitionEnum.MoveNext()) { if (invocationEnum.Current.ConvertedType == null) { // 1 point for having a parameter score += 1; } else if (invocationEnum.Current.ConvertedType.Equals(definitionEnum.Current.Type)) { // 2 points for having a parameter and being // the same type score += 2; } } return score; } private static SignatureHelpItem BuildSignature(IMethodSymbol symbol) { var signature = new SignatureHelpItem(); signature.Documentation = symbol.GetDocumentationCommentXml(); signature.Name = symbol.MethodKind == MethodKind.Constructor ? symbol.ContainingType.Name : symbol.Name; signature.Label = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); signature.Parameters = GetParameters(symbol).Select(parameter => { return new SignatureHelpParameter() { Name = parameter.Name, Label = parameter.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat), Documentation = parameter.GetDocumentationCommentXml() }; }); return signature; } private static IEnumerable<IParameterSymbol> GetParameters(IMethodSymbol methodSymbol) { if (!methodSymbol.IsExtensionMethod) { return methodSymbol.Parameters; } else { return methodSymbol.Parameters.RemoveAt(0); } } } }
namespace Hermes.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class Initial : DbMigration { public override void Up() { CreateTable( "dbo.Additional", c => new { Id = c.Int(nullable: false, identity: true), AdditionalTypeId = c.Int(nullable: false), Name = c.String(nullable: false, maxLength: 50), Cost = c.Decimal(nullable: false, precision: 18, scale: 2), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AdditionalType", t => t.AdditionalTypeId, cascadeDelete: true) .Index(t => t.AdditionalTypeId); CreateTable( "dbo.AdditionalTrip", c => new { Id = c.Int(nullable: false, identity: true), RegularId = c.Int(nullable: false), AdditionalId = c.Int(nullable: false), Number = c.Int(nullable: false), Notes = c.String(maxLength: 225), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Additional", t => t.AdditionalId, cascadeDelete: true) .ForeignKey("dbo.Regulars", t => t.RegularId, cascadeDelete: true) .Index(t => t.RegularId) .Index(t => t.AdditionalId); CreateTable( "dbo.Regulars", c => new { Id = c.Int(nullable: false, identity: true), HHID = c.Int(nullable: false), MemberId = c.Int(), TripTypeId = c.Int(nullable: false), KiawahLocation = c.String(nullable: false, maxLength: 50), TripLocation = c.String(nullable: false, maxLength: 50), NonKiawahPickup = c.Boolean(nullable: false), DriverId = c.Int(), Date = c.DateTime(nullable: false), PickupTime = c.Time(nullable: false, precision: 7), OfficerName = c.String(nullable: false, maxLength: 50), VehicleId = c.Int(), Email = c.String(nullable: false, maxLength: 50), Notes = c.String(), IsCancelled = c.Boolean(nullable: false), otherAddress = c.String(maxLength: 50), Phone = c.String(nullable: false, maxLength: 50), Count = c.Int(), Cost = c.Double(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Drivers", t => t.DriverId) .ForeignKey("dbo.Households", t => t.HHID, cascadeDelete: true) .ForeignKey("dbo.Members", t => t.MemberId) .ForeignKey("dbo.TripTypes", t => t.TripTypeId, cascadeDelete: true) .ForeignKey("dbo.Vehicles", t => t.VehicleId) .Index(t => t.HHID) .Index(t => t.MemberId) .Index(t => t.TripTypeId) .Index(t => t.DriverId) .Index(t => t.VehicleId); CreateTable( "dbo.Drivers", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), License = c.String(), ShiftId = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.DriverShift", t => t.ShiftId) .Index(t => t.ShiftId); CreateTable( "dbo.Buses", c => new { Id = c.Int(nullable: false, identity: true), StopsId = c.Int(nullable: false), TripTypeId = c.Int(nullable: false), Kiawah_Id = c.Int(), DriverId = c.Int(nullable: false), BusTimeId = c.Int(), Date = c.DateTime(), GuestId = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.BusTime", t => t.BusTimeId) .ForeignKey("dbo.Drivers", t => t.DriverId, cascadeDelete: true) .ForeignKey("dbo.Guests", t => t.GuestId) .ForeignKey("dbo.Intersections", t => t.StopsId, cascadeDelete: true) .ForeignKey("dbo.Kiawahs", t => t.Kiawah_Id) .ForeignKey("dbo.RouteStops", t => t.StopsId, cascadeDelete: true) .ForeignKey("dbo.TripTypes", t => t.TripTypeId, cascadeDelete: true) .Index(t => t.StopsId) .Index(t => t.TripTypeId) .Index(t => t.Kiawah_Id) .Index(t => t.DriverId) .Index(t => t.BusTimeId) .Index(t => t.GuestId); CreateTable( "dbo.BusTime", c => new { Id = c.Int(nullable: false), StopTime = c.Time(precision: 7), StopLocation = c.String(maxLength: 50), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Guests", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(maxLength: 50), RegularId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Regulars", t => t.RegularId, cascadeDelete: true) .Index(t => t.RegularId); CreateTable( "dbo.Intersections", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), POIId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.POIs", t => t.POIId, cascadeDelete: true) .Index(t => t.POIId); CreateTable( "dbo.POIs", c => new { id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false), Address = c.String(nullable: false), }) .PrimaryKey(t => t.id); CreateTable( "dbo.RouteStops", c => new { Id = c.Int(nullable: false, identity: true), POIId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.POIs", t => t.POIId, cascadeDelete: false) .Index(t => t.POIId); CreateTable( "dbo.Kiawahs", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 50), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Members", c => new { Id = c.Int(nullable: false), Name = c.String(), FamilyRolesId = c.Int(), Email = c.String(), HouseholdId = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.FamilyRoles", t => t.FamilyRolesId) .ForeignKey("dbo.Households", t => t.HouseholdId, cascadeDelete: true) .Index(t => t.FamilyRolesId) .Index(t => t.HouseholdId); CreateTable( "dbo.FamilyRoles", c => new { Id = c.Int(nullable: false), Description = c.String(maxLength: 50), AuthorizedUser = c.Boolean(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Households", c => new { Id = c.Int(nullable: false), Name = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AuthorizedUsers", c => new { Id = c.Int(nullable: false, identity: true), HouseholdId = c.Int(nullable: false), Name = c.String(maxLength: 50), DateCreated = c.DateTime(), DateExpired = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Households", t => t.HouseholdId, cascadeDelete: true) .Index(t => t.HouseholdId); CreateTable( "dbo.BillingAddresses", c => new { Id = c.Int(nullable: false, identity: true), Address2 = c.String(), City = c.String(), State = c.String(), ZipCode = c.String(), Country = c.String(), Address1 = c.String(), HouseholdId = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Households", t => t.HouseholdId) .Index(t => t.HouseholdId); CreateTable( "dbo.KiawahAddresses", c => new { Id = c.Int(nullable: false), Address1 = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Phones", c => new { Id = c.Int(nullable: false, identity: true), Number = c.String(), MemberId = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Members", t => t.MemberId) .Index(t => t.MemberId); CreateTable( "dbo.TripTypes", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Description = c.String(nullable: false), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Costs", c => new { Id = c.Int(nullable: false, identity: true), twoperprice = c.Double(), addperprice = c.Double(), TripTypeId = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.TripTypes", t => t.TripTypeId) .Index(t => t.TripTypeId); CreateTable( "dbo.DriverShift", c => new { Id = c.Int(nullable: false), DriverShift = c.String(maxLength: 50), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.ReturnTrip", c => new { Id = c.Int(nullable: false, identity: true), RegularId = c.Int(nullable: false), PickupTime = c.Time(precision: 7), TripLocation = c.String(maxLength: 50), KiawahLocation = c.String(maxLength: 50), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Regulars", t => t.RegularId, cascadeDelete: false ) .Index(t => t.RegularId); CreateTable( "dbo.ShoppingCart", c => new { Id = c.Int(nullable: false, identity: true), RegularId = c.Int(nullable: false), TotalCost = c.Double(), ShoppingCartDate = c.DateTime(), HouseholdID = c.Int(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Regulars", t => t.RegularId, cascadeDelete: true) .Index(t => t.RegularId); CreateTable( "dbo.Vehicles", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.DailyHours", c => new { id = c.Int(nullable: false, identity: true), Day = c.DateTime(nullable: false), Miles = c.Double(nullable: false), VehicleId = c.Int(), }) .PrimaryKey(t => t.id) .ForeignKey("dbo.Vehicles", t => t.VehicleId) .Index(t => t.VehicleId); CreateTable( "dbo.GasMileages", c => new { Id = c.Int(nullable: false, identity: true), Date = c.DateTime(nullable: false), Mileage = c.Single(nullable: false), Gallons = c.Single(nullable: false), VehicleId = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Vehicles", t => t.VehicleId) .Index(t => t.VehicleId); CreateTable( "dbo.Maintenance", c => new { Id = c.Int(nullable: false), Date = c.DateTime(), Type = c.String(maxLength: 50), Description = c.String(maxLength: 50), Cost = c.Double(), VehicleId = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Vehicles", t => t.VehicleId) .Index(t => t.VehicleId); CreateTable( "dbo.AdditionalType", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(maxLength: 50), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.KiawahLocations", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Address = c.String(), City = c.String(), Directions = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.sysdiagrams", c => new { diagram_id = c.Int(nullable: false, identity: true), name = c.String(nullable: false, maxLength: 128), principal_id = c.Int(nullable: false), version = c.Int(), definition = c.Binary(), }) .PrimaryKey(t => t.diagram_id); CreateTable( "dbo.TripLocations", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Address = c.String(), City = c.String(), Directions = c.String(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.Ownership", c => new { HouseholdId = c.Int(nullable: false), KiawahLocationsId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.HouseholdId, t.KiawahLocationsId }) .ForeignKey("dbo.Households", t => t.HouseholdId, cascadeDelete: true) .ForeignKey("dbo.KiawahAddresses", t => t.KiawahLocationsId, cascadeDelete: true) .Index(t => t.HouseholdId) .Index(t => t.KiawahLocationsId); CreateTable( "dbo.RegularTrips", c => new { MemberId = c.Int(nullable: false), RegularId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.MemberId, t.RegularId }) .ForeignKey("dbo.Members", t => t.MemberId, cascadeDelete: true) .ForeignKey("dbo.Regulars", t => t.RegularId, cascadeDelete: false) .Index(t => t.MemberId) .Index(t => t.RegularId); CreateTable( "dbo.BusTrips", c => new { BusId = c.Int(nullable: false), MemberId = c.Int(nullable: false), }) .PrimaryKey(t => new { t.BusId, t.MemberId }) .ForeignKey("dbo.Buses", t => t.BusId, cascadeDelete: false) .ForeignKey("dbo.Members", t => t.MemberId, cascadeDelete: true) .Index(t => t.BusId) .Index(t => t.MemberId); } public override void Down() { DropForeignKey("dbo.Additional", "AdditionalTypeId", "dbo.AdditionalType"); DropForeignKey("dbo.AdditionalTrip", "RegularId", "dbo.Regulars"); DropForeignKey("dbo.Regulars", "VehicleId", "dbo.Vehicles"); DropForeignKey("dbo.Maintenance", "VehicleId", "dbo.Vehicles"); DropForeignKey("dbo.GasMileages", "VehicleId", "dbo.Vehicles"); DropForeignKey("dbo.DailyHours", "VehicleId", "dbo.Vehicles"); DropForeignKey("dbo.Regulars", "TripTypeId", "dbo.TripTypes"); DropForeignKey("dbo.ShoppingCart", "RegularId", "dbo.Regulars"); DropForeignKey("dbo.ReturnTrip", "RegularId", "dbo.Regulars"); DropForeignKey("dbo.Regulars", "MemberId", "dbo.Members"); DropForeignKey("dbo.Regulars", "HHID", "dbo.Households"); DropForeignKey("dbo.Regulars", "DriverId", "dbo.Drivers"); DropForeignKey("dbo.Drivers", "ShiftId", "dbo.DriverShift"); DropForeignKey("dbo.Buses", "TripTypeId", "dbo.TripTypes"); DropForeignKey("dbo.Costs", "TripTypeId", "dbo.TripTypes"); DropForeignKey("dbo.Buses", "StopsId", "dbo.RouteStops"); DropForeignKey("dbo.BusTrips", "MemberId", "dbo.Members"); DropForeignKey("dbo.BusTrips", "BusId", "dbo.Buses"); DropForeignKey("dbo.RegularTrips", "RegularId", "dbo.Regulars"); DropForeignKey("dbo.RegularTrips", "MemberId", "dbo.Members"); DropForeignKey("dbo.Phones", "MemberId", "dbo.Members"); DropForeignKey("dbo.Members", "HouseholdId", "dbo.Households"); DropForeignKey("dbo.Ownership", "KiawahLocationsId", "dbo.KiawahAddresses"); DropForeignKey("dbo.Ownership", "HouseholdId", "dbo.Households"); DropForeignKey("dbo.BillingAddresses", "HouseholdId", "dbo.Households"); DropForeignKey("dbo.AuthorizedUsers", "HouseholdId", "dbo.Households"); DropForeignKey("dbo.Members", "FamilyRolesId", "dbo.FamilyRoles"); DropForeignKey("dbo.Buses", "Kiawah_Id", "dbo.Kiawahs"); DropForeignKey("dbo.Buses", "StopsId", "dbo.Intersections"); DropForeignKey("dbo.Intersections", "POIId", "dbo.POIs"); DropForeignKey("dbo.RouteStops", "POIId", "dbo.POIs"); DropForeignKey("dbo.Buses", "GuestId", "dbo.Guests"); DropForeignKey("dbo.Guests", "RegularId", "dbo.Regulars"); DropForeignKey("dbo.Buses", "DriverId", "dbo.Drivers"); DropForeignKey("dbo.Buses", "BusTimeId", "dbo.BusTime"); DropForeignKey("dbo.AdditionalTrip", "AdditionalId", "dbo.Additional"); DropIndex("dbo.BusTrips", new[] { "MemberId" }); DropIndex("dbo.BusTrips", new[] { "BusId" }); DropIndex("dbo.RegularTrips", new[] { "RegularId" }); DropIndex("dbo.RegularTrips", new[] { "MemberId" }); DropIndex("dbo.Ownership", new[] { "KiawahLocationsId" }); DropIndex("dbo.Ownership", new[] { "HouseholdId" }); DropIndex("dbo.Maintenance", new[] { "VehicleId" }); DropIndex("dbo.GasMileages", new[] { "VehicleId" }); DropIndex("dbo.DailyHours", new[] { "VehicleId" }); DropIndex("dbo.ShoppingCart", new[] { "RegularId" }); DropIndex("dbo.ReturnTrip", new[] { "RegularId" }); DropIndex("dbo.Costs", new[] { "TripTypeId" }); DropIndex("dbo.Phones", new[] { "MemberId" }); DropIndex("dbo.BillingAddresses", new[] { "HouseholdId" }); DropIndex("dbo.AuthorizedUsers", new[] { "HouseholdId" }); DropIndex("dbo.Members", new[] { "HouseholdId" }); DropIndex("dbo.Members", new[] { "FamilyRolesId" }); DropIndex("dbo.RouteStops", new[] { "POIId" }); DropIndex("dbo.Intersections", new[] { "POIId" }); DropIndex("dbo.Guests", new[] { "RegularId" }); DropIndex("dbo.Buses", new[] { "GuestId" }); DropIndex("dbo.Buses", new[] { "BusTimeId" }); DropIndex("dbo.Buses", new[] { "DriverId" }); DropIndex("dbo.Buses", new[] { "Kiawah_Id" }); DropIndex("dbo.Buses", new[] { "TripTypeId" }); DropIndex("dbo.Buses", new[] { "StopsId" }); DropIndex("dbo.Drivers", new[] { "ShiftId" }); DropIndex("dbo.Regulars", new[] { "VehicleId" }); DropIndex("dbo.Regulars", new[] { "DriverId" }); DropIndex("dbo.Regulars", new[] { "TripTypeId" }); DropIndex("dbo.Regulars", new[] { "MemberId" }); DropIndex("dbo.Regulars", new[] { "HHID" }); DropIndex("dbo.AdditionalTrip", new[] { "AdditionalId" }); DropIndex("dbo.AdditionalTrip", new[] { "RegularId" }); DropIndex("dbo.Additional", new[] { "AdditionalTypeId" }); DropTable("dbo.BusTrips"); DropTable("dbo.RegularTrips"); DropTable("dbo.Ownership"); DropTable("dbo.TripLocations"); DropTable("dbo.sysdiagrams"); DropTable("dbo.KiawahLocations"); DropTable("dbo.AdditionalType"); DropTable("dbo.Maintenance"); DropTable("dbo.GasMileages"); DropTable("dbo.DailyHours"); DropTable("dbo.Vehicles"); DropTable("dbo.ShoppingCart"); DropTable("dbo.ReturnTrip"); DropTable("dbo.DriverShift"); DropTable("dbo.Costs"); DropTable("dbo.TripTypes"); DropTable("dbo.Phones"); DropTable("dbo.KiawahAddresses"); DropTable("dbo.BillingAddresses"); DropTable("dbo.AuthorizedUsers"); DropTable("dbo.Households"); DropTable("dbo.FamilyRoles"); DropTable("dbo.Members"); DropTable("dbo.Kiawahs"); DropTable("dbo.RouteStops"); DropTable("dbo.POIs"); DropTable("dbo.Intersections"); DropTable("dbo.Guests"); DropTable("dbo.BusTime"); DropTable("dbo.Buses"); DropTable("dbo.Drivers"); DropTable("dbo.Regulars"); DropTable("dbo.AdditionalTrip"); DropTable("dbo.Additional"); } } }
using System.Collections.Generic; using System.Linq; namespace NuGet.Client.VisualStudio.UI { // SelectedAction -> SelectedVersion // SelectedVersion -> ProjectList update public class PackageSolutionDetailControlModel : PackageDetailControlModel { // list of projects where the package is installed private List<PackageInstallationInfo> _projects; private VsSolution _solution; private List<string> _actions; public List<PackageInstallationInfo> Projects { get { return _projects; } } public List<string> Actions { get { return _actions; } } private string _selectedAction; public string SelectedAction { get { return _selectedAction; } set { _selectedAction = value; InstallOptionsVisible = SelectedAction != Resources.Resources.Action_Uninstall; CreateVersions(); OnPropertyChanged("SelectedAction"); } } private bool _actionEnabled; // Indicates if the action button and preview button is enabled. public bool ActionEnabled { get { return _actionEnabled; } set { _actionEnabled = value; OnPropertyChanged("ActionEnabled"); } } protected override void OnSelectedVersionChanged() { CreateProjectList(); UiDetailedPackage selectedPackage = null; if (_allPackages.TryGetValue(SelectedVersion.Version, out selectedPackage)) { Package = selectedPackage; } else { Package = null; } } private void CreateVersions() { if (_selectedAction == Resources.Resources.Action_Consolidate || _selectedAction == Resources.Resources.Action_Uninstall) { var installedVersions = _solution.Projects .Select(project => project.InstalledPackages.GetInstalledPackage(Package.Id)) .ToList(); installedVersions.Add(_solution.InstalledPackages.GetInstalledPackage(Package.Id)); _versions = installedVersions.Where(package => package != null) .OrderByDescending(p => p.Identity.Version) .Select(package => new VersionForDisplay(package.Identity.Version, string.Empty)) .ToList(); } else if (_selectedAction == Resources.Resources.Action_Install || _selectedAction == Resources.Resources.Action_Update) { _versions = new List<VersionForDisplay>(); var allVersions = _allPackages.Keys.OrderByDescending(v => v); var latestStableVersion = allVersions.FirstOrDefault(v => !v.IsPrerelease); if (latestStableVersion != null) { _versions.Add(new VersionForDisplay(latestStableVersion, "Latest stable ")); } // add a separator if (_versions.Count > 0) { _versions.Add(null); } foreach (var version in allVersions) { _versions.Add(new VersionForDisplay(version, string.Empty)); } } if (_versions.Count > 0) { SelectedVersion = _versions[0]; } OnPropertyChanged("Versions"); } public PackageSolutionDetailControlModel( UiSearchResultPackage searchResultPackage, VsSolution solution) : base(searchResultPackage, installedVersion: null) { _solution = solution; SelectedVersion = new VersionForDisplay(Package.Version, null); CreateActions(); } private bool CanUpdate() { var canUpdateInProjects = _solution.Projects .Any(project => { return project.InstalledPackages.IsInstalled(Package.Id) && _allPackages.Count >= 2; }); var installedInSolution = _solution.InstalledPackages.IsInstalled(Package.Id); var canUpdateInSolution = installedInSolution && _allPackages.Count >= 2; return canUpdateInProjects || canUpdateInSolution; } private bool CanInstall() { var canInstallInProjects = _solution.Projects .Any(project => { return !project.InstalledPackages.IsInstalled(Package.Id); }); var installedInSolution = _solution.InstalledPackages.IsInstalled(Package.Id); return !installedInSolution && canInstallInProjects; } private bool CanUninstall() { var canUninstallFromProjects = _solution.Projects .Any(project => { return project.InstalledPackages.IsInstalled(Package.Id); }); var installedInSolution = _solution.InstalledPackages.IsInstalled(Package.Id); return installedInSolution || canUninstallFromProjects; } private bool CanConsolidate() { var installedVersions = _solution.Projects .Select(project => project.InstalledPackages.GetInstalledPackage(Package.Id)) .Where(package => package != null) .Select(package => package.Identity.Version) .Distinct(); return installedVersions.Count() >= 2; } // indicates if the install options expander is visible or not bool _installOptionsVisible; public bool InstallOptionsVisible { get { return _installOptionsVisible; } set { if (_installOptionsVisible != value) { _installOptionsVisible = value; OnPropertyChanged("InstallOptionsVisible"); } } } private void CreateActions() { // initialize actions _actions = new List<string>(); if (CanUpdate()) { _actions.Add(Resources.Resources.Action_Update); } if (CanInstall()) { _actions.Add(Resources.Resources.Action_Install); } if (CanUninstall()) { _actions.Add(Resources.Resources.Action_Uninstall); } if (CanConsolidate()) { _actions.Add(Resources.Resources.Action_Consolidate); } if (_actions.Count > 0) { SelectedAction = _actions[0]; } else { InstallOptionsVisible = false; } OnPropertyChanged("Actions"); } private void CreateProjectList() { _projects = new List<PackageInstallationInfo>(); if (_selectedAction == Resources.Resources.Action_Consolidate) { // project list contains projects that have the package installed. // The project with the same version installed is included, but disabled. foreach (var project in _solution.Projects) { var installed = project.InstalledPackages.GetInstalledPackage(Package.Id); if (installed != null) { var enabled = installed.Identity.Version != SelectedVersion.Version; var info = new PackageInstallationInfo(project, installed.Identity.Version, enabled); _projects.Add(info); } } } else if (_selectedAction == Resources.Resources.Action_Update) { // project list contains projects/solution that have the package // installed. The project/solution with the same version installed // is included, but disabled. foreach (var project in _solution.Projects) { var installed = project.InstalledPackages.GetInstalledPackage(Package.Id); if (installed != null) { var enabled = installed.Identity.Version != SelectedVersion.Version; var info = new PackageInstallationInfo(project, installed.Identity.Version, enabled); _projects.Add(info); } } var v = _solution.InstalledPackages.GetInstalledPackage(Package.Id); if (v != null) { var enabled = v.Identity.Version != SelectedVersion.Version; var info = new PackageInstallationInfo( _solution.Name, SelectedVersion.Version, enabled, _solution.Projects.First()); _projects.Add(info); } } else if (_selectedAction == Resources.Resources.Action_Install) { // project list contains projects that do not have the package installed. foreach (var project in _solution.Projects) { var installed = project.InstalledPackages.GetInstalledPackage(Package.Id); if (installed == null) { var info = new PackageInstallationInfo(project, null, enabled: true); _projects.Add(info); } } } else if (_selectedAction == Resources.Resources.Action_Uninstall) { // project list contains projects/solution that have the same version installed. foreach (var project in _solution.Projects) { var installed = project.InstalledPackages.GetInstalledPackage(Package.Id); if (installed != null && installed.Identity.Version == SelectedVersion.Version) { var info = new PackageInstallationInfo(project, installed.Identity.Version, enabled: true); _projects.Add(info); } } var v = _solution.InstalledPackages.GetInstalledPackage(Package.Id); if (v != null) { var enabled = v.Identity.Version == SelectedVersion.Version; var info = new PackageInstallationInfo( _solution.Name, SelectedVersion.Version, enabled, _solution.Projects.First()); _projects.Add(info); } } foreach (var p in _projects) { p.SelectedChanged += (sender, e) => { ActionEnabled = _projects.Any(i => i.Selected); }; } ActionEnabled = _projects.Any(i => i.Selected); OnPropertyChanged("Projects"); } public void Refresh() { SelectedVersion = new VersionForDisplay(Package.Version, null); CreateActions(); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Diagnostics; using System.ServiceModel.Diagnostics; using System.Text; using System.Xml; using System.Xml.Serialization; using System.Runtime.Serialization.Diagnostics; #if USE_REFEMIT public class XmlObjectSerializerReadContext : XmlObjectSerializerContext #else internal class XmlObjectSerializerReadContext : XmlObjectSerializerContext #endif { internal Attributes attributes; HybridObjectCache deserializedObjects; XmlSerializableReader xmlSerializableReader; XmlDocument xmlDocument; Attributes attributesInXmlData; XmlReaderDelegator extensionDataReader; object getOnlyCollectionValue; bool isGetOnlyCollection; HybridObjectCache DeserializedObjects { get { if (deserializedObjects == null) deserializedObjects = new HybridObjectCache(); return deserializedObjects; } } XmlDocument Document { get { if (xmlDocument == null) xmlDocument = new XmlDocument(); return xmlDocument; } } internal override bool IsGetOnlyCollection { get { return this.isGetOnlyCollection; } set { this.isGetOnlyCollection = value; } } #if USE_REFEMIT public object GetCollectionMember() #else internal object GetCollectionMember() #endif { return this.getOnlyCollectionValue; } #if USE_REFEMIT public void StoreCollectionMemberInfo(object collectionMember) #else internal void StoreCollectionMemberInfo(object collectionMember) #endif { this.getOnlyCollectionValue = collectionMember; this.isGetOnlyCollection = true; } #if USE_REFEMIT public static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) #else internal static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) #endif { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.NullValueReturnedForGetOnlyCollection, DataContract.GetClrTypeFullName(type)))); } #if USE_REFEMIT public static void ThrowArrayExceededSizeException(int arraySize, Type type) #else internal static void ThrowArrayExceededSizeException(int arraySize, Type type) #endif { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ArrayExceededSize, arraySize, DataContract.GetClrTypeFullName(type)))); } internal static XmlObjectSerializerReadContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) { return (serializer.PreserveObjectReferences || serializer.DataContractSurrogate != null) ? new XmlObjectSerializerReadContextComplex(serializer, rootTypeDataContract, dataContractResolver) : new XmlObjectSerializerReadContext(serializer, rootTypeDataContract, dataContractResolver); } internal static XmlObjectSerializerReadContext CreateContext(NetDataContractSerializer serializer) { return new XmlObjectSerializerReadContextComplex(serializer); } internal XmlObjectSerializerReadContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { this.attributes = new Attributes(); } protected XmlObjectSerializerReadContext(NetDataContractSerializer serializer) : base(serializer) { this.attributes = new Attributes(); } public virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) { DataContract dataContract = GetDataContract(id, declaredTypeHandle); return InternalDeserialize(xmlReader, name, ns, Type.GetTypeFromHandle(declaredTypeHandle), ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) { DataContract dataContract = GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns) { if (dataContract == null) GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); } protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string name, string ns, ref object retObj) { ReadAttributes(reader); if (attributes.Ref != Globals.NewObjectId) { if (this.isGetOnlyCollection) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.IsReferenceGetOnlyCollectionsNotSupported, attributes.Ref, DataContract.GetClrTypeFullName(declaredType)))); } else { retObj = GetExistingObject(attributes.Ref, declaredType, name, ns); reader.Skip(); return true; } } else if (attributes.XsiNil) { reader.Skip(); return true; } return false; } protected object InternalDeserialize(XmlReaderDelegator reader, string name, string ns, Type declaredType, ref DataContract dataContract) { object retObj = null; if (TryHandleNullOrRef(reader, dataContract.UnderlyingType, name, ns, ref retObj)) return retObj; bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } if (attributes.XsiTypeName != null) { dataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract, declaredType); if (dataContract == null) { if (DataContractResolver == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.GetString(SR.DcTypeNotFoundOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.GetString(SR.DcTypeNotResolvedOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope); } if (dataContract.IsISerializable && attributes.FactoryTypeName != null) { DataContract factoryDataContract = ResolveDataContractFromKnownTypes(attributes.FactoryTypeName, attributes.FactoryTypeNamespace, dataContract, declaredType); if (factoryDataContract != null) { if (factoryDataContract.IsISerializable) { dataContract = factoryDataContract; knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope); } else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.FactoryTypeNotISerializable, DataContract.GetClrTypeFullName(factoryDataContract.UnderlyingType), DataContract.GetClrTypeFullName(dataContract.UnderlyingType)))); } else { if (DiagnosticUtility.ShouldTraceWarning) { Dictionary<string, string> values = new Dictionary<string, string>(2); values["FactoryType"] = attributes.FactoryTypeNamespace + ":" + attributes.FactoryTypeName; values["ISerializableType"] = dataContract.StableName.Namespace + ":" + dataContract.StableName.Name; TraceUtility.Trace(TraceEventType.Warning, TraceCode.FactoryTypeNotFound, SR.GetString(SR.TraceCodeFactoryTypeNotFound), new DictionaryTraceRecord(values)); } } } if (knownTypesAddedInCurrentScope) { object obj = ReadDataContractValue(dataContract, reader); scopedKnownTypes.Pop(); return obj; } else { return ReadDataContractValue(dataContract, reader); } } bool ReplaceScopedKnownTypesTop(Dictionary<XmlQualifiedName, DataContract> knownDataContracts, bool knownTypesAddedInCurrentScope) { if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); knownTypesAddedInCurrentScope = false; } if (knownDataContracts != null) { scopedKnownTypes.Push(knownDataContracts); knownTypesAddedInCurrentScope = true; } return knownTypesAddedInCurrentScope; } public static bool MoveToNextElement(XmlReaderDelegator xmlReader) { return (xmlReader.MoveToContent() != XmlNodeType.EndElement); } public int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) return i; } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } public int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) { if (requiredIndex < i) ThrowRequiredMemberMissingException(xmlReader, memberIndex, requiredIndex, memberNames); return i; } } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } public static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames) { StringBuilder stringBuilder = new StringBuilder(); if (requiredIndex == memberNames.Length) requiredIndex--; for (int i = memberIndex + 1; i <= requiredIndex; i++) { if (stringBuilder.Length != 0) stringBuilder.Append(" | "); stringBuilder.Append(memberNames[i].Value); } throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.GetString(SR.UnexpectedElementExpectingElements, xmlReader.NodeType, xmlReader.LocalName, xmlReader.NamespaceURI, stringBuilder.ToString())))); } protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { xmlReader.MoveToContent(); if (xmlReader.NodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (IgnoreExtensionDataObject || extensionData == null) SkipUnknownElement(xmlReader); else HandleUnknownElement(xmlReader, extensionData, memberIndex); } internal void HandleUnknownElement(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { if (extensionData.Members == null) extensionData.Members = new List<ExtensionDataMember>(); extensionData.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex)); } public void SkipUnknownElement(XmlReaderDelegator xmlReader) { ReadAttributes(xmlReader); if (DiagnosticUtility.ShouldTraceVerbose) { TraceUtility.Trace(TraceEventType.Verbose, TraceCode.ElementIgnored, SR.GetString(SR.TraceCodeElementIgnored), new StringTraceRecord("Element", xmlReader.NamespaceURI + ":" + xmlReader.LocalName)); } xmlReader.Skip(); } public string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) { if (attributes.Ref != Globals.NewObjectId) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return attributes.Ref; } else if (attributes.XsiNil) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return Globals.NullObjectId; } return Globals.NewObjectId; } #if USE_REFEMIT public virtual void ReadAttributes(XmlReaderDelegator xmlReader) #else internal virtual void ReadAttributes(XmlReaderDelegator xmlReader) #endif { if (attributes == null) attributes = new Attributes(); attributes.Read(xmlReader); } public void ResetAttributes() { if (attributes != null) attributes.Reset(); } public string GetObjectId() { return attributes.Id; } #if USE_REFEMIT public virtual int GetArraySize() #else internal virtual int GetArraySize() #endif { return -1; } public void AddNewObject(object obj) { AddNewObjectWithId(attributes.Id, obj); } public void AddNewObjectWithId(string id, object obj) { if (id != Globals.NewObjectId) DeserializedObjects.Add(id, obj); if (extensionDataReader != null) extensionDataReader.UnderlyingExtensionDataReader.SetDeserializedValue(obj); } public void ReplaceDeserializedObject(string id, object oldObj, object newObj) { if (object.ReferenceEquals(oldObj, newObj)) return; if (id != Globals.NewObjectId) { // In certain cases (IObjectReference, SerializationSurrogate or DataContractSurrogate), // an object can be replaced with a different object once it is deserialized. If the // object happens to be referenced from within itself, that reference needs to be updated // with the new instance. BinaryFormatter supports this by fixing up such references later. // These XmlObjectSerializer implementations do not currently support fix-ups. Hence we // throw in such cases to allow us add fix-up support in the future if we need to. if (DeserializedObjects.IsObjectReferenced(id)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.FactoryObjectContainsSelfReference, DataContract.GetClrTypeFullName(oldObj.GetType()), DataContract.GetClrTypeFullName(newObj.GetType()), id))); DeserializedObjects.Remove(id); DeserializedObjects.Add(id, newObj); } if (extensionDataReader != null) extensionDataReader.UnderlyingExtensionDataReader.SetDeserializedValue(newObj); } public object GetExistingObject(string id, Type type, string name, string ns) { object retObj = DeserializedObjects.GetObject(id); if (retObj == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.DeserializedObjectWithIdNotFound, id))); if (retObj is IDataNode) { IDataNode dataNode = (IDataNode)retObj; retObj = (dataNode.Value != null && dataNode.IsFinalValue) ? dataNode.Value : DeserializeFromExtensionData(dataNode, type, name, ns); } return retObj; } object GetExistingObjectOrExtensionData(string id) { object retObj = DeserializedObjects.GetObject(id); if (retObj == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.DeserializedObjectWithIdNotFound, id))); return retObj; } public object GetRealObject(IObjectReference obj, string id) { object realObj = SurrogateDataContract.GetRealObject(obj, this.GetStreamingContext()); // If GetRealObject returns null, it indicates that the object could not resolve itself because // it is missing information. This may occur in a case where multiple IObjectReference instances // depend on each other. BinaryFormatter supports this by fixing up the references later. These // XmlObjectSerializer implementations do not support fix-ups since the format does not contain // forward references. However, we throw for this case since it allows us to add fix-up support // in the future if we need to. if (realObj == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.GetRealObjectReturnedNull, DataContract.GetClrTypeFullName(obj.GetType())))); ReplaceDeserializedObject(id, obj, realObj); return realObj; } object DeserializeFromExtensionData(IDataNode dataNode, Type type, string name, string ns) { ExtensionDataReader underlyingExtensionDataReader; if (extensionDataReader == null) { underlyingExtensionDataReader = new ExtensionDataReader(this); extensionDataReader = CreateReaderDelegatorForReader(underlyingExtensionDataReader); } else underlyingExtensionDataReader = extensionDataReader.UnderlyingExtensionDataReader; underlyingExtensionDataReader.SetDataNode(dataNode, name, ns); object retObj = InternalDeserialize(extensionDataReader, type, name, ns); dataNode.Clear(); underlyingExtensionDataReader.Reset(); return retObj; } public static void Read(XmlReaderDelegator xmlReader) { if (!xmlReader.Read()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.UnexpectedEndOfFile))); } internal static void ParseQualifiedName(string qname, XmlReaderDelegator xmlReader, out string name, out string ns, out string prefix) { int colon = qname.IndexOf(':'); prefix = ""; if (colon >= 0) prefix = qname.Substring(0, colon); name = qname.Substring(colon + 1); ns = xmlReader.LookupNamespace(prefix); } public static T[] EnsureArraySize<T>(T[] array, int index) { if (array.Length <= index) { if (index == Int32.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( XmlObjectSerializer.CreateSerializationException( SR.GetString(SR.MaxArrayLengthExceeded, Int32.MaxValue, DataContract.GetClrTypeFullName(typeof(T))))); } int newSize = (index < Int32.MaxValue / 2) ? index * 2 : Int32.MaxValue; T[] newArray = new T[newSize]; Array.Copy(array, 0, newArray, 0, array.Length); array = newArray; } return array; } public static T[] TrimArraySize<T>(T[] array, int size) { if (size != array.Length) { T[] newArray = new T[size]; Array.Copy(array, 0, newArray, 0, size); array = newArray; } return array; } public void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (xmlReader.NodeType == XmlNodeType.EndElement) return; while (xmlReader.IsStartElement()) { if (xmlReader.IsStartElement(itemName, itemNamespace)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ArrayExceededSizeAttribute, arraySize, itemName.Value, itemNamespace.Value))); SkipUnknownElement(xmlReader); } if (xmlReader.NodeType != XmlNodeType.EndElement) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.EndElement, xmlReader)); } internal object ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { if (xmlSerializableReader == null) xmlSerializableReader = new XmlSerializableReader(); return ReadIXmlSerializable(xmlSerializableReader, xmlReader, xmlDataContract, isMemberType); } internal static object ReadRootIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { return ReadIXmlSerializable(new XmlSerializableReader(), xmlReader, xmlDataContract, isMemberType); } internal static object ReadIXmlSerializable(XmlSerializableReader xmlSerializableReader, XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { object obj = null; xmlSerializableReader.BeginRead(xmlReader); if (isMemberType && !xmlDataContract.HasRoot) { xmlReader.Read(); xmlReader.MoveToContent(); } if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlElement) { if (!xmlReader.IsStartElement()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); XmlDocument xmlDoc = new XmlDocument(); obj = (XmlElement)xmlDoc.ReadNode(xmlSerializableReader); } else if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlNodeArray) { obj = XmlSerializableServices.ReadNodes(xmlSerializableReader); } else { IXmlSerializable xmlSerializable = xmlDataContract.CreateXmlSerializableDelegate(); xmlSerializable.ReadXml(xmlSerializableReader); obj = xmlSerializable; } xmlSerializableReader.EndRead(); return obj; } public SerializationInfo ReadSerializationInfo(XmlReaderDelegator xmlReader, Type type) { SerializationInfo serInfo = new SerializationInfo(type, XmlObjectSerializer.FormatterConverter); XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (xmlReader.NamespaceURI.Length != 0) { SkipUnknownElement(xmlReader); continue; } string name = XmlConvert.DecodeName(xmlReader.LocalName); IncrementItemCount(1); ReadAttributes(xmlReader); object value; if (attributes.Ref != Globals.NewObjectId) { xmlReader.Skip(); value = GetExistingObject(attributes.Ref, null, name, String.Empty); } else if (attributes.XsiNil) { xmlReader.Skip(); value = null; } else { value = InternalDeserialize(xmlReader, Globals.TypeOfObject, name, String.Empty); } serInfo.AddValue(name, value); } return serInfo; } protected virtual DataContract ResolveDataContractFromTypeName() { return (attributes.XsiTypeName == null) ? null : ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, null /*memberTypeContract*/, null); } ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader, int memberIndex) { ExtensionDataMember member = new ExtensionDataMember(); member.Name = xmlReader.LocalName; member.Namespace = xmlReader.NamespaceURI; member.MemberIndex = memberIndex; if (xmlReader.UnderlyingExtensionDataReader != null) { // no need to re-read extension data structure member.Value = xmlReader.UnderlyingExtensionDataReader.GetCurrentNode(); } else member.Value = ReadExtensionDataValue(xmlReader); return member; } public IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader) { ReadAttributes(xmlReader); IncrementItemCount(1); IDataNode dataNode = null; if (attributes.Ref != Globals.NewObjectId) { xmlReader.Skip(); object o = GetExistingObjectOrExtensionData(attributes.Ref); dataNode = (o is IDataNode) ? (IDataNode)o : new DataNode<object>(o); dataNode.Id = attributes.Ref; } else if (attributes.XsiNil) { xmlReader.Skip(); dataNode = null; } else { string dataContractName = null; string dataContractNamespace = null; if (attributes.XsiTypeName != null) { dataContractName = attributes.XsiTypeName; dataContractNamespace = attributes.XsiTypeNamespace; } if (IsReadingCollectionExtensionData(xmlReader)) { Read(xmlReader); dataNode = ReadUnknownCollectionData(xmlReader, dataContractName, dataContractNamespace); } else if (attributes.FactoryTypeName != null) { Read(xmlReader); dataNode = ReadUnknownISerializableData(xmlReader, dataContractName, dataContractNamespace); } else if (IsReadingClassExtensionData(xmlReader)) { Read(xmlReader); dataNode = ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); } else { DataContract dataContract = ResolveDataContractFromTypeName(); if (dataContract == null) dataNode = ReadExtensionDataValue(xmlReader, dataContractName, dataContractNamespace); else if (dataContract is XmlDataContract) dataNode = ReadUnknownXmlData(xmlReader, dataContractName, dataContractNamespace); else { if (dataContract.IsISerializable) { Read(xmlReader); dataNode = ReadUnknownISerializableData(xmlReader, dataContractName, dataContractNamespace); } else if (dataContract is PrimitiveDataContract) { if (attributes.Id == Globals.NewObjectId) { Read(xmlReader); xmlReader.MoveToContent(); dataNode = ReadUnknownPrimitiveData(xmlReader, dataContract.UnderlyingType, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); } else { dataNode = new DataNode<object>(xmlReader.ReadElementContentAsAnyType(dataContract.UnderlyingType)); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); } } else if (dataContract is EnumDataContract) { dataNode = new DataNode<object>(((EnumDataContract)dataContract).ReadEnumValue(xmlReader)); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); } else if (dataContract is ClassDataContract) { Read(xmlReader); dataNode = ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); } else if (dataContract is CollectionDataContract) { Read(xmlReader); dataNode = ReadUnknownCollectionData(xmlReader, dataContractName, dataContractNamespace); } } } } return dataNode; } protected virtual void StartReadExtensionDataValue(XmlReaderDelegator xmlReader) { } IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { StartReadExtensionDataValue(xmlReader); if (attributes.UnrecognizedAttributesFound) return ReadUnknownXmlData(xmlReader, dataContractName, dataContractNamespace); IDictionary<string, string> namespacesInScope = xmlReader.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml); Read(xmlReader); xmlReader.MoveToContent(); switch (xmlReader.NodeType) { case XmlNodeType.Text: return ReadPrimitiveExtensionDataValue(xmlReader, dataContractName, dataContractNamespace); case XmlNodeType.Element: if (xmlReader.NamespaceURI.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal)) return ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); else return ReadAndResolveUnknownXmlData(xmlReader, namespacesInScope, dataContractName, dataContractNamespace); case XmlNodeType.EndElement: { // NOTE: cannot distinguish between empty class or IXmlSerializable and typeof(object) IDataNode objNode = ReadUnknownPrimitiveData(xmlReader, Globals.TypeOfObject, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); objNode.IsFinalValue = false; return objNode; } default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } } protected virtual IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { Type valueType = xmlReader.ValueType; if (valueType == Globals.TypeOfString) { // NOTE: cannot distinguish other primitives from string (default XmlReader ValueType) IDataNode stringNode = new DataNode<object>(xmlReader.ReadContentAsString()); InitializeExtensionDataNode(stringNode, dataContractName, dataContractNamespace); stringNode.IsFinalValue = false; xmlReader.ReadEndElement(); return stringNode; } else { IDataNode objNode = ReadUnknownPrimitiveData(xmlReader, valueType, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); return objNode; } } protected void InitializeExtensionDataNode(IDataNode dataNode, string dataContractName, string dataContractNamespace) { dataNode.DataContractName = dataContractName; dataNode.DataContractNamespace = dataContractNamespace; dataNode.ClrAssemblyName = attributes.ClrAssembly; dataNode.ClrTypeName = attributes.ClrType; AddNewObject(dataNode); dataNode.Id = attributes.Id; } IDataNode ReadUnknownPrimitiveData(XmlReaderDelegator xmlReader, Type type, string dataContractName, string dataContractNamespace) { IDataNode dataNode = xmlReader.ReadExtensionData(type); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); return dataNode; } ClassDataNode ReadUnknownClassData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { ClassDataNode dataNode = new ClassDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); int memberIndex = 0; XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (dataNode.Members == null) dataNode.Members = new List<ExtensionDataMember>(); dataNode.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex++)); } xmlReader.ReadEndElement(); return dataNode; } CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { CollectionDataNode dataNode = new CollectionDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); int arraySize = attributes.ArraySZSize; XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (dataNode.ItemName == null) { dataNode.ItemName = xmlReader.LocalName; dataNode.ItemNamespace = xmlReader.NamespaceURI; } if (xmlReader.IsStartElement(dataNode.ItemName, dataNode.ItemNamespace)) { if (dataNode.Items == null) dataNode.Items = new List<IDataNode>(); dataNode.Items.Add(ReadExtensionDataValue(xmlReader)); } else SkipUnknownElement(xmlReader); } xmlReader.ReadEndElement(); if (arraySize != -1) { dataNode.Size = arraySize; if (dataNode.Items == null) { if (dataNode.Size > 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ArraySizeAttributeIncorrect, arraySize, 0))); } else if (dataNode.Size != dataNode.Items.Count) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.ArraySizeAttributeIncorrect, arraySize, dataNode.Items.Count))); } else { if (dataNode.Items != null) { dataNode.Size = dataNode.Items.Count; } else { dataNode.Size = 0; } } return dataNode; } ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { ISerializableDataNode dataNode = new ISerializableDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); dataNode.FactoryTypeName = attributes.FactoryTypeName; dataNode.FactoryTypeNamespace = attributes.FactoryTypeNamespace; XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (xmlReader.NamespaceURI.Length != 0) { SkipUnknownElement(xmlReader); continue; } ISerializableDataMember member = new ISerializableDataMember(); member.Name = xmlReader.LocalName; member.Value = ReadExtensionDataValue(xmlReader); if (dataNode.Members == null) dataNode.Members = new List<ISerializableDataMember>(); dataNode.Members.Add(member); } xmlReader.ReadEndElement(); return dataNode; } IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { XmlDataNode dataNode = new XmlDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); dataNode.OwnerDocument = Document; if (xmlReader.NodeType == XmlNodeType.EndElement) return dataNode; IList<XmlAttribute> xmlAttributes = null; IList<XmlNode> xmlChildNodes = null; XmlNodeType nodeType = xmlReader.MoveToContent(); if (nodeType != XmlNodeType.Text) { while (xmlReader.MoveToNextAttribute()) { string ns = xmlReader.NamespaceURI; if (ns != Globals.SerializationNamespace && ns != Globals.SchemaInstanceNamespace) { if (xmlAttributes == null) xmlAttributes = new List<XmlAttribute>(); xmlAttributes.Add((XmlAttribute)Document.ReadNode(xmlReader.UnderlyingReader)); } } Read(xmlReader); } while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (xmlReader.EOF) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.UnexpectedEndOfFile))); if (xmlChildNodes == null) xmlChildNodes = new List<XmlNode>(); xmlChildNodes.Add(Document.ReadNode(xmlReader.UnderlyingReader)); } xmlReader.ReadEndElement(); dataNode.XmlAttributes = xmlAttributes; dataNode.XmlChildNodes = xmlChildNodes; return dataNode; } // Pattern-recognition logic: the method reads XML elements into DOM. To recognize as an array, it requires that // all items have the same name and namespace. To recognize as an ISerializable type, it requires that all // items be unqualified. If the XML only contains elements (no attributes or other nodes) is recognized as a // class/class hierarchy. Otherwise it is deserialized as XML. IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDictionary<string, string> namespaces, string dataContractName, string dataContractNamespace) { bool couldBeISerializableData = true; bool couldBeCollectionData = true; bool couldBeClassData = true; string elementNs = null, elementName = null; IList<XmlNode> xmlChildNodes = new List<XmlNode>(); IList<XmlAttribute> xmlAttributes = null; if (namespaces != null) { xmlAttributes = new List<XmlAttribute>(); foreach (KeyValuePair<string, string> prefixNsPair in namespaces) { xmlAttributes.Add(AddNamespaceDeclaration(prefixNsPair.Key, prefixNsPair.Value)); } } XmlNodeType nodeType; while ((nodeType = xmlReader.NodeType) != XmlNodeType.EndElement) { if (nodeType == XmlNodeType.Element) { string ns = xmlReader.NamespaceURI; string name = xmlReader.LocalName; if (couldBeISerializableData) couldBeISerializableData = (ns.Length == 0); if (couldBeCollectionData) { if (elementName == null) { elementName = name; elementNs = ns; } else couldBeCollectionData = (String.CompareOrdinal(elementName, name) == 0) && (String.CompareOrdinal(elementNs, ns) == 0); } } else if (xmlReader.EOF) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.UnexpectedEndOfFile))); else if (IsContentNode(xmlReader.NodeType)) couldBeClassData = couldBeISerializableData = couldBeCollectionData = false; if (attributesInXmlData == null) attributesInXmlData = new Attributes(); attributesInXmlData.Read(xmlReader); XmlNode childNode = Document.ReadNode(xmlReader.UnderlyingReader); xmlChildNodes.Add(childNode); if (namespaces == null) { if (attributesInXmlData.XsiTypeName != null) childNode.Attributes.Append(AddNamespaceDeclaration(attributesInXmlData.XsiTypePrefix, attributesInXmlData.XsiTypeNamespace)); if (attributesInXmlData.FactoryTypeName != null) childNode.Attributes.Append(AddNamespaceDeclaration(attributesInXmlData.FactoryTypePrefix, attributesInXmlData.FactoryTypeNamespace)); } } xmlReader.ReadEndElement(); if (elementName != null && couldBeCollectionData) return ReadUnknownCollectionData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace); else if (couldBeISerializableData) return ReadUnknownISerializableData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace); else if (couldBeClassData) return ReadUnknownClassData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace); else { XmlDataNode dataNode = new XmlDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); dataNode.OwnerDocument = Document; dataNode.XmlChildNodes = xmlChildNodes; dataNode.XmlAttributes = xmlAttributes; return dataNode; } } bool IsContentNode(XmlNodeType nodeType) { switch (nodeType) { case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: return false; default: return true; } } internal XmlReaderDelegator CreateReaderOverChildNodes(IList<XmlAttribute> xmlAttributes, IList<XmlNode> xmlChildNodes) { XmlNode wrapperElement = CreateWrapperXmlElement(Document, xmlAttributes, xmlChildNodes, null, null, null); XmlReaderDelegator nodeReader = CreateReaderDelegatorForReader(new XmlNodeReader(wrapperElement)); nodeReader.MoveToContent(); Read(nodeReader); return nodeReader; } internal static XmlNode CreateWrapperXmlElement(XmlDocument document, IList<XmlAttribute> xmlAttributes, IList<XmlNode> xmlChildNodes, string prefix, string localName, string ns) { localName = localName ?? "wrapper"; ns = ns ?? String.Empty; XmlNode wrapperElement = document.CreateElement(prefix, localName, ns); if (xmlAttributes != null) { for (int i = 0; i < xmlAttributes.Count; i++) wrapperElement.Attributes.Append((XmlAttribute)xmlAttributes[i]); } if (xmlChildNodes != null) { for (int i = 0; i < xmlChildNodes.Count; i++) wrapperElement.AppendChild(xmlChildNodes[i]); } return wrapperElement; } XmlAttribute AddNamespaceDeclaration(string prefix, string ns) { XmlAttribute attribute = (prefix == null || prefix.Length == 0) ? Document.CreateAttribute(null, Globals.XmlnsPrefix, Globals.XmlnsNamespace) : Document.CreateAttribute(Globals.XmlnsPrefix, prefix, Globals.XmlnsNamespace); attribute.Value = ns; return attribute; } public static Exception CreateUnexpectedStateException(XmlNodeType expectedState, XmlReaderDelegator xmlReader) { return XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.GetString(SR.ExpectingState, expectedState), xmlReader); } protected virtual object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) { return dataContract.ReadXmlValue(reader, this); } protected virtual XmlReaderDelegator CreateReaderDelegatorForReader(XmlReader xmlReader) { return new XmlReaderDelegator(xmlReader); } protected virtual bool IsReadingCollectionExtensionData(XmlReaderDelegator xmlReader) { return (attributes.ArraySZSize != -1); } protected virtual bool IsReadingClassExtensionData(XmlReaderDelegator xmlReader) { return false; } } }
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 SinglePageAppAndWebApi.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Runtime.InteropServices.ComTypes { public static class __ITypeInfo2 { public static IObservable<System.IntPtr> GetTypeAttr( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value) { return Observable.Select(ITypeInfo2Value, (ITypeInfo2ValueLambda) => { System.IntPtr ppTypeAttrOutput = default(System.IntPtr); ITypeInfo2ValueLambda.GetTypeAttr(out ppTypeAttrOutput); return ppTypeAttrOutput; }); } public static IObservable<System.Runtime.InteropServices.ComTypes.ITypeComp> GetTypeComp( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value) { return Observable.Select(ITypeInfo2Value, (ITypeInfo2ValueLambda) => { System.Runtime.InteropServices.ComTypes.ITypeComp ppTCompOutput = default(System.Runtime.InteropServices.ComTypes.ITypeComp); ITypeInfo2ValueLambda.GetTypeComp(out ppTCompOutput); return ppTCompOutput; }); } public static IObservable<System.IntPtr> GetFuncDesc( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> index) { return Observable.Zip(ITypeInfo2Value, index, (ITypeInfo2ValueLambda, indexLambda) => { System.IntPtr ppFuncDescOutput = default(System.IntPtr); ITypeInfo2ValueLambda.GetFuncDesc(indexLambda, out ppFuncDescOutput); return ppFuncDescOutput; }); } public static IObservable<System.IntPtr> GetVarDesc( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> index) { return Observable.Zip(ITypeInfo2Value, index, (ITypeInfo2ValueLambda, indexLambda) => { System.IntPtr ppVarDescOutput = default(System.IntPtr); ITypeInfo2ValueLambda.GetVarDesc(indexLambda, out ppVarDescOutput); return ppVarDescOutput; }); } public static IObservable<int> GetNames( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> memid, IObservable<System.String[]> rgBstrNames, IObservable<System.Int32> cMaxNames) { return Observable.Zip(ITypeInfo2Value, memid, rgBstrNames, cMaxNames, (ITypeInfo2ValueLambda, memidLambda, rgBstrNamesLambda, cMaxNamesLambda) => { System.Int32 pcNamesOutput = default(System.Int32); ITypeInfo2ValueLambda.GetNames(memidLambda, rgBstrNamesLambda, cMaxNamesLambda, out pcNamesOutput); return pcNamesOutput; }); } public static IObservable<System.Int32> GetRefTypeOfImplType( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> index) { return Observable.Zip(ITypeInfo2Value, index, (ITypeInfo2ValueLambda, indexLambda) => { System.Int32 hrefOutput = default(System.Int32); ITypeInfo2ValueLambda.GetRefTypeOfImplType(indexLambda, out hrefOutput); return hrefOutput; }); } public static IObservable<System.Runtime.InteropServices.ComTypes.IMPLTYPEFLAGS> GetImplTypeFlags( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> index) { return Observable.Zip(ITypeInfo2Value, index, (ITypeInfo2ValueLambda, indexLambda) => { System.Runtime.InteropServices.ComTypes.IMPLTYPEFLAGS pImplTypeFlagsOutput = default(System.Runtime.InteropServices.ComTypes.IMPLTYPEFLAGS); ITypeInfo2ValueLambda.GetImplTypeFlags(indexLambda, out pImplTypeFlagsOutput); return pImplTypeFlagsOutput; }); } public static IObservable<Unit> GetIDsOfNames( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.String[]> rgszNames, IObservable<System.Int32> cNames, IObservable<System.Int32[]> pMemId) { return ObservableExt.ZipExecute(ITypeInfo2Value, rgszNames, cNames, pMemId, (ITypeInfo2ValueLambda, rgszNamesLambda, cNamesLambda, pMemIdLambda) => ITypeInfo2ValueLambda.GetIDsOfNames(rgszNamesLambda, cNamesLambda, pMemIdLambda)); } public static IObservable<Tuple<System.Runtime.InteropServices.ComTypes.DISPPARAMS, System.Int32>> Invoke( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Object> pvInstance, IObservable<System.Int32> memid, IObservable<System.Int16> wFlags, IObservable<System.Runtime.InteropServices.ComTypes.DISPPARAMS> pDispParams, IObservable<System.IntPtr> pVarResult, IObservable<System.IntPtr> pExcepInfo) { return Observable.Zip(ITypeInfo2Value, pvInstance, memid, wFlags, pDispParams, pVarResult, pExcepInfo, (ITypeInfo2ValueLambda, pvInstanceLambda, memidLambda, wFlagsLambda, pDispParamsLambda, pVarResultLambda, pExcepInfoLambda) => { System.Int32 puArgErrOutput = default(System.Int32); ITypeInfo2ValueLambda.Invoke(pvInstanceLambda, memidLambda, wFlagsLambda, ref pDispParamsLambda, pVarResultLambda, pExcepInfoLambda, out puArgErrOutput); return Tuple.Create(pDispParamsLambda, puArgErrOutput); }); } public static IObservable<Tuple<System.String, System.String, System.Int32, System.String>> GetDocumentation( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> index) { return Observable.Zip(ITypeInfo2Value, index, (ITypeInfo2ValueLambda, indexLambda) => { System.String strNameOutput = default(System.String); System.String strDocStringOutput = default(System.String); System.Int32 dwHelpContextOutput = default(System.Int32); System.String strHelpFileOutput = default(System.String); ITypeInfo2ValueLambda.GetDocumentation(indexLambda, out strNameOutput, out strDocStringOutput, out dwHelpContextOutput, out strHelpFileOutput); return Tuple.Create(strNameOutput, strDocStringOutput, dwHelpContextOutput, strHelpFileOutput); }); } public static IObservable<System.Reactive.Unit> GetDllEntry( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> memid, IObservable<System.Runtime.InteropServices.ComTypes.INVOKEKIND> invKind, IObservable<System.IntPtr> pBstrDllName, IObservable<System.IntPtr> pBstrName, IObservable<System.IntPtr> pwOrdinal) { return ObservableExt.ZipExecute(ITypeInfo2Value, memid, invKind, pBstrDllName, pBstrName, pwOrdinal, (ITypeInfo2ValueLambda, memidLambda, invKindLambda, pBstrDllNameLambda, pBstrNameLambda, pwOrdinalLambda) => ITypeInfo2ValueLambda.GetDllEntry(memidLambda, invKindLambda, pBstrDllNameLambda, pBstrNameLambda, pwOrdinalLambda)); } public static IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo> GetRefTypeInfo( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> hRef) { return Observable.Zip(ITypeInfo2Value, hRef, (ITypeInfo2ValueLambda, hRefLambda) => { System.Runtime.InteropServices.ComTypes.ITypeInfo ppTIOutput = default(System.Runtime.InteropServices.ComTypes.ITypeInfo); ITypeInfo2ValueLambda.GetRefTypeInfo(hRefLambda, out ppTIOutput); return ppTIOutput; }); } public static IObservable<System.IntPtr> AddressOfMember( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> memid, IObservable<System.Runtime.InteropServices.ComTypes.INVOKEKIND> invKind) { return Observable.Zip(ITypeInfo2Value, memid, invKind, (ITypeInfo2ValueLambda, memidLambda, invKindLambda) => { System.IntPtr ppvOutput = default(System.IntPtr); ITypeInfo2ValueLambda.AddressOfMember(memidLambda, invKindLambda, out ppvOutput); return ppvOutput; }); } public static IObservable<Tuple<System.Guid, System.Object>> CreateInstance( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Object> pUnkOuter, IObservable<System.Guid> riid) { return Observable.Zip(ITypeInfo2Value, pUnkOuter, riid, (ITypeInfo2ValueLambda, pUnkOuterLambda, riidLambda) => { System.Object ppvObjOutput = default(System.Object); ITypeInfo2ValueLambda.CreateInstance(pUnkOuterLambda, ref riidLambda, out ppvObjOutput); return Tuple.Create(riidLambda, ppvObjOutput); }); } public static IObservable<System.String> GetMops( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> memid) { return Observable.Zip(ITypeInfo2Value, memid, (ITypeInfo2ValueLambda, memidLambda) => { System.String pBstrMopsOutput = default(System.String); ITypeInfo2ValueLambda.GetMops(memidLambda, out pBstrMopsOutput); return pBstrMopsOutput; }); } public static IObservable<Tuple<System.Runtime.InteropServices.ComTypes.ITypeLib, System.Int32>> GetContainingTypeLib(this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value) { return Observable.Select(ITypeInfo2Value, (ITypeInfo2ValueLambda) => { System.Runtime.InteropServices.ComTypes.ITypeLib ppTLBOutput = default(System.Runtime.InteropServices.ComTypes.ITypeLib); System.Int32 pIndexOutput = default(System.Int32); ITypeInfo2ValueLambda.GetContainingTypeLib(out ppTLBOutput, out pIndexOutput); return Tuple.Create(ppTLBOutput, pIndexOutput); }); } public static IObservable<System.Reactive.Unit> ReleaseTypeAttr( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.IntPtr> pTypeAttr) { return ObservableExt.ZipExecute(ITypeInfo2Value, pTypeAttr, (ITypeInfo2ValueLambda, pTypeAttrLambda) => ITypeInfo2ValueLambda.ReleaseTypeAttr(pTypeAttrLambda)); } public static IObservable<System.Reactive.Unit> ReleaseFuncDesc( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.IntPtr> pFuncDesc) { return ObservableExt.ZipExecute(ITypeInfo2Value, pFuncDesc, (ITypeInfo2ValueLambda, pFuncDescLambda) => ITypeInfo2ValueLambda.ReleaseFuncDesc(pFuncDescLambda)); } public static IObservable<System.Reactive.Unit> ReleaseVarDesc( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.IntPtr> pVarDesc) { return ObservableExt.ZipExecute(ITypeInfo2Value, pVarDesc, (ITypeInfo2ValueLambda, pVarDescLambda) => ITypeInfo2ValueLambda.ReleaseVarDesc(pVarDescLambda)); } public static IObservable<System.Runtime.InteropServices.ComTypes.TYPEKIND> GetTypeKind( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value) { return Observable.Select(ITypeInfo2Value, (ITypeInfo2ValueLambda) => { System.Runtime.InteropServices.ComTypes.TYPEKIND pTypeKindOutput = default(System.Runtime.InteropServices.ComTypes.TYPEKIND); ITypeInfo2ValueLambda.GetTypeKind(out pTypeKindOutput); return pTypeKindOutput; }); } public static IObservable<System.Int32> GetTypeFlags( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value) { return Observable.Select(ITypeInfo2Value, (ITypeInfo2ValueLambda) => { System.Int32 pTypeFlagsOutput = default(System.Int32); ITypeInfo2ValueLambda.GetTypeFlags(out pTypeFlagsOutput); return pTypeFlagsOutput; }); } public static IObservable<System.Int32> GetFuncIndexOfMemId( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> memid, IObservable<System.Runtime.InteropServices.ComTypes.INVOKEKIND> invKind) { return Observable.Zip(ITypeInfo2Value, memid, invKind, (ITypeInfo2ValueLambda, memidLambda, invKindLambda) => { System.Int32 pFuncIndexOutput = default(System.Int32); ITypeInfo2ValueLambda.GetFuncIndexOfMemId(memidLambda, invKindLambda, out pFuncIndexOutput); return pFuncIndexOutput; }); } public static IObservable<System.Int32> GetVarIndexOfMemId( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> memid) { return Observable.Zip(ITypeInfo2Value, memid, (ITypeInfo2ValueLambda, memidLambda) => { System.Int32 pVarIndexOutput = default(System.Int32); ITypeInfo2ValueLambda.GetVarIndexOfMemId(memidLambda, out pVarIndexOutput); return pVarIndexOutput; }); } public static IObservable<Tuple<System.Guid, System.Object>> GetCustData( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Guid> guid) { return Observable.Zip(ITypeInfo2Value, guid, (ITypeInfo2ValueLambda, guidLambda) => { System.Object pVarValOutput = default(System.Object); ITypeInfo2ValueLambda.GetCustData(ref guidLambda, out pVarValOutput); return Tuple.Create(guidLambda, pVarValOutput); }); } public static IObservable<Tuple<System.Guid, System.Object>> GetFuncCustData( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> index, IObservable<System.Guid> guid) { return Observable.Zip(ITypeInfo2Value, index, guid, (ITypeInfo2ValueLambda, indexLambda, guidLambda) => { System.Object pVarValOutput = default(System.Object); ITypeInfo2ValueLambda.GetFuncCustData(indexLambda, ref guidLambda, out pVarValOutput); return Tuple.Create(guidLambda, pVarValOutput); }); } public static IObservable<Tuple<System.Guid, System.Object>> GetParamCustData( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> indexFunc, IObservable<System.Int32> indexParam, IObservable<System.Guid> guid) { return Observable.Zip(ITypeInfo2Value, indexFunc, indexParam, guid, (ITypeInfo2ValueLambda, indexFuncLambda, indexParamLambda, guidLambda) => { System.Object pVarValOutput = default(System.Object); ITypeInfo2ValueLambda.GetParamCustData(indexFuncLambda, indexParamLambda, ref guidLambda, out pVarValOutput); return Tuple.Create(guidLambda, pVarValOutput); }); } public static IObservable<Tuple<System.Guid, System.Object>> GetVarCustData( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> index, IObservable<System.Guid> guid) { return Observable.Zip(ITypeInfo2Value, index, guid, (ITypeInfo2ValueLambda, indexLambda, guidLambda) => { System.Object pVarValOutput = default(System.Object); ITypeInfo2ValueLambda.GetVarCustData(indexLambda, ref guidLambda, out pVarValOutput); return Tuple.Create(guidLambda, pVarValOutput); }); } public static IObservable<Tuple<System.Guid, System.Object>> GetImplTypeCustData( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> index, IObservable<System.Guid> guid) { return Observable.Zip(ITypeInfo2Value, index, guid, (ITypeInfo2ValueLambda, indexLambda, guidLambda) => { System.Object pVarValOutput = default(System.Object); ITypeInfo2ValueLambda.GetImplTypeCustData(indexLambda, ref guidLambda, out pVarValOutput); return Tuple.Create(guidLambda, pVarValOutput); }); } public static IObservable<Tuple<System.String, System.Int32, System.String>> GetDocumentation2( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> memid) { return Observable.Zip(ITypeInfo2Value, memid, (ITypeInfo2ValueLambda, memidLambda) => { System.String pbstrHelpStringOutput = default(System.String); System.Int32 pdwHelpStringContextOutput = default(System.Int32); System.String pbstrHelpStringDllOutput = default(System.String); ITypeInfo2ValueLambda.GetDocumentation2(memidLambda, out pbstrHelpStringOutput, out pdwHelpStringContextOutput, out pbstrHelpStringDllOutput); return Tuple.Create(pbstrHelpStringOutput, pdwHelpStringContextOutput, pbstrHelpStringDllOutput); }); } public static IObservable<System.Reactive.Unit> GetAllCustData( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.IntPtr> pCustData) { return ObservableExt.ZipExecute(ITypeInfo2Value, pCustData, (ITypeInfo2ValueLambda, pCustDataLambda) => ITypeInfo2ValueLambda.GetAllCustData(pCustDataLambda)); } public static IObservable<System.Reactive.Unit> GetAllFuncCustData( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> index, IObservable<System.IntPtr> pCustData) { return ObservableExt.ZipExecute(ITypeInfo2Value, index, pCustData, (ITypeInfo2ValueLambda, indexLambda, pCustDataLambda) => ITypeInfo2ValueLambda.GetAllFuncCustData(indexLambda, pCustDataLambda)); } public static IObservable<System.Reactive.Unit> GetAllParamCustData( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> indexFunc, IObservable<System.Int32> indexParam, IObservable<System.IntPtr> pCustData) { return ObservableExt.ZipExecute(ITypeInfo2Value, indexFunc, indexParam, pCustData, (ITypeInfo2ValueLambda, indexFuncLambda, indexParamLambda, pCustDataLambda) => ITypeInfo2ValueLambda.GetAllParamCustData(indexFuncLambda, indexParamLambda, pCustDataLambda)); } public static IObservable<System.Reactive.Unit> GetAllVarCustData( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> index, IObservable<System.IntPtr> pCustData) { return ObservableExt.ZipExecute(ITypeInfo2Value, index, pCustData, (ITypeInfo2ValueLambda, indexLambda, pCustDataLambda) => ITypeInfo2ValueLambda.GetAllVarCustData(indexLambda, pCustDataLambda)); } public static IObservable<System.Reactive.Unit> GetAllImplTypeCustData( this IObservable<System.Runtime.InteropServices.ComTypes.ITypeInfo2> ITypeInfo2Value, IObservable<System.Int32> index, IObservable<System.IntPtr> pCustData) { return ObservableExt.ZipExecute(ITypeInfo2Value, index, pCustData, (ITypeInfo2ValueLambda, indexLambda, pCustDataLambda) => ITypeInfo2ValueLambda.GetAllImplTypeCustData(indexLambda, pCustDataLambda)); } } }
// dnlib: See LICENSE.txt for more info // See coreclr/src/vm/siginfo.cpp using System; using System.Diagnostics; namespace dnlib.DotNet { /// <summary> /// <c>System.Runtime.InteropServices.TypeIdentifierAttribute</c> helper code used by <see cref="SigComparer"/> /// </summary> static class TIAHelper { readonly struct Info : IEquatable<Info> { public readonly UTF8String Scope; public readonly UTF8String Identifier; public Info(UTF8String scope, UTF8String identifier) { Scope = scope; Identifier = identifier; } public bool Equals(Info other) => stricmp(Scope, other.Scope) && UTF8String.Equals(Identifier, other.Identifier); static bool stricmp(UTF8String a, UTF8String b) { var da = a?.Data; var db = b?.Data; if (da == db) return true; if (da is null || db is null) return false; if (da.Length != db.Length) return false; for (int i = 0; i < da.Length; i++) { byte ba = da[i], bb = db[i]; if ((byte)'A' <= ba && ba <= (byte)'Z') ba = (byte)(ba - 'A' + 'a'); if ((byte)'A' <= bb && bb <= (byte)'Z') bb = (byte)(bb - 'A' + 'a'); if (ba != bb) return false; } return true; } } static Info? GetInfo(TypeDef td) { if (td is null) return null; if (td.IsWindowsRuntime) return null; UTF8String scope = null, identifier = null; var tia = td.CustomAttributes.Find("System.Runtime.InteropServices.TypeIdentifierAttribute"); if (tia is not null) { if (tia.ConstructorArguments.Count >= 2) { if (tia.ConstructorArguments[0].Type.GetElementType() != ElementType.String) return null; if (tia.ConstructorArguments[1].Type.GetElementType() != ElementType.String) return null; scope = tia.ConstructorArguments[0].Value as UTF8String ?? tia.ConstructorArguments[0].Value as string; identifier = tia.ConstructorArguments[1].Value as UTF8String ?? tia.ConstructorArguments[1].Value as string; } } else { var asm = td.Module?.Assembly; if (asm is null) return null; bool isTypeLib = asm.CustomAttributes.IsDefined("System.Runtime.InteropServices.ImportedFromTypeLibAttribute") || asm.CustomAttributes.IsDefined("System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute"); if (!isTypeLib) return null; } if (UTF8String.IsNull(identifier)) { CustomAttribute gca; if (td.IsInterface && td.IsImport) gca = td.CustomAttributes.Find("System.Runtime.InteropServices.GuidAttribute"); else { var asm = td.Module?.Assembly; if (asm is null) return null; gca = asm.CustomAttributes.Find("System.Runtime.InteropServices.GuidAttribute"); } if (gca is null) return null; if (gca.ConstructorArguments.Count < 1) return null; if (gca.ConstructorArguments[0].Type.GetElementType() != ElementType.String) return null; scope = gca.ConstructorArguments[0].Value as UTF8String ?? gca.ConstructorArguments[0].Value as string; var ns = td.Namespace; var name = td.Name; if (UTF8String.IsNullOrEmpty(ns)) identifier = name; else if (UTF8String.IsNullOrEmpty(name)) identifier = new UTF8String(Concat(ns.Data, (byte)'.', Array2.Empty<byte>())); else identifier = new UTF8String(Concat(ns.Data, (byte)'.', name.Data)); } return new Info(scope, identifier); } static byte[] Concat(byte[] a, byte b, byte[] c) { var data = new byte[a.Length + 1 + c.Length]; for (int i = 0; i < a.Length; i++) data[i] = a[i]; data[a.Length] = b; for (int i = 0, j = a.Length + 1; i < c.Length; i++, j++) data[j] = c[i]; return data; } internal static bool IsTypeDefEquivalent(TypeDef td) => GetInfo(td) is not null && CheckEquivalent(td); static bool CheckEquivalent(TypeDef td) { Debug.Assert(td is not null); for (int i = 0; td is not null && i < 1000; i++) { if (i != 0) { var info = GetInfo(td); if (info is null) return false; } bool f; if (td.IsInterface) f = td.IsImport || td.CustomAttributes.IsDefined("System.Runtime.InteropServices.ComEventInterfaceAttribute"); else f = td.IsValueType || td.IsDelegate; if (!f) return false; if (td.GenericParameters.Count > 0) return false; var declType = td.DeclaringType; if (declType is null) return td.IsPublic; if (!td.IsNestedPublic) return false; td = declType; } return false; } public static bool Equivalent(TypeDef td1, TypeDef td2) { var info1 = GetInfo(td1); if (info1 is null) return false; var info2 = GetInfo(td2); if (info2 is null) return false; if (!CheckEquivalent(td1) || !CheckEquivalent(td2)) return false; if (!info1.Value.Equals(info2.Value)) return false; // Caller has already compared names of the types and any declaring types for (int i = 0; i < 1000; i++) { if (td1.IsInterface) { if (!td2.IsInterface) return false; } else { var bt1 = td1.BaseType; var bt2 = td2.BaseType; if (bt1 is null || bt2 is null) return false; if (td1.IsDelegate) { if (!td2.IsDelegate) return false; if (!DelegateEquals(td1, td2)) return false; } else if (td1.IsValueType) { if (td1.IsEnum != td2.IsEnum) return false; if (!td2.IsValueType) return false; if (!ValueTypeEquals(td1, td2, td1.IsEnum)) return false; } else return false; } td1 = td1.DeclaringType; td2 = td2.DeclaringType; if (td1 is null && td2 is null) break; if (td1 is null || td2 is null) return false; } return true; } static bool DelegateEquals(TypeDef td1, TypeDef td2) { var invoke1 = td1.FindMethod(InvokeString); var invoke2 = td2.FindMethod(InvokeString); if (invoke1 is null || invoke2 is null) return false; //TODO: Compare method signatures. Prevent infinite recursion... return true; } static readonly UTF8String InvokeString = new UTF8String("Invoke"); static bool ValueTypeEquals(TypeDef td1, TypeDef td2, bool isEnum) { if (td1.Methods.Count != 0 || td2.Methods.Count != 0) return false; //TODO: Compare the fields. Prevent infinite recursion... return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Globalization; using System.Threading; namespace System.Text { // This class overrides Encoding with the things we need for our NLS Encodings // // All of the GetBytes/Chars GetByte/CharCount methods are just wrappers for the pointer // plus decoder/encoder method that is our real workhorse. Note that this is an internal // class, so our public classes cannot derive from this class. Because of this, all of the // GetBytes/Chars GetByte/CharCount wrapper methods are duplicated in all of our public // encodings, which currently include: // // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, & UnicodeEncoding // // So if you change the wrappers in this class, you must change the wrappers in the other classes // as well because they should have the same behavior. internal abstract class EncodingNLS : Encoding { protected EncodingNLS(int codePage) : base(codePage) { } // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(String s) { // Validate input if (s==null) throw new ArgumentNullException("s"); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException("chars", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = s) fixed (byte* pBytes = &bytes[0]) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty arrays if (bytes.Length == 0) bytes = new byte[1]; fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0]) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays if (count == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty arrays if (chars.Length == 0) chars = new char[1]; fixed (byte* pBytes = bytes) fixed (char* pChars = &chars[0]) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe String GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer if (count == 0) return String.Empty; fixed (byte* pBytes = bytes) return String.CreateStringFromEncoding( pBytes + index, count, this); } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } } }
using System; using UnityEngine; namespace Stratus.AI { /// <summary> /// In artificial intelligence, an intelligent agent (IA) is an autonomous entity /// which observes through sensors and acts upon an environment using actuators /// and directs its activity towards achieving goals. /// </summary> public partial class StratusAgent : StratusManagedBehaviour, IStratusDebuggable { //------------------------------------------------------------------------/ // Declarations //------------------------------------------------------------------------/ /// <summary> /// The agent's base states /// </summary> public enum State { /// <summary> /// The agent is idle, performing no actions /// </summary> Idle, /// <summary> /// The agent is moving towards its target destination /// </summary> Moving, /// <summary> /// The agent is performing an action /// </summary> Action } public enum Control { Manual, Automatic } /// <summary> /// Base class for all status events /// </summary> public abstract class BaseEvent : StratusEvent { protected BaseEvent(StratusAgent agent) { this.agent = agent; } public StratusAgent agent { get; set; } } /// <summary> /// Signals that the agent has spawned /// </summary> public class SpawnEvent : BaseEvent { public SpawnEvent(StratusAgent agent) : base(agent) { } } /// <summary> /// Signals the agent to start considering its next action /// </summary> public class AssessEvent : BaseEvent { public AssessEvent(StratusAgent agent) : base(agent) { } } /// <summary> /// Signals to the agent that it should be disabled for a set amount of time /// </summary> public class DisableEvent : StratusEvent { public float duration = 0f; public DisableEvent(float duration) { this.duration = duration; } } /// <summary> /// Signals that the agent should stop its current action /// </summary> public class StopEvent : StratusEvent { } //------------------------------------------------------------------------/ // Fields: Public //------------------------------------------------------------------------/ [Header("Status")] /// <summary> /// How the agent is currently controlled /// </summary> public Control control = Control.Automatic; /// <summary> /// The collection of behaviors to run on this agent (a behavior system such as a BT, Planner, etc) /// </summary> public StratusBehaviorSystem behavior; /// <summary> /// Whether this agent is active /// </summary> public bool active = true; /// <summary> /// Whether we are debugging the agent /// </summary> public bool debug = false; //------------------------------------------------------------------------/ // Properties: Public //------------------------------------------------------------------------/ /// <summary> /// Whether this agent is being driven by a behaviour system /// </summary> public bool isAutomatic => this.control == Control.Automatic; /// <summary> /// The current state of this agent /// </summary> public State currentState { get; protected set; } /// <summary> /// If there's a behavior set for this agent /// </summary> public bool hasBehavior => this.behavior != null; /// <summary> /// The blackboard this agent is using /// </summary> public StratusBlackboard blackboard => this.behavior.blackboard; //------------------------------------------------------------------------/ // Interface //------------------------------------------------------------------------/ protected virtual void OnAgentAwake() { } protected virtual void OnAgentDestroy() { } protected virtual void OnAgentStart() { } protected virtual void OnAgentUpdate() { } protected virtual void OnAgentStop() { } protected virtual void OnTargetAgent(StratusAgent agent) { } protected virtual void OnAgentPause() { } protected virtual void OnAgentResume() { } //------------------------------------------------------------------------/ // Events //------------------------------------------------------------------------/ public event Action onPause; public event Action onResume; //------------------------------------------------------------------------/ // Messages //------------------------------------------------------------------------/ protected override void OnManagedAwake() { this.Subscribe(); this.OnAgentAwake(); StratusScene.Dispatch<SpawnEvent>(new SpawnEvent(this)); } protected override void OnManagedStart() { this.OnAgentStart(); this.currentState = State.Idle; if (this.hasBehavior) { this.behavior = StratusBehaviorSystem.InitializeSystemInstance(this, this.behavior); } } protected override void OnManagedDestroy() { this.OnAgentDestroy(); } protected override void OnManagedUpdate() { if (!this.active) { return; } this.OnAgentUpdate(); if (this.hasBehavior && isAutomatic) { this.behavior.UpdateSystem(); } } void IStratusDebuggable.Toggle(bool debug) { this.debug = debug; } //------------------------------------------------------------------------/ // Events //------------------------------------------------------------------------/ /// <summary> /// Subscribes to events /// </summary> protected virtual void Subscribe() { this.gameObject.Connect<DisableEvent>(this.OnDisableEvent); this.gameObject.Connect<StopEvent>(this.OnStopEvent); } private void OnDisableEvent(DisableEvent e) { this.Disable(e.duration); } private void OnStopEvent(StopEvent e) { this.Stop(); } //------------------------------------------------------------------------/ // Methods: Public //------------------------------------------------------------------------/ /// <summary> /// Targets the given agent, performing the default action on it /// </summary> /// <param name="agent"></param> public void Target(StratusAgent agent) { this.OnTargetAgent(agent); } /// <summary> /// Stops all of the agent's current actions /// </summary> public void Stop() { if (this.debug) { StratusDebug.Log("The agent has been stopped.", this); } this.OnAgentStop(); this.StopAllCoroutines(); } /// <summary> /// Pauses this agent, stopping its AI routines and navigation /// </summary> public void Pause() { if (this.debug) { StratusDebug.Log("Paused", this); } this.active = false; this.OnAgentPause(); } /// <summary> /// Resumes the AI routines and navigation for this agent /// </summary> public void Resume() { if (this.debug) { StratusDebug.Log("Resumed", this); } this.active = true; this.OnAgentResume(); } /// <summary> /// Disables this agent's behaviour temporarily /// </summary> /// <param name="duration"></param> public void Disable(float duration) { this.active = false; this.Stop(); StratusActionSet seq = StratusActions.Sequence(this); StratusActions.Call(seq, () => { this.active = true; }); } } }
using UnityEngine; using System.Collections.Generic; namespace UnityEngine.UI { [AddComponentMenu("Layout/Grid Layout Group", 152)] public class GridLayoutGroup : LayoutGroup { public enum Corner { UpperLeft = 0, UpperRight = 1, LowerLeft = 2, LowerRight = 3 } public enum Axis { Horizontal = 0, Vertical = 1 } public enum Constraint { Flexible = 0, FixedColumnCount = 1, FixedRowCount = 2 } [SerializeField] protected Corner m_StartCorner = Corner.UpperLeft; public Corner startCorner { get { return m_StartCorner; } set { SetProperty(ref m_StartCorner, value); } } [SerializeField] protected Axis m_StartAxis = Axis.Horizontal; public Axis startAxis { get { return m_StartAxis; } set { SetProperty(ref m_StartAxis, value); } } [SerializeField] protected Vector2 m_CellSize = new Vector2(100, 100); public Vector2 cellSize { get { return m_CellSize; } set { SetProperty(ref m_CellSize, value); } } [SerializeField] protected Vector2 m_Spacing = Vector2.zero; public Vector2 spacing { get { return m_Spacing; } set { SetProperty(ref m_Spacing, value); } } [SerializeField] protected Constraint m_Constraint = Constraint.Flexible; public Constraint constraint { get { return m_Constraint; } set { SetProperty(ref m_Constraint, value); } } [SerializeField] protected int m_ConstraintCount = 2; public int constraintCount { get { return m_ConstraintCount; } set { SetProperty(ref m_ConstraintCount, Mathf.Max(1, value)); } } protected GridLayoutGroup() {} #if UNITY_EDITOR protected override void OnValidate() { base.OnValidate(); constraintCount = constraintCount; } #endif public override void CalculateLayoutInputHorizontal() { base.CalculateLayoutInputHorizontal(); int minColumns = 0; int preferredColumns = 0; if (m_Constraint == Constraint.FixedColumnCount) { minColumns = preferredColumns = m_ConstraintCount; } else if (m_Constraint == Constraint.FixedRowCount) { minColumns = preferredColumns = Mathf.CeilToInt(rectChildren.Count / (float)m_ConstraintCount - 0.001f); } else { minColumns = 1; preferredColumns = Mathf.CeilToInt(Mathf.Sqrt(rectChildren.Count)); } SetLayoutInputForAxis( padding.horizontal + (cellSize.x + spacing.x) * minColumns - spacing.x, padding.horizontal + (cellSize.x + spacing.x) * preferredColumns - spacing.x, -1, 0); } public override void CalculateLayoutInputVertical() { int minRows = 0; if (m_Constraint == Constraint.FixedColumnCount) { minRows = Mathf.CeilToInt(rectChildren.Count / (float)m_ConstraintCount - 0.001f); } else if (m_Constraint == Constraint.FixedRowCount) { minRows = m_ConstraintCount; } else { float width = rectTransform.rect.size.x; int cellCountX = Mathf.Max(1, Mathf.FloorToInt((width - padding.horizontal + spacing.x + 0.001f) / (cellSize.x + spacing.x))); minRows = Mathf.CeilToInt(rectChildren.Count / (float)cellCountX); } float minSpace = padding.vertical + (cellSize.y + spacing.y) * minRows - spacing.y; SetLayoutInputForAxis(minSpace, minSpace, -1, 1); } public override void SetLayoutHorizontal() { SetCellsAlongAxis(0); } public override void SetLayoutVertical() { SetCellsAlongAxis(1); } private void SetCellsAlongAxis(int axis) { // Normally a Layout Controller should only set horizontal values when invoked for the horizontal axis // and only vertical values when invoked for the vertical axis. // However, in this case we set both the horizontal and vertical position when invoked for the vertical axis. // Since we only set the horizontal position and not the size, it shouldn't affect children's layout, // and thus shouldn't break the rule that all horizontal layout must be calculated before all vertical layout. if (axis == 0) { // Only set the sizes when invoked for horizontal axis, not the positions. for (int i = 0; i < rectChildren.Count; i++) { RectTransform rect = rectChildren[i]; m_Tracker.Add(this, rect, DrivenTransformProperties.Anchors | DrivenTransformProperties.AnchoredPosition | DrivenTransformProperties.SizeDelta); rect.anchorMin = Vector2.up; rect.anchorMax = Vector2.up; rect.sizeDelta = cellSize; } return; } float width = rectTransform.rect.size.x; float height = rectTransform.rect.size.y; int cellCountX = 1; int cellCountY = 1; if (m_Constraint == Constraint.FixedColumnCount) { cellCountX = m_ConstraintCount; cellCountY = Mathf.CeilToInt(rectChildren.Count / (float)cellCountX - 0.001f); } else if (m_Constraint == Constraint.FixedRowCount) { cellCountY = m_ConstraintCount; cellCountX = Mathf.CeilToInt(rectChildren.Count / (float)cellCountY - 0.001f); } else { if (cellSize.x + spacing.x <= 0) cellCountX = int.MaxValue; else cellCountX = Mathf.Max(1, Mathf.FloorToInt((width - padding.horizontal + spacing.x + 0.001f) / (cellSize.x + spacing.x))); if (cellSize.y + spacing.y <= 0) cellCountY = int.MaxValue; else cellCountY = Mathf.Max(1, Mathf.FloorToInt((height - padding.vertical + spacing.y + 0.001f) / (cellSize.y + spacing.y))); } int cornerX = (int)startCorner % 2; int cornerY = (int)startCorner / 2; int cellsPerMainAxis, actualCellCountX, actualCellCountY; if (startAxis == Axis.Horizontal) { cellsPerMainAxis = cellCountX; actualCellCountX = Mathf.Clamp(cellCountX, 1, rectChildren.Count); actualCellCountY = Mathf.Clamp(cellCountY, 1, Mathf.CeilToInt(rectChildren.Count / (float)cellsPerMainAxis)); } else { cellsPerMainAxis = cellCountY; actualCellCountY = Mathf.Clamp(cellCountY, 1, rectChildren.Count); actualCellCountX = Mathf.Clamp(cellCountX, 1, Mathf.CeilToInt(rectChildren.Count / (float)cellsPerMainAxis)); } Vector2 requiredSpace = new Vector2( actualCellCountX * cellSize.x + (actualCellCountX - 1) * spacing.x, actualCellCountY * cellSize.y + (actualCellCountY - 1) * spacing.y ); Vector2 startOffset = new Vector2( GetStartOffset(0, requiredSpace.x), GetStartOffset(1, requiredSpace.y) ); for (int i = 0; i < rectChildren.Count; i++) { int positionX; int positionY; if (startAxis == Axis.Horizontal) { positionX = i % cellsPerMainAxis; positionY = i / cellsPerMainAxis; } else { positionX = i / cellsPerMainAxis; positionY = i % cellsPerMainAxis; } if (cornerX == 1) positionX = actualCellCountX - 1 - positionX; if (cornerY == 1) positionY = actualCellCountY - 1 - positionY; SetChildAlongAxis(rectChildren[i], 0, startOffset.x + (cellSize[0] + spacing[0]) * positionX, cellSize[0]); SetChildAlongAxis(rectChildren[i], 1, startOffset.y + (cellSize[1] + spacing[1]) * positionY, cellSize[1]); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using BTDB.FieldHandler; using BTDB.IL; using BTDB.ODBLayer; using BTDB.StreamLayer; namespace BTDB.EventStoreLayer { class EnumTypeDescriptor : ITypeDescriptor, IPersistTypeDescriptor { readonly TypeSerializers _typeSerializers; Type _type; readonly string _name; readonly bool _signed; readonly bool _flags; readonly List<KeyValuePair<string, ulong>> _pairs; public EnumTypeDescriptor(TypeSerializers typeSerializers, Type type) { _typeSerializers = typeSerializers; _type = type; _name = typeSerializers.TypeToName(type); _signed = IsSignedEnum(type); _flags = IsFlagsEnum(type); var undertype = type.GetEnumUnderlyingType(); var enumValues = type.GetEnumValues(); IEnumerable<ulong> enumValuesUlongs; if (undertype == typeof(int)) enumValuesUlongs = enumValues.Cast<int>().Select(i => (ulong)i); else if (undertype == typeof(uint)) enumValuesUlongs = enumValues.Cast<uint>().Select(i => (ulong)i); else if (undertype == typeof(sbyte)) enumValuesUlongs = enumValues.Cast<sbyte>().Select(i => (ulong)i); else if (undertype == typeof(byte)) enumValuesUlongs = enumValues.Cast<byte>().Select(i => (ulong)i); else if (undertype == typeof(short)) enumValuesUlongs = enumValues.Cast<short>().Select(i => (ulong)i); else if (undertype == typeof(ushort)) enumValuesUlongs = enumValues.Cast<ushort>().Select(i => (ulong)i); else if (undertype == typeof(long)) enumValuesUlongs = enumValues.Cast<long>().Select(i => (ulong)i); else enumValuesUlongs = enumValues.Cast<ulong>(); _pairs = type.GetEnumNames().Zip(enumValuesUlongs.ToArray(), (s, v) => new KeyValuePair<string, ulong>(s, v)).ToList(); } public EnumTypeDescriptor(TypeSerializers typeSerializers, AbstractBufferedReader reader) { _typeSerializers = typeSerializers; _name = reader.ReadString(); var header = reader.ReadVUInt32(); _signed = (header & 1) != 0; _flags = (header & 2) != 0; var count = header >> 2; _pairs = new List<KeyValuePair<string, ulong>>((int)count); for (int i = 0; i < count; i++) { _pairs.Add(_signed ? new KeyValuePair<string, ulong>(reader.ReadString(), (ulong)reader.ReadVInt64()) : new KeyValuePair<string, ulong>(reader.ReadString(), reader.ReadVUInt64())); } } static bool IsSignedEnum(Type enumType) { return SignedFieldHandler.IsCompatibleWith(enumType.GetEnumUnderlyingType()); } static bool IsFlagsEnum(Type type) { return type.GetCustomAttributes(typeof(FlagsAttribute), false).Length != 0; } public bool Equals(ITypeDescriptor other) { return Equals(other, new HashSet<ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance)); } public string Name { get { return _name; } } public void FinishBuildFromType(ITypeDescriptorFactory factory) { } public void BuildHumanReadableFullName(StringBuilder text, HashSet<ITypeDescriptor> stack, uint indent) { if (stack.Contains(this)) { text.Append(Name); return; } stack.Add(this); text.AppendLine(Name); AppendIndent(text, indent); text.Append("enum "); if (_flags) text.Append("flags "); text.AppendLine("{"); foreach (var pair in _pairs) { AppendIndent(text, indent + 1); text.Append(pair.Key); text.Append(" = "); if (_signed) text.Append((long)pair.Value); else text.Append(pair.Value); text.AppendLine(); } AppendIndent(text, indent); text.Append("}"); } static void AppendIndent(StringBuilder text, uint indent) { text.Append(' ', (int)(indent * 4)); } public bool Equals(ITypeDescriptor other, HashSet<ITypeDescriptor> stack) { var o = other as EnumTypeDescriptor; if (o == null) return false; if (Name != o.Name) return false; if (_flags != o._flags) return false; if (_signed != o._signed) return false; return _pairs.SequenceEqual(o._pairs); } public Type GetPreferedType() { return _type; } public class DynamicEnum : IKnowDescriptor { readonly ITypeDescriptor _descriptor; readonly ulong _value; public DynamicEnum(long value, ITypeDescriptor descriptor) { _value = (ulong)value; _descriptor = descriptor; } public DynamicEnum(ulong value, ITypeDescriptor descriptor) { _value = value; _descriptor = descriptor; } public ITypeDescriptor GetDescriptor() { return _descriptor; } public override string ToString() { return ((EnumTypeDescriptor)_descriptor).UlongValueToString(_value); } public override int GetHashCode() { return _value.GetHashCode(); } public override bool Equals(object obj) { if (obj == null) return false; var objMe = obj as DynamicEnum; if (objMe != null) { if (objMe._descriptor != _descriptor) return false; return objMe._value == _value; } if (!obj.GetType().IsEnum) return false; var myDescriptor = ((EnumTypeDescriptor)_descriptor); var otherDescriptor = myDescriptor._typeSerializers.DescriptorOf(obj.GetType()); if (!myDescriptor.Equals(otherDescriptor)) return false; if (myDescriptor._signed) { return _value == (ulong)Convert.ToInt64(obj, CultureInfo.InvariantCulture); } return _value == Convert.ToUInt64(obj, CultureInfo.InvariantCulture); } } string UlongValueToString(ulong value) { if (_flags) { return UlongValueToStringFlags(value); } var index = _pairs.FindIndex(p => p.Value == value); if (index < 0) return UlongValueToStringAsNumber(value); return _pairs[index].Key; } string UlongValueToStringAsNumber(ulong value) { if (_signed) { return ((long)value).ToString(CultureInfo.InvariantCulture); } return value.ToString(CultureInfo.InvariantCulture); } string UlongValueToStringFlags(ulong value) { var workingValue = value; var index = _pairs.Count - 1; var stringBuilder = new StringBuilder(); var isFirstText = true; while (index >= 0) { var currentValue = _pairs[index].Value; if ((index == 0) && (currentValue == 0L)) { break; } if ((workingValue & currentValue) == currentValue) { workingValue -= currentValue; if (!isFirstText) { stringBuilder.Insert(0, ", "); } stringBuilder.Insert(0, _pairs[index].Key); isFirstText = false; } index--; } if (workingValue != 0L) { return UlongValueToStringAsNumber(value); } if (value != 0) { return stringBuilder.ToString(); } if ((_pairs.Count > 0) && (_pairs[0].Value == 0)) { return _pairs[0].Key; } return "0"; } public bool AnyOpNeedsCtx() { return false; } public void GenerateLoad(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx, Action<IILGen> pushDescriptor, Type targetType) { pushReader(ilGenerator); Type typeRead; if (_signed) { ilGenerator.Call(() => default(AbstractBufferedReader).ReadVInt64()); typeRead = typeof(long); } else { ilGenerator.Call(() => default(AbstractBufferedReader).ReadVUInt64()); typeRead = typeof(ulong); } if (targetType == typeof(object)) { ilGenerator.Do(pushDescriptor); if (_signed) { ilGenerator.Newobj(() => new DynamicEnum(0L, null)); } else { ilGenerator.Newobj(() => new DynamicEnum(0UL, null)); } ilGenerator.Castclass(typeof(object)); return; } new DefaultTypeConvertorGenerator().GenerateConversion(typeRead, targetType.GetEnumUnderlyingType())(ilGenerator); } public ITypeNewDescriptorGenerator BuildNewDescriptorGenerator() { return null; } public ITypeDescriptor NestedType(int index) { return null; } public void MapNestedTypes(Func<ITypeDescriptor, ITypeDescriptor> map) { } public bool Sealed { get { return true; } } public bool StoredInline { get { return true; } } public void ClearMappingToType() { _type = null; } public bool ContainsField(string name) { return false; } public void Persist(AbstractBufferedWriter writer, Action<AbstractBufferedWriter, ITypeDescriptor> nestedDescriptorPersistor) { writer.WriteString(_name); writer.WriteVUInt32((_signed ? 1u : 0) + (_flags ? 2u : 0) + 4u * (uint)_pairs.Count); foreach (var pair in _pairs) { writer.WriteString(pair.Key); if (_signed) writer.WriteVInt64((long)pair.Value); else writer.WriteVUInt64(pair.Value); } } public void GenerateSave(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushCtx, Action<IILGen> pushValue, Type valueType) { pushWriter(ilGenerator); pushValue(ilGenerator); if (_signed) { ilGenerator .ConvI8() .Call(() => default(AbstractBufferedWriter).WriteVInt64(0)); } else { ilGenerator .ConvU8() .Call(() => default(AbstractBufferedWriter).WriteVUInt64(0)); } } public void GenerateSkip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx) { pushReader(ilGenerator); if (_signed) { ilGenerator.Call(() => default(AbstractBufferedReader).SkipVInt64()); } else { ilGenerator.Call(() => default(AbstractBufferedReader).SkipVUInt64()); } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Totem.Runtime; using Totem.Timeline.Area; namespace Totem.Timeline.Runtime { /// <summary> /// The scope of a topic's activity on the timeline /// </summary> public class TopicScope : FlowScope<Topic> { readonly IServiceProvider _services; public TopicScope(FlowKey key, ITimelineDb db, IServiceProvider services) : base(key, db) { _services = services; } new TopicObservation Observation => (TopicObservation) base.Observation; bool CanCallWhen => Observation.HasWhen(Point.Scheduled); bool CanCallGiven => Observation.HasGiven(Point.Scheduled); bool GivenWasNotImmediate => Point.Topic != Key; protected override async Task ObservePoint() { if(CanCallWhen) { LogPoint(); if(CanCallGiven && GivenWasNotImmediate) { CallGivenBeforeWhen(); } await CallWhenAndWrite(); } else { if(GivenWasNotImmediate) { LogPoint(); CallGivenWithoutWhen(); await WriteCheckpoint(); } } } void LogPoint() => LogPoint(Point); void LogPoint(TimelinePoint point) => Log.Trace("[timeline] #{Position} => {Key}", point.Position.ToInt64(), Key); void CallGivenBeforeWhen() => Flow.Context.CallGiven(new FlowCall.Given(Point, Observation)); void CallGivenWithoutWhen() => Flow.Context.CallGiven(new FlowCall.Given(Point, Observation), advanceCheckpoint: true); // // When // async Task CallWhenAndWrite() { var newEvents = await CallWhen(); if(newEvents.Count == 0) { await WriteCheckpoint(); } else { var newPosition = await Db.WriteNewEvents(Point.Position, Key, newEvents); var immediateGivens = GetImmediateGivens(newEvents, newPosition).ToMany(); if(immediateGivens.Count == 0) { await WriteCheckpointAfterNewEvents(Point); } else { await CallImmediateGivensAndWrite(immediateGivens); } } } async Task<Many<Event>> CallWhen() { using(var callScope = _services.CreateScope()) { var call = new FlowCall.When(Point, Observation, callScope.ServiceProvider, State.CancellationToken); await Flow.Context.CallWhen(call); return call.GetNewEvents(); } } IEnumerable<FlowCall.Given> GetImmediateGivens(Many<Event> newEvents, TimelinePosition newPosition) { foreach(var e in newEvents) { if(TryGetImmediateGiven(e, newPosition, out var given)) { yield return given; } newPosition = newPosition.Next(); } } bool TryGetImmediateGiven(Event e, TimelinePosition position, out FlowCall.Given given) { given = null; if(TryGetObservation(e, out var observation)) { var routes = observation.EventType.GetRoutes(e).ToMany(); if(routes.Contains(Key)) { var point = new TimelinePoint( position, Point.Position, observation.EventType, e.When, Event.Traits.WhenOccurs.Get(e), Event.Traits.EventId.Get(e), Event.Traits.CommandId.Get(e), Event.Traits.UserId.Get(e), Key, routes, () => e); given = new FlowCall.Given(point, observation); } } return given != null; } bool TryGetObservation(Event e, out FlowObservation observation) => Key.Type.Observations.TryGet(e, out observation) && observation.HasGiven(Event.IsScheduled(e)); // // After writing new events // async Task WriteCheckpointAfterNewEvents(TimelinePoint point) { try { await WriteCheckpoint(); } catch(Exception error) { await StopAfterNewEvents(point, error); } } async Task CallImmediateGivensAndWrite(Many<FlowCall.Given> givens) { var latestPoint = Point; var advanceCheckpoint = true; try { foreach(var given in givens) { latestPoint = given.Point; LogPoint(latestPoint); var observation = (TopicObservation) given.Observation; var hasWhen = observation.HasWhen(latestPoint.Scheduled); advanceCheckpoint = advanceCheckpoint && !hasWhen; Flow.Context.CallGiven(given, advanceCheckpoint); } } catch(Exception error) { await StopAfterNewEvents(latestPoint, error); return; } await WriteCheckpointAfterNewEvents(latestPoint); } async Task StopAfterNewEvents(TimelinePoint latestPoint, Exception error) { try { Flow.Context.SetError(latestPoint.Position, error.ToString()); await Db.WriteCheckpoint(Flow, latestPoint); Flow.Context.SetNotNew(); CompleteTask(error); } catch(Exception writeError) { CompleteTask(new Exception( $"Topic {Key} added events to the timeline, but failed to save its checkpoint. This should be vanishingly rare and would be surprising if it occurred. This can be reconciled when resuming via each new point's topic key, but that is not in place yet, so the flow is stopped. Manual resolution is required.", new AggregateException(error, writeError))); } } } }
#region File Information //----------------------------------------------------------------------------- // SoundAndMusicSampleGame.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; #endregion Using Statements namespace SoundAndMusicSample { /// <summary> /// This is the main type for your game /// </summary> public class SoundAndMusicSampleGame : Microsoft.Xna.Framework.Game { #region Fields public TouchLocation? touchLocation; // UI Elements GraphicsDeviceManager graphics; Button handleVolumeSong; Button handleVolumeSound; Button handlePitchSound; Button handlePanSound; //Sound variables SoundEffect laserSoundEffect; SoundEffect loopedSoundEffect; SoundEffectInstance soundEffectInstance; Song song; // Helper class to handle all the UI in the game UIHelper uiHelper; #endregion Fields #region Initialization /// <summary> /// Construction /// </summary> public SoundAndMusicSampleGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // Frame rate is 30 fps by default for Windows Phone. TargetElapsedTime = TimeSpan.FromTicks(333333); // Setup game orientation to Portrait and enable Full Screen graphics.IsFullScreen = true; graphics.PreferredBackBufferWidth = 480; graphics.PreferredBackBufferHeight = 800; uiHelper = new UIHelper(); uiHelper.CreateUIComponents(this, out handleVolumeSong, out handleVolumeSound, out handlePitchSound, out handlePanSound); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); uiHelper.InitializeUIComponents(ButtonPlayFireForgetTouchDown, ButtonPlayStoredSoundEffectTouchDown, ButtonPauseStoredSoundEffectTouchDown, ButtonStopStoredSoundEffectTouchDown, SliderHandlePositionChanged, ButtonPlaySongTouchDown, ButtonPauseSongTouchDown, ButtonStopSongTouchDown); } #endregion #region Loading /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { uiHelper.LoadAssets(this, out laserSoundEffect, out loopedSoundEffect, out soundEffectInstance, out song); base.LoadContent(); } #endregion #region Update protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); //Get the touch data - to be used from UI elements TouchCollection touches = TouchPanel.GetState(); if (touches.Count == 1) { // Use only the single (first) touch point touchLocation = touches[0]; } else touchLocation = null; base.Update(gameTime); } #endregion #region Rendering /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { uiHelper.RenderUI(GraphicsDevice); base.Draw(gameTime); } #endregion #region Event Handlers - Handles UI events and perfroms the Sound-related logic /// <summary> /// Handles the PositionChanged event of all the slider handles /// by extracting the scaledValue from the handle's position relative to it's dragging bounds /// and acting according to the handle the was moved. /// </summary> /// <param name="sender">The handle</param> /// <param name="e"></param> private void SliderHandlePositionChanged(object sender, EventArgs e) { Button handle = sender as Button; float scaledValue = (handle.PositionOfOrigin.X - (float)handle.DragRestrictions.Left) / (float)handle.DragRestrictions.Width; // Sound pan handle if (handle == handlePanSound) { // Rescale a 0->1 value to -1->1 value // -1 is panning left and 1 is panning right scaledValue = (scaledValue - 0.5f) * 2; soundEffectInstance.Pan = scaledValue; } // Sound pitch handle else if (handle == handlePitchSound) { // Rescale a 0->1 value to -1->1 value // -1 one octave down and 1 is one octave up scaledValue = (scaledValue - 0.5f) * 2; soundEffectInstance.Pitch = scaledValue; } // Sound volume handle else if (handle == handleVolumeSound) { soundEffectInstance.Volume = scaledValue; } // Song volume handle else if (handle == handleVolumeSong) { // Note: Because the bug in emulator, setting MediaPlayer.Volume to 0 will reset the // volume to 1. This is not occurs when deployed to the real device. As a workaround // this sample checks the runtime environment and behaves correspondingly // Note: Volume adjustment is based on a decibel, not multiplicative, scale. // For more information please refer to documentation online: // http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.media.mediaplayer.volume.aspx if (Microsoft.Devices.Environment.DeviceType == Microsoft.Devices.DeviceType.Device) MediaPlayer.Volume = scaledValue; else MediaPlayer.Volume = MathHelper.Clamp(scaledValue, 0.000001f, 1); } } /// <summary> /// Acting upon PlayFireForget button press /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonPlayFireForgetTouchDown(object sender, EventArgs e) { laserSoundEffect.Play(); } /// <summary> /// Acting upon StopStoredSoundEffect button press /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonStopStoredSoundEffectTouchDown(object sender, EventArgs e) { if (soundEffectInstance.State != SoundState.Stopped) { soundEffectInstance.Stop(); } } /// <summary> /// Acting upon PauseStoredSoundEffect button press /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonPauseStoredSoundEffectTouchDown(object sender, EventArgs e) { if (soundEffectInstance.State == SoundState.Playing) { soundEffectInstance.Pause(); } } /// <summary> /// Acting upon PlayStoredSoundEffect button press /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonPlayStoredSoundEffectTouchDown(object sender, EventArgs e) { if (soundEffectInstance.State == SoundState.Paused) { soundEffectInstance.Resume(); } else if (soundEffectInstance.State == SoundState.Stopped) { soundEffectInstance.Play(); } } /// <summary> /// Acting upon StopSong button press /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonStopSongTouchDown(object sender, EventArgs e) { if (MediaPlayer.State != MediaState.Stopped) { MediaPlayer.Stop(); } } /// <summary> /// Acting upon PauseSong button press /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonPauseSongTouchDown(object sender, EventArgs e) { if (MediaPlayer.State == MediaState.Playing) { MediaPlayer.Pause(); } } /// <summary> /// Acting upon PlaySong button press /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void ButtonPlaySongTouchDown(object sender, EventArgs e) { if (MediaPlayer.State == MediaState.Paused) { MediaPlayer.Resume(); } else if (MediaPlayer.State == MediaState.Stopped) { MediaPlayer.IsRepeating = true; MediaPlayer.Play(song); } } #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.ComponentModel.Composition; using System.ComponentModel.Composition.Factories; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.UnitTesting; using Xunit; namespace Tests.Integration { public class RejectionTests { public interface IExtension { int Id { get; set; } } [Export] public class MyImporter { [ImportMany(AllowRecomposition = true)] public IExtension[] Extensions { get; set; } } [Export(typeof(IExtension))] public class Extension1 : IExtension { [Import("IExtension.IdValue")] public int Id { get; set; } } [Export(typeof(IExtension))] public class Extension2 : IExtension { [Import("IExtension.IdValue2")] public int Id { get; set; } } [Fact] public void Rejection_ExtensionLightUp_AddedViaBatch() { var container = ContainerFactory.CreateWithAttributedCatalog( typeof(MyImporter), typeof(Extension1), typeof(Extension2)); var importer = container.GetExportedValue<MyImporter>(); Assert.Equal(0, importer.Extensions.Length); container.ComposeExportedValue<int>("IExtension.IdValue", 10); Assert.Equal(1, importer.Extensions.Length); Assert.Equal(10, importer.Extensions[0].Id); container.ComposeExportedValue<int>("IExtension.IdValue2", 20); Assert.Equal(2, importer.Extensions.Length); Assert.Equal(10, importer.Extensions[0].Id); Assert.Equal(20, importer.Extensions[1].Id); } public class ExtensionValues { [Export("IExtension.IdValue")] public int Value = 10; [Export("IExtension.IdValue2")] public int Value2 = 20; } [Fact] public void Rejection_ExtensionLightUp_AddedViaCatalog() { var ext1Cat = CatalogFactory.CreateAttributed(typeof(Extension1)); var ext2Cat = CatalogFactory.CreateAttributed(typeof(Extension2)); var hostCat = CatalogFactory.CreateAttributed(typeof(MyImporter)); var valueCat = CatalogFactory.CreateAttributed(typeof(ExtensionValues)); var catalog = new AggregateCatalog(); catalog.Catalogs.Add(hostCat); var container = ContainerFactory.Create(catalog); var importer = container.GetExportedValue<MyImporter>(); Assert.Equal(0, importer.Extensions.Length); catalog.Catalogs.Add(ext1Cat); Assert.Equal(0, importer.Extensions.Length); catalog.Catalogs.Add(ext2Cat); Assert.Equal(0, importer.Extensions.Length); catalog.Catalogs.Add(valueCat); Assert.Equal(2, importer.Extensions.Length); Assert.Equal(10, importer.Extensions[0].Id); Assert.Equal(20, importer.Extensions[1].Id); } public interface IMissing { } public interface ISingle { } public interface IMultiple { } public interface IConditional { } public class SingleImpl : ISingle { } public class MultipleImpl : IMultiple { } public class NoImportPart { public NoImportPart() { SingleExport = new SingleImpl(); MultipleExport1 = new MultipleImpl(); MultipleExport2 = new MultipleImpl(); } [Export] public ISingle SingleExport { private set; get; } [Export] public IMultiple MultipleExport1 { private set; get; } [Export] public IMultiple MultipleExport2 { private set; get; } } [Export] public class Needy { public Needy() { } [Import] public ISingle SingleImport { get; set; } } [Fact] public void Rejection_Resurrection() { var container = ContainerFactory.CreateWithAttributedCatalog(typeof(Needy)); var exports1 = container.GetExportedValues<Needy>(); Assert.Equal(0, exports1.Count()); container.ComposeParts(new NoImportPart()); var exports2 = container.GetExportedValues<Needy>(); Assert.Equal(1, exports2.Count()); } [Fact] public void Rejection_BatchSatisfiesBatch() { var container = ContainerFactory.Create(); var needy = new Needy(); container.ComposeParts(needy, new NoImportPart()); Assert.IsType<SingleImpl>(needy.SingleImport); } [Fact] public void Rejection_BatchSatisfiesBatchReversed() { var container = ContainerFactory.Create(); var needy = new Needy(); container.ComposeParts(new NoImportPart(), needy); Assert.IsType<SingleImpl>(needy.SingleImport); } [Fact] public void Rejection_CatalogSatisfiesBatch() { var container = ContainerFactory.CreateWithAttributedCatalog(typeof(NoImportPart)); var needy = new Needy(); container.ComposeParts(needy); Assert.IsType<SingleImpl>(needy.SingleImport); } [Fact] public void Rejection_TransitiveDependenciesSatisfied() { var container = ContainerFactory.CreateWithAttributedCatalog(typeof(Needy), typeof(NoImportPart)); var needy = container.GetExportedValue<Needy>(); Assert.NotNull(needy); Assert.IsType<SingleImpl>(needy.SingleImport); } [Fact] public void Rejection_TransitiveDependenciesUnsatisfied_ShouldThrowCardinalityMismatch() { var container = ContainerFactory.CreateWithAttributedCatalog(typeof(Needy), typeof(MissingImportPart)); ExceptionAssert.Throws<ImportCardinalityMismatchException>(() => container.GetExportedValue<Needy>()); } public class MissingImportPart : NoImportPart { [Import] public IMissing MissingImport { set; get; } } [Fact] public void Rejection_BatchRevert() { var container = ContainerFactory.Create(); ExceptionAssert.Throws<ChangeRejectedException>(() => container.ComposeParts(new MissingImportPart())); } [Fact] public void Rejection_DefendPromisesOnceMade() { var container = ContainerFactory.CreateWithAttributedCatalog(typeof(Needy)); var addBatch = new CompositionBatch(); var removeBatch = new CompositionBatch(); var addedPart = addBatch.AddPart(new NoImportPart()); removeBatch.RemovePart(addedPart); // Add then remove should be fine as long as exports aren't used yet. container.Compose(addBatch); container.Compose(removeBatch); // Add the dependencies container.Compose(addBatch); // Retrieve needy which uses an export from addedPart var export = container.GetExportedValue<Needy>(); // Should not be able to remove the addedPart because someone depends on it. ExceptionAssert.Throws<ChangeRejectedException>(() => container.Compose(removeBatch)); } [Fact] public void Rejection_DefendPromisesLazily() { var container = ContainerFactory.CreateWithAttributedCatalog(typeof(Needy)); // Add the missing dependency for Needy container.ComposeParts(new NoImportPart()); // This change should succeed since the component "Needy" hasn't been fully composed // and one way of satisfying its needs is as good ask another var export = container.GetExport<Needy>(); // Cannot add another import because it would break existing promised compositions ExceptionAssert.Throws<ChangeRejectedException>(() => container.ComposeParts(new NoImportPart())); // Instansitate the object var needy = export.Value; // Cannot add another import because it would break existing compositions ExceptionAssert.Throws<ChangeRejectedException>(() => container.ComposeParts(new NoImportPart())); } [Fact] public void Rejection_SwitchPromiseFromManualToCatalog() { // This test shows how the priority list in the AggregateCatalog can actually play with // the rejection work. Until the actual object is actually pulled on and satisfied the // promise can be moved around even for not-recomposable imports but once the object is // pulled on it is fixed from that point on. var container = ContainerFactory.CreateWithAttributedCatalog(typeof(Needy), typeof(NoImportPart)); // Add the missing dependency for Needy container.ComposeParts(new NoImportPart()); // This change should succeed since the component "Needy" hasn't been fully composed // and one way of satisfying its needs is as good as another var export = container.GetExport<Needy>(); // Adding more exports doesn't fail because we push the promise to use the NoImportPart from the catalog // using the priorities from the AggregateExportProvider container.ComposeParts(new NoImportPart()); // Instansitate the object var needy = export.Value; // Cannot add another import because it would break existing compositions ExceptionAssert.Throws<ChangeRejectedException>(() => container.ComposeParts(new NoImportPart())); } public interface ILoopA { } public interface ILoopB { } [Export(typeof(ILoopA))] public class LoopA1 : ILoopA { [Import] public ILoopB LoopB { set; get; } } [Export(typeof(ILoopA))] public class LoopA2 : ILoopA { [Import] public ILoopB LoopB { set; get; } } [Export(typeof(ILoopB))] public class LoopB1 : ILoopB { [Import] public ILoopA LoopA { set; get; } } [Export(typeof(ILoopB))] public class LoopB2 : ILoopB { [Import] public ILoopA LoopA { set; get; } } // This is an interesting situation. There are several possible self-consistent outcomes: // - All parts involved in the loop are rejected // - A consistent subset are not rejected (exactly one of LoopA1/LoopA2 and one of LoopB1/LoopB2 // // Both have desireable and undesirable characteristics. The first case is non-discriminatory but // rejects more parts than are necessary, the second minimizes rejection but must choose a subset // on somewhat arbitary grounds. [Fact] public void Rejection_TheClemensLoop() { var catalog = new TypeCatalog(new Type[] { typeof(LoopA1), typeof(LoopA2), typeof(LoopB1), typeof(LoopB2) }); var container = new CompositionContainer(catalog); var exportsA = container.GetExportedValues<ILoopA>(); var exportsB = container.GetExportedValues<ILoopB>(); // These assertions would prove solution one Assert.Equal(0, exportsA.Count()); Assert.Equal(0, exportsB.Count()); // These assertions would prove solution two //Assert.Equal(1, exportsA.Count); //Assert.Equal(1, exportsB.Count); } public interface IWorkItem { string Id { get; set; } } [Export] public class AllWorkItems { [ImportMany(AllowRecomposition = true)] public Lazy<IWorkItem>[] WorkItems { get; set; } } [Export(typeof(IWorkItem))] public class WorkItem : IWorkItem { [Import("WorkItem.Id", AllowRecomposition = true)] public string Id { get; set; } } public class Ids { [Export("WorkItem.Id")] public string Id = "MyId"; } [Fact] public void AppliedStateNotCompleteedYet() { var container = ContainerFactory.CreateWithAttributedCatalog(typeof(AllWorkItems)); container.ComposeExportedValue<string>("WorkItem.Id", "A"); var workItems = container.GetExportedValue<AllWorkItems>(); Assert.Equal(0, workItems.WorkItems.Length); container.ComposeParts(new WorkItem()); Assert.Equal(1, workItems.WorkItems.Length); Assert.Equal("A", workItems.WorkItems[0].Value.Id); } [Export] public class ClassWithMissingImport { [Import] private string _importNotFound = null; public ClassWithMissingImport() { if (_importNotFound != null) throw new ArgumentException(); } } [Fact] public void AppliedStateStored_ShouldRevertStateOnFailure() { var container = ContainerFactory.CreateWithAttributedCatalog(typeof(AllWorkItems), typeof(WorkItem), typeof(Ids)); var workItems = container.GetExportedValue<AllWorkItems>(); Assert.Equal(1, workItems.WorkItems.Length); var batch = new CompositionBatch(); batch.AddExportedValue("WorkItem.Id", "B"); batch.AddPart(new ClassWithMissingImport()); ExceptionAssert.Throws<ChangeRejectedException>(() => container.Compose(batch)); Assert.Equal("MyId", workItems.WorkItems[0].Value.Id); } [Export] public class OptionalImporter { [Import(AllowDefault = true)] public ClassWithMissingImport Import { get; set; } } [Fact] public void OptionalImportWithMissingDependency_ShouldRejectAndComposeFine() { var container = ContainerFactory.CreateWithAttributedCatalog(typeof(OptionalImporter), typeof(ClassWithMissingImport)); var importer = container.GetExportedValue<OptionalImporter>(); Assert.Null(importer.Import); } [Export] public class PartA { [Import(AllowDefault = true, AllowRecomposition = true)] public PartB ImportB { get; set; } } [Export] public class PartB { [Import] public PartC ImportC { get; set; } } [Export] public class PartC { [Import] public PartB ImportB { get; set; } } [Fact] [ActiveIssue(684510)] public void PartAOptionalDependsOnPartB_PartBGetAddedLater() { var container = new CompositionContainer(new TypeCatalog(typeof(PartC), typeof(PartA))); var partA = container.GetExportedValue<PartA>(); Assert.Null(partA.ImportB); var partB = new PartB(); container.ComposeParts(partB); Assert.Equal(partA.ImportB, partB); Assert.NotNull(partB.ImportC); } [Export] public class PartA2 { [Import(AllowDefault = true, AllowRecomposition = true)] public PartB ImportB { get; set; } [Import(AllowDefault = true, AllowRecomposition = true)] public PartC ImportC { get; set; } } [Fact] [ActiveIssue(684510)] public void PartAOptionalDependsOnPartBAndPartC_PartCGetRecurrected() { var container = new CompositionContainer(new TypeCatalog(typeof(PartA2), typeof(PartB))); var partA = container.GetExportedValue<PartA2>(); Assert.Null(partA.ImportB); Assert.Null(partA.ImportC); var partC = new PartC(); container.ComposeParts(partC); Assert.Equal(partA.ImportB, partC.ImportB); Assert.Equal(partA.ImportC, partC); } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Org.Webrtc { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='Logging']" [global::Android.Runtime.Register ("org/webrtc/Logging", DoNotGenerateAcw=true)] public partial class Logging : global::Java.Lang.Object { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.Severity']" [global::Android.Runtime.Register ("org/webrtc/Logging$Severity", DoNotGenerateAcw=true)] public sealed partial class Severity : global::Java.Lang.Enum { static IntPtr LS_ERROR_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.Severity']/field[@name='LS_ERROR']" [Register ("LS_ERROR")] public static global::Org.Webrtc.Logging.Severity LsError { get { if (LS_ERROR_jfieldId == IntPtr.Zero) LS_ERROR_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "LS_ERROR", "Lorg/webrtc/Logging$Severity;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, LS_ERROR_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.Severity> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr LS_INFO_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.Severity']/field[@name='LS_INFO']" [Register ("LS_INFO")] public static global::Org.Webrtc.Logging.Severity LsInfo { get { if (LS_INFO_jfieldId == IntPtr.Zero) LS_INFO_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "LS_INFO", "Lorg/webrtc/Logging$Severity;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, LS_INFO_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.Severity> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr LS_SENSITIVE_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.Severity']/field[@name='LS_SENSITIVE']" [Register ("LS_SENSITIVE")] public static global::Org.Webrtc.Logging.Severity LsSensitive { get { if (LS_SENSITIVE_jfieldId == IntPtr.Zero) LS_SENSITIVE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "LS_SENSITIVE", "Lorg/webrtc/Logging$Severity;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, LS_SENSITIVE_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.Severity> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr LS_VERBOSE_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.Severity']/field[@name='LS_VERBOSE']" [Register ("LS_VERBOSE")] public static global::Org.Webrtc.Logging.Severity LsVerbose { get { if (LS_VERBOSE_jfieldId == IntPtr.Zero) LS_VERBOSE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "LS_VERBOSE", "Lorg/webrtc/Logging$Severity;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, LS_VERBOSE_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.Severity> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr LS_WARNING_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.Severity']/field[@name='LS_WARNING']" [Register ("LS_WARNING")] public static global::Org.Webrtc.Logging.Severity LsWarning { get { if (LS_WARNING_jfieldId == IntPtr.Zero) LS_WARNING_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "LS_WARNING", "Lorg/webrtc/Logging$Severity;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, LS_WARNING_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.Severity> (__ret, JniHandleOwnership.TransferLocalRef); } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/Logging$Severity", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Severity); } } internal Severity (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_valueOf_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.Severity']/method[@name='valueOf' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("valueOf", "(Ljava/lang/String;)Lorg/webrtc/Logging$Severity;", "")] public static unsafe global::Org.Webrtc.Logging.Severity ValueOf (string p0) { if (id_valueOf_Ljava_lang_String_ == IntPtr.Zero) id_valueOf_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "valueOf", "(Ljava/lang/String;)Lorg/webrtc/Logging$Severity;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); global::Org.Webrtc.Logging.Severity __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.Severity> (JNIEnv.CallStaticObjectMethod (class_ref, id_valueOf_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_values; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.Severity']/method[@name='values' and count(parameter)=0]" [Register ("values", "()[Lorg/webrtc/Logging$Severity;", "")] public static unsafe global::Org.Webrtc.Logging.Severity[] Values () { if (id_values == IntPtr.Zero) id_values = JNIEnv.GetStaticMethodID (class_ref, "values", "()[Lorg/webrtc/Logging$Severity;"); try { return (global::Org.Webrtc.Logging.Severity[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_values), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Webrtc.Logging.Severity)); } finally { } } } // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']" [global::Android.Runtime.Register ("org/webrtc/Logging$TraceLevel", DoNotGenerateAcw=true)] public sealed partial class TraceLevel : global::Java.Lang.Enum { static IntPtr TRACE_ALL_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_ALL']" [Register ("TRACE_ALL")] public static global::Org.Webrtc.Logging.TraceLevel TraceAll { get { if (TRACE_ALL_jfieldId == IntPtr.Zero) TRACE_ALL_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_ALL", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_ALL_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_APICALL_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_APICALL']" [Register ("TRACE_APICALL")] public static global::Org.Webrtc.Logging.TraceLevel TraceApicall { get { if (TRACE_APICALL_jfieldId == IntPtr.Zero) TRACE_APICALL_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_APICALL", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_APICALL_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_CRITICAL_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_CRITICAL']" [Register ("TRACE_CRITICAL")] public static global::Org.Webrtc.Logging.TraceLevel TraceCritical { get { if (TRACE_CRITICAL_jfieldId == IntPtr.Zero) TRACE_CRITICAL_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_CRITICAL", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_CRITICAL_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_DEBUG_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_DEBUG']" [Register ("TRACE_DEBUG")] public static global::Org.Webrtc.Logging.TraceLevel TraceDebug { get { if (TRACE_DEBUG_jfieldId == IntPtr.Zero) TRACE_DEBUG_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_DEBUG", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_DEBUG_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_DEFAULT_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_DEFAULT']" [Register ("TRACE_DEFAULT")] public static global::Org.Webrtc.Logging.TraceLevel TraceDefault { get { if (TRACE_DEFAULT_jfieldId == IntPtr.Zero) TRACE_DEFAULT_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_DEFAULT", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_DEFAULT_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_ERROR_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_ERROR']" [Register ("TRACE_ERROR")] public static global::Org.Webrtc.Logging.TraceLevel TraceError { get { if (TRACE_ERROR_jfieldId == IntPtr.Zero) TRACE_ERROR_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_ERROR", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_ERROR_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_INFO_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_INFO']" [Register ("TRACE_INFO")] public static global::Org.Webrtc.Logging.TraceLevel TraceInfo { get { if (TRACE_INFO_jfieldId == IntPtr.Zero) TRACE_INFO_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_INFO", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_INFO_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_MEMORY_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_MEMORY']" [Register ("TRACE_MEMORY")] public static global::Org.Webrtc.Logging.TraceLevel TraceMemory { get { if (TRACE_MEMORY_jfieldId == IntPtr.Zero) TRACE_MEMORY_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_MEMORY", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_MEMORY_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_MODULECALL_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_MODULECALL']" [Register ("TRACE_MODULECALL")] public static global::Org.Webrtc.Logging.TraceLevel TraceModulecall { get { if (TRACE_MODULECALL_jfieldId == IntPtr.Zero) TRACE_MODULECALL_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_MODULECALL", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_MODULECALL_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_NONE_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_NONE']" [Register ("TRACE_NONE")] public static global::Org.Webrtc.Logging.TraceLevel TraceNone { get { if (TRACE_NONE_jfieldId == IntPtr.Zero) TRACE_NONE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_NONE", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_NONE_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_STATEINFO_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_STATEINFO']" [Register ("TRACE_STATEINFO")] public static global::Org.Webrtc.Logging.TraceLevel TraceStateinfo { get { if (TRACE_STATEINFO_jfieldId == IntPtr.Zero) TRACE_STATEINFO_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_STATEINFO", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_STATEINFO_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_STREAM_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_STREAM']" [Register ("TRACE_STREAM")] public static global::Org.Webrtc.Logging.TraceLevel TraceStream { get { if (TRACE_STREAM_jfieldId == IntPtr.Zero) TRACE_STREAM_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_STREAM", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_STREAM_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_TERSEINFO_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_TERSEINFO']" [Register ("TRACE_TERSEINFO")] public static global::Org.Webrtc.Logging.TraceLevel TraceTerseinfo { get { if (TRACE_TERSEINFO_jfieldId == IntPtr.Zero) TRACE_TERSEINFO_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_TERSEINFO", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_TERSEINFO_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_TIMER_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_TIMER']" [Register ("TRACE_TIMER")] public static global::Org.Webrtc.Logging.TraceLevel TraceTimer { get { if (TRACE_TIMER_jfieldId == IntPtr.Zero) TRACE_TIMER_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_TIMER", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_TIMER_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr TRACE_WARNING_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='TRACE_WARNING']" [Register ("TRACE_WARNING")] public static global::Org.Webrtc.Logging.TraceLevel TraceWarning { get { if (TRACE_WARNING_jfieldId == IntPtr.Zero) TRACE_WARNING_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "TRACE_WARNING", "Lorg/webrtc/Logging$TraceLevel;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, TRACE_WARNING_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr level_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/field[@name='level']" [Register ("level")] public int Level { get { if (level_jfieldId == IntPtr.Zero) level_jfieldId = JNIEnv.GetFieldID (class_ref, "level", "I"); return JNIEnv.GetIntField (Handle, level_jfieldId); } set { if (level_jfieldId == IntPtr.Zero) level_jfieldId = JNIEnv.GetFieldID (class_ref, "level", "I"); try { JNIEnv.SetField (Handle, level_jfieldId, value); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/Logging$TraceLevel", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (TraceLevel); } } internal TraceLevel (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_valueOf_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/method[@name='valueOf' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("valueOf", "(Ljava/lang/String;)Lorg/webrtc/Logging$TraceLevel;", "")] public static unsafe global::Org.Webrtc.Logging.TraceLevel ValueOf (string p0) { if (id_valueOf_Ljava_lang_String_ == IntPtr.Zero) id_valueOf_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "valueOf", "(Ljava/lang/String;)Lorg/webrtc/Logging$TraceLevel;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); global::Org.Webrtc.Logging.TraceLevel __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.Logging.TraceLevel> (JNIEnv.CallStaticObjectMethod (class_ref, id_valueOf_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_values; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='Logging.TraceLevel']/method[@name='values' and count(parameter)=0]" [Register ("values", "()[Lorg/webrtc/Logging$TraceLevel;", "")] public static unsafe global::Org.Webrtc.Logging.TraceLevel[] Values () { if (id_values == IntPtr.Zero) id_values = JNIEnv.GetStaticMethodID (class_ref, "values", "()[Lorg/webrtc/Logging$TraceLevel;"); try { return (global::Org.Webrtc.Logging.TraceLevel[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_values), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Webrtc.Logging.TraceLevel)); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/Logging", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (Logging); } } protected Logging (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='Logging']/constructor[@name='Logging' and count(parameter)=0]" [Register (".ctor", "()V", "")] public unsafe Logging () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { if (GetType () != typeof (Logging)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V"); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor); } finally { } } static IntPtr id_enableTracing_Ljava_lang_String_Ljava_util_EnumSet_Lorg_webrtc_Logging_Severity_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='Logging']/method[@name='enableTracing' and count(parameter)=3 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.util.EnumSet&lt;org.webrtc.Logging.TraceLevel&gt;'] and parameter[3][@type='org.webrtc.Logging.Severity']]" [Register ("enableTracing", "(Ljava/lang/String;Ljava/util/EnumSet;Lorg/webrtc/Logging$Severity;)V", "")] public static unsafe void EnableTracing (string p0, global::Java.Util.EnumSet p1, global::Org.Webrtc.Logging.Severity p2) { if (id_enableTracing_Ljava_lang_String_Ljava_util_EnumSet_Lorg_webrtc_Logging_Severity_ == IntPtr.Zero) id_enableTracing_Ljava_lang_String_Ljava_util_EnumSet_Lorg_webrtc_Logging_Severity_ = JNIEnv.GetStaticMethodID (class_ref, "enableTracing", "(Ljava/lang/String;Ljava/util/EnumSet;Lorg/webrtc/Logging$Severity;)V"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [3]; __args [0] = new JValue (native_p0); __args [1] = new JValue (p1); __args [2] = new JValue (p2); JNIEnv.CallStaticVoidMethod (class_ref, id_enableTracing_Ljava_lang_String_Ljava_util_EnumSet_Lorg_webrtc_Logging_Severity_, __args); } finally { JNIEnv.DeleteLocalRef (native_p0); } } } }
//////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2021 Tim Stair // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.IO; using System.Windows.Forms; namespace Support.IO { public class IniManager { private const char CHAR_SPLITTER = '='; private const string CONTROL_FORMAT = "{0}_{1}"; private Dictionary<string, string> m_dictionaryItems = new Dictionary<string, string>(); private bool m_bReadOnly; private bool m_bMatchCase; private enum ERestoreStateValue { LocationX, LocationY, SizeWidth, SizeHeight, State, End } /// <summary> /// Sets the IniManager to flush to the ini file every time a value is set. (Automatic call to FlushIniSettings) /// </summary> public bool AutoFlush { get; set; } /// <summary> /// The ini file path /// </summary> public string Filename { get; private set; } /// <summary> /// Creates a new IniManager /// </summary> /// <param name="sFileName">The file to use in the IniManager</param> /// <param name="bReadOnly">Flag indicating items can only be read</param> public IniManager(string sFileName, bool bReadOnly) { Init(sFileName, bReadOnly, true, false); } /// <summary> /// Creates a new IniManager /// </summary> /// <param name="sFileName">Path of the ini file (or just the name)</param> /// <param name="bReadOnly">Flag indicating items can only be read</param> /// <param name="bUseApplicationPath">Automatically construct the full path using the startup path and append .ini</param> public IniManager(string sFileName, bool bReadOnly, bool bUseApplicationPath) { Init(sFileName, bReadOnly, bUseApplicationPath, false); } /// <summary> /// Creates a new IniManager /// </summary> /// <param name="sFileName">Path of the ini file (or just the name)</param> /// <param name="bReadOnly">Flag indicating items can only be read</param> /// <param name="bUseApplicationPath">Automatically construct the full path using the startup path and append .ini</param> /// <param name="bMatchCase">Items in the ini file must match the case of the item specified.</param> public IniManager(string sFileName, bool bReadOnly, bool bUseApplicationPath, bool bMatchCase) { Init(sFileName, bReadOnly, bUseApplicationPath, bMatchCase); } /// <summary> /// Core call to setup the inimanager /// </summary> /// <param name="sFileName">Path of the ini file (or just the name)</param> /// <param name="bReadOnly">Flag indicating items can only be read</param> /// <param name="bUseApplicationPath">Automatically construct the full path using the startup path and append .ini</param> /// <param name="bMatchCase">Items in the ini file must match the case of the item specified.</param> private void Init(string sFileName, bool bReadOnly, bool bUseApplicationPath, bool bMatchCase) { if (bUseApplicationPath) Filename = Application.StartupPath + Path.DirectorySeparatorChar + sFileName + ".ini"; else Filename = sFileName; m_bReadOnly = bReadOnly; m_bMatchCase = bMatchCase; m_dictionaryItems = GetIniTable(Filename, CHAR_SPLITTER); } /// <summary> /// Gets the value of the string specified /// </summary> /// <param name="sItem">The string requested</param> /// <param name="sDefault">The default value</param> /// <returns>The value of the string or default value</returns> public string GetValue(string sItem, string sDefault="") { string sCheck = m_bMatchCase ? sItem : sItem.ToLower(); string sValue; if (m_dictionaryItems.TryGetValue(sCheck, out sValue)) { return sValue; } return sDefault; } /// <summary> /// Gets the value of the string specified /// </summary> /// <param name="eItem">The enum.ToString() requested</param> /// <param name="sDefault">The default value</param> /// <returns>The value of the string or string.empty</returns> public string GetValue(Enum eItem, string sDefault="") { return GetValue(eItem.ToString(), sDefault); } /// <summary> /// Sets the value of a specified string /// </summary> /// <param name="sItem">The key string</param> /// <param name="sValue">The value string</param> public void SetValue(string sItem, string sValue) { if(m_bReadOnly) throw new Exception("Attempting to write to a read-only IniManager! " + Filename); string sCheck = m_bMatchCase ? sItem : sItem.ToLower(); if (m_dictionaryItems.ContainsKey(sCheck)) m_dictionaryItems[sCheck] = sValue; else m_dictionaryItems.Add(sCheck, sValue); if (AutoFlush) FlushIniSettings(); } /// <summary> /// Sets the value of a specified string /// </summary> /// <param name="eItem">The key string</param> /// <param name="sValue">The value string</param> public void SetValue(Enum eItem, string sValue) { SetValue(eItem.ToString(), sValue); } /// <summary> /// Flushes the Ini settings to the file associated with this object /// </summary> public void FlushIniSettings() { string sDirectory = Path.GetDirectoryName(Filename); if (sDirectory != null && !Directory.Exists(sDirectory)) { Directory.CreateDirectory(sDirectory); } try { var zWriter = new StreamWriter(Filename, false); foreach (var sKey in m_dictionaryItems.Keys) { zWriter.WriteLine(sKey + CHAR_SPLITTER + m_dictionaryItems[sKey]); } zWriter.Close(); } #warning do nothing? catch (Exception) { throw; } } /// <summary> /// Method to return all of the current keys /// </summary> /// <returns>Returns all of the key strings</returns> public string[] GetKeys() { var arrayKeys = new string[m_dictionaryItems.Keys.Count]; int nIdx = 0; foreach (string sKey in m_dictionaryItems.Keys) { arrayKeys[nIdx] = sKey; nIdx++; } return arrayKeys; } /// <summary> /// Reads the specified ini file /// </summary> /// <param name="sFile">The file to read from</param> /// <param name="cSplitItem">The character to split on</param> /// <returns>Dictionary of keys and values read from the file</returns> private Dictionary<string, string> GetIniTable(string sFile, char cSplitItem) { var dictionaryItems = new Dictionary<string, string>(); try { if (File.Exists(sFile)) { var arrayLines = File.ReadAllLines(sFile); foreach (var sLine in arrayLines) { var arraySplit = sLine.Split(new char[] {cSplitItem}, 2); var sItem = m_bMatchCase ? arraySplit[0] : arraySplit[0].ToLower(); if (!dictionaryItems.ContainsKey(sItem)) dictionaryItems.Add(sItem, arraySplit[1]); } } } #warning do nothing?? catch (Exception) { } return dictionaryItems; } /// <summary> /// Gets the string representation of the specified form's state /// </summary> /// <param name="zForm">The form to get the state of</param> /// <returns></returns> public static string GetFormSettings(Form zForm) { if (FormWindowState.Normal == zForm.WindowState) { return zForm.Location.X + ";" + zForm.Location.Y + ";" + zForm.Size.Width + ";" + zForm.Size.Height + ";" + (int) zForm.WindowState; } return zForm.RestoreBounds.Location.X + ";" + zForm.RestoreBounds.Location.Y + ";" + zForm.RestoreBounds.Size.Width + ";" + zForm.RestoreBounds.Size.Height + ";" + (int)zForm.WindowState; } /// <summary> /// Restores the state of a form based on the input string /// </summary> /// <param name="zForm">The form to restore the state of</param> /// <param name="sInput">The string representation of the form state</param> public static void RestoreState(Form zForm, string sInput) { string[] arraySplit = sInput.Split(new char[] { ';' }); var nValues = new int[(int)ERestoreStateValue.End]; if ((int)ERestoreStateValue.End == arraySplit.Length) { for (int nIdx = 0; nIdx < arraySplit.Length; nIdx++) { nValues[nIdx] = int.Parse(arraySplit[nIdx]); } zForm.Location = new Point(nValues[(int)ERestoreStateValue.LocationX], nValues[(int)ERestoreStateValue.LocationY]); zForm.Size = new Size(nValues[(int)ERestoreStateValue.SizeWidth], nValues[(int)ERestoreStateValue.SizeHeight]); zForm.WindowState = (FormWindowState)nValues[(int)ERestoreStateValue.State]; } } /// <summary> /// Stores the settings of the controls in the specified form /// </summary> /// <param name="zForm">The form to store the controls of</param> public void StoreControlSettings(Form zForm) { foreach (Control zControl in zForm.Controls) { string sKeyName = string.Format(CONTROL_FORMAT, zForm.Name, zControl.Name); if (zControl is TextBox) SetValue(sKeyName, ((TextBox)zControl).Text); else if (zControl is NumericUpDown) SetValue(sKeyName, ((NumericUpDown)zControl).Value.ToString(CultureInfo.CurrentCulture)); else if (zControl is CheckBox) SetValue(sKeyName, ((CheckBox)zControl).Checked.ToString()); } } /// <summary> /// Restores the settings of the controls in the specified form. /// Proceed with caution in relation to value change events! /// </summary> /// <param name="zForm"></param> public void RestoreControlSettings(Form zForm) { foreach (Control zControl in zForm.Controls) { string sKeyName = string.Format(CONTROL_FORMAT, zForm.Name, zControl.Name); if (zControl is TextBox) { ((TextBox) zControl).Text = GetValue(sKeyName, string.Empty); } else if (zControl is NumericUpDown) { ((NumericUpDown) zControl).Value = decimal.Parse(GetValue(sKeyName, "0")); } else if (zControl is CheckBox) { ((CheckBox) zControl).Checked = bool.Parse(GetValue(sKeyName, bool.FalseString)); } } } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System; using System.Threading; using Common.Logging; using Quartz.Collection; using Quartz.Impl.AdoJobStore.Common; using Quartz.Util; namespace Quartz.Impl.AdoJobStore { /// <summary> /// Base class for database based lock handlers for providing thread/resource locking /// in order to protect resources from being altered by multiple threads at the /// same time. /// </summary> /// <author>Marko Lahma (.NET)</author> public abstract class DBSemaphore : StdAdoConstants, ISemaphore, ITablePrefixAware { private readonly ILog log; private const string ThreadContextKeyLockOwners = "qrtz_dbs_lck_owners"; private string sql; private String insertSql; private string tablePrefix; private string schedName; private string expandedSQL; private string expandedInsertSQL; private readonly AdoUtil adoUtil; /// <summary> /// Initializes a new instance of the <see cref="DBSemaphore"/> class. /// </summary> /// <param name="tablePrefix">The table prefix.</param> /// <param name="schedName">the scheduler name</param> /// <param name="defaultInsertSQL">The SQL.</param> /// <param name="defaultSQL">The default SQL.</param> /// <param name="dbProvider">The db provider.</param> protected DBSemaphore(string tablePrefix, string schedName, string defaultSQL, string defaultInsertSQL, IDbProvider dbProvider) { log = LogManager.GetLogger(GetType()); this.schedName = schedName; this.tablePrefix = tablePrefix; SQL = defaultSQL; InsertSQL = defaultInsertSQL; adoUtil = new AdoUtil(dbProvider); } /// <summary> /// Gets or sets the lock owners. /// </summary> /// <value>The lock owners.</value> private static HashSet<string> LockOwners { get { return LogicalThreadContext.GetData<HashSet<string>>(ThreadContextKeyLockOwners); } set { LogicalThreadContext.SetData(ThreadContextKeyLockOwners, value); } } /// <summary> /// Gets the log. /// </summary> /// <value>The log.</value> protected ILog Log { get { return log; } } private static HashSet<string> ThreadLocks { get { if (LockOwners == null) { LockOwners = new HashSet<string>(); } return LockOwners; } } /// <summary> /// Execute the SQL that will lock the proper database row. /// </summary> /// <param name="conn"></param> /// <param name="lockName"></param> /// <param name="expandedSQL"></param> /// <param name="expandedInsertSQL"></param> protected abstract void ExecuteSQL(ConnectionAndTransactionHolder conn, string lockName, string expandedSQL, string expandedInsertSQL); /// <summary> /// Grants a lock on the identified resource to the calling thread (blocking /// until it is available). /// </summary> /// <param name="metadata"></param> /// <param name="conn"></param> /// <param name="lockName"></param> /// <returns>true if the lock was obtained.</returns> public bool ObtainLock(DbMetadata metadata, ConnectionAndTransactionHolder conn, string lockName) { lockName = string.Intern(lockName); if (Log.IsDebugEnabled) { Log.DebugFormat("Lock '{0}' is desired by: {1}", lockName, Thread.CurrentThread.Name); } if (!IsLockOwner(lockName)) { ExecuteSQL(conn, lockName, expandedSQL, expandedInsertSQL); if (Log.IsDebugEnabled) { Log.DebugFormat("Lock '{0}' given to: {1}", lockName, Thread.CurrentThread.Name); } ThreadLocks.Add(lockName); //getThreadLocksObtainer().put(lockName, new // Exception("Obtainer...")); } else if (log.IsDebugEnabled) { Log.DebugFormat("Lock '{0}' Is already owned by: {1}", lockName, Thread.CurrentThread.Name); } return true; } /// <summary> /// Release the lock on the identified resource if it is held by the calling /// thread. /// </summary> /// <param name="lockName"></param> public void ReleaseLock(string lockName) { lockName = string.Intern(lockName); if (IsLockOwner(lockName)) { if (Log.IsDebugEnabled) { Log.DebugFormat("Lock '{0}' returned by: {1}", lockName, Thread.CurrentThread.Name); } ThreadLocks.Remove(lockName); //getThreadLocksObtainer().remove(lockName); } else if (Log.IsDebugEnabled) { Log.WarnFormat("Lock '{0}' attempt to return by: {1} -- but not owner!", new Exception("stack-trace of wrongful returner"), lockName, Thread.CurrentThread.Name); } } /// <summary> /// Determine whether the calling thread owns a lock on the identified /// resource. /// </summary> /// <param name="lockName"></param> /// <returns></returns> public bool IsLockOwner(string lockName) { lockName = string.Intern(lockName); return ThreadLocks.Contains(lockName); } /// <summary> /// This Semaphore implementation does use the database. /// </summary> public bool RequiresConnection { get { return true; } } protected string SQL { get { return sql; } set { if (!value.IsNullOrWhiteSpace()) { sql = value.Trim(); } SetExpandedSql(); } } protected string InsertSQL { set { if (!value.IsNullOrWhiteSpace()) { insertSql = value.Trim(); } SetExpandedSql(); } } private void SetExpandedSql() { if (TablePrefix != null && SchedName != null && sql != null && insertSql != null) { expandedSQL = AdoJobStoreUtil.ReplaceTablePrefix(sql, TablePrefix, SchedulerNameLiteral); expandedInsertSQL = AdoJobStoreUtil.ReplaceTablePrefix(insertSql, TablePrefix, SchedulerNameLiteral); } } private String schedNameLiteral; protected string SchedulerNameLiteral { get { if (schedNameLiteral == null) { schedNameLiteral = "'" + schedName + "'"; } return schedNameLiteral; } } public string SchedName { get { return schedName; } set { schedName = value; SetExpandedSql(); } } /// <summary> /// Gets or sets the table prefix. /// </summary> /// <value>The table prefix.</value> public string TablePrefix { get { return tablePrefix; } set { tablePrefix = value; SetExpandedSql(); } } protected AdoUtil AdoUtil { get { return adoUtil; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Threading; namespace System.Net.Sockets { public partial class SocketAsyncEventArgs : EventArgs, IDisposable { // Struct sizes needed for some custom marshaling. internal static readonly int s_controlDataSize = Marshal.SizeOf<Interop.Winsock.ControlData>(); internal static readonly int s_controlDataIPv6Size = Marshal.SizeOf<Interop.Winsock.ControlDataIPv6>(); internal static readonly int s_wsaMsgSize = Marshal.SizeOf<Interop.Winsock.WSAMsg>(); // Buffer,Offset,Count property variables. private WSABuffer _wsaBuffer; private IntPtr _ptrSingleBuffer; // BufferList property variables. private WSABuffer[] _wsaBufferArray; private bool _bufferListChanged; // Internal buffers for WSARecvMsg private byte[] _wsaMessageBuffer; private GCHandle _wsaMessageBufferGCHandle; private IntPtr _ptrWSAMessageBuffer; private byte[] _controlBuffer; private GCHandle _controlBufferGCHandle; private IntPtr _ptrControlBuffer; private WSABuffer[] _wsaRecvMsgWSABufferArray; private GCHandle _wsaRecvMsgWSABufferArrayGCHandle; private IntPtr _ptrWSARecvMsgWSABufferArray; // Internal buffer for AcceptEx when Buffer not supplied. private IntPtr _ptrAcceptBuffer; // Internal SocketAddress buffer private GCHandle _socketAddressGCHandle; private Internals.SocketAddress _pinnedSocketAddress; private IntPtr _ptrSocketAddressBuffer; private IntPtr _ptrSocketAddressBufferSize; // SendPacketsElements property variables. private SendPacketsElement[] _sendPacketsElementsInternal; private Interop.Winsock.TransmitPacketsElement[] _sendPacketsDescriptor; private int _sendPacketsElementsFileCount; private int _sendPacketsElementsBufferCount; // Internal variables for SendPackets private FileStream[] _sendPacketsFileStreams; private SafeHandle[] _sendPacketsFileHandles; private IntPtr _ptrSendPacketsDescriptor; // Overlapped object related variables. private SafeNativeOverlapped _ptrNativeOverlapped; private PreAllocatedOverlapped _preAllocatedOverlapped; private object[] _objectsToPin; private enum PinState { None = 0, NoBuffer, SingleAcceptBuffer, SingleBuffer, MultipleBuffer, SendPackets } private PinState _pinState; private byte[] _pinnedAcceptBuffer; private byte[] _pinnedSingleBuffer; private int _pinnedSingleBufferOffset; private int _pinnedSingleBufferCount; internal int? SendPacketsDescriptorCount { get { return _sendPacketsDescriptor == null ? null : (int?)_sendPacketsDescriptor.Length; } } private void InitializeInternals() { // Zero tells TransmitPackets to select a default send size. _sendPacketsSendSize = 0; } private void FreeInternals(bool calledFromFinalizer) { // Free native overlapped data. FreeOverlapped(calledFromFinalizer); } private void SetupSingleBuffer() { CheckPinSingleBuffer(true); } private void SetupMultipleBuffers() { _bufferListChanged = true; CheckPinMultipleBuffers(); } private void SetupSendPacketsElements() { _sendPacketsElementsInternal = null; } private void InnerComplete() { CompleteIOCPOperation(); } private unsafe void PrepareIOCPOperation() { Debug.Assert(_currentSocket != null, "_currentSocket is null"); Debug.Assert(_currentSocket.SafeHandle != null, "_currentSocket.SafeHandle is null"); Debug.Assert(!_currentSocket.SafeHandle.IsInvalid, "_currentSocket.SafeHandle is invalid"); ThreadPoolBoundHandle boundHandle = _currentSocket.SafeHandle.GetOrAllocateThreadPoolBoundHandle(); NativeOverlapped* overlapped = null; if (_preAllocatedOverlapped != null) { overlapped = boundHandle.AllocateNativeOverlapped(_preAllocatedOverlapped); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::boundHandle#" + LoggingHash.HashString(boundHandle) + "::AllocateNativeOverlapped(m_PreAllocatedOverlapped=" + LoggingHash.HashString(_preAllocatedOverlapped) + "). Returned = " + ((IntPtr)overlapped).ToString("x")); } } else { overlapped = boundHandle.AllocateNativeOverlapped(CompletionPortCallback, this, null); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::boundHandle#" + LoggingHash.HashString(boundHandle) + "::AllocateNativeOverlapped(pinData=null)" + "). Returned = " + ((IntPtr)overlapped).ToString("x")); } } Debug.Assert(overlapped != null, "NativeOverlapped is null."); _ptrNativeOverlapped = new SafeNativeOverlapped(_currentSocket.SafeHandle, overlapped); } private void CompleteIOCPOperation() { // TODO #4900: Optimization to remove callbacks if the operations are completed synchronously: // Use SetFileCompletionNotificationModes(FILE_SKIP_COMPLETION_PORT_ON_SUCCESS). // If SetFileCompletionNotificationModes(FILE_SKIP_COMPLETION_PORT_ON_SUCCESS) is not set on this handle // it is guaranteed that the IOCP operation will be completed in the callback even if Socket.Success was // returned by the Win32 API. // Required to allow another IOCP operation for the same handle. if (_ptrNativeOverlapped != null) { _ptrNativeOverlapped.Dispose(); _ptrNativeOverlapped = null; } } private void InnerStartOperationAccept(bool userSuppliedBuffer) { if (!userSuppliedBuffer) { CheckPinSingleBuffer(false); } } internal unsafe SocketError DoOperationAccept(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, out int bytesTransferred) { PrepareIOCPOperation(); SocketError socketError = SocketError.Success; if (!socket.AcceptEx( handle, acceptHandle, (_ptrSingleBuffer != IntPtr.Zero) ? _ptrSingleBuffer : _ptrAcceptBuffer, (_ptrSingleBuffer != IntPtr.Zero) ? Count - _acceptAddressBufferCount : 0, _acceptAddressBufferCount / 2, _acceptAddressBufferCount / 2, out bytesTransferred, _ptrNativeOverlapped)) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationConnect() { // ConnectEx uses a sockaddr buffer containing he remote address to which to connect. // It can also optionally take a single buffer of data to send after the connection is complete. // // The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack. // The optional buffer is pinned using the Overlapped.UnsafePack method that takes a single object to pin. PinSocketAddressBuffer(); CheckPinNoBuffer(); } internal unsafe SocketError DoOperationConnect(Socket socket, SafeCloseSocket handle, out int bytesTransferred) { PrepareIOCPOperation(); SocketError socketError = SocketError.Success; if (!socket.ConnectEx( handle, _ptrSocketAddressBuffer, _socketAddress.Size, _ptrSingleBuffer, Count, out bytesTransferred, _ptrNativeOverlapped)) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationDisconnect() { CheckPinNoBuffer(); } private void InnerStartOperationReceive() { // WWSARecv uses a WSABuffer array describing buffers of data to send. // // Single and multiple buffers are handled differently so as to optimize // performance for the more common single buffer case. // // For a single buffer: // The Overlapped.UnsafePack method is used that takes a single object to pin. // A single WSABuffer that pre-exists in SocketAsyncEventArgs is used. // // For multiple buffers: // The Overlapped.UnsafePack method is used that takes an array of objects to pin. // An array to reference the multiple buffer is allocated. // An array of WSABuffer descriptors is allocated. } internal unsafe SocketError DoOperationReceive(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred) { PrepareIOCPOperation(); flags = _socketFlags; SocketError socketError; if (_buffer != null) { // Single buffer case. socketError = Interop.Winsock.WSARecv( handle, ref _wsaBuffer, 1, out bytesTransferred, ref flags, _ptrNativeOverlapped, IntPtr.Zero); } else { // Multi buffer case. socketError = Interop.Winsock.WSARecv( handle, _wsaBufferArray, _wsaBufferArray.Length, out bytesTransferred, ref flags, _ptrNativeOverlapped, IntPtr.Zero); } if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationReceiveFrom() { // WSARecvFrom uses e a WSABuffer array describing buffers in which to // receive data and from which to send data respectively. Single and multiple buffers // are handled differently so as to optimize performance for the more common single buffer case. // // For a single buffer: // The Overlapped.UnsafePack method is used that takes a single object to pin. // A single WSABuffer that pre-exists in SocketAsyncEventArgs is used. // // For multiple buffers: // The Overlapped.UnsafePack method is used that takes an array of objects to pin. // An array to reference the multiple buffer is allocated. // An array of WSABuffer descriptors is allocated. // // WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received. // The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack. PinSocketAddressBuffer(); } internal unsafe SocketError DoOperationReceiveFrom(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred) { PrepareIOCPOperation(); flags = _socketFlags; SocketError socketError; if (_buffer != null) { socketError = Interop.Winsock.WSARecvFrom( handle, ref _wsaBuffer, 1, out bytesTransferred, ref flags, _ptrSocketAddressBuffer, _ptrSocketAddressBufferSize, _ptrNativeOverlapped, IntPtr.Zero); } else { socketError = Interop.Winsock.WSARecvFrom( handle, _wsaBufferArray, _wsaBufferArray.Length, out bytesTransferred, ref flags, _ptrSocketAddressBuffer, _ptrSocketAddressBufferSize, _ptrNativeOverlapped, IntPtr.Zero); } if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationReceiveMessageFrom() { // WSARecvMsg uses a WSAMsg descriptor. // The WSAMsg buffer is pinned with a GCHandle to avoid complicating the use of Overlapped. // WSAMsg contains a pointer to a sockaddr. // The sockaddr is pinned with a GCHandle to avoid complicating the use of Overlapped. // WSAMsg contains a pointer to a WSABuffer array describing data buffers. // WSAMsg also contains a single WSABuffer describing a control buffer. PinSocketAddressBuffer(); // Create and pin a WSAMessageBuffer if none already. if (_wsaMessageBuffer == null) { _wsaMessageBuffer = new byte[s_wsaMsgSize]; _wsaMessageBufferGCHandle = GCHandle.Alloc(_wsaMessageBuffer, GCHandleType.Pinned); _ptrWSAMessageBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0); } // Create and pin an appropriately sized control buffer if none already IPAddress ipAddress = (_socketAddress.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null); bool ipv4 = (_currentSocket.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode bool ipv6 = _currentSocket.AddressFamily == AddressFamily.InterNetworkV6; if (ipv4 && (_controlBuffer == null || _controlBuffer.Length != s_controlDataSize)) { if (_controlBufferGCHandle.IsAllocated) { _controlBufferGCHandle.Free(); } _controlBuffer = new byte[s_controlDataSize]; } else if (ipv6 && (_controlBuffer == null || _controlBuffer.Length != s_controlDataIPv6Size)) { if (_controlBufferGCHandle.IsAllocated) { _controlBufferGCHandle.Free(); } _controlBuffer = new byte[s_controlDataIPv6Size]; } if (!_controlBufferGCHandle.IsAllocated) { _controlBufferGCHandle = GCHandle.Alloc(_controlBuffer, GCHandleType.Pinned); _ptrControlBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_controlBuffer, 0); } // If single buffer we need a pinned 1 element WSABuffer. if (_buffer != null) { if (_wsaRecvMsgWSABufferArray == null) { _wsaRecvMsgWSABufferArray = new WSABuffer[1]; } _wsaRecvMsgWSABufferArray[0].Pointer = _ptrSingleBuffer; _wsaRecvMsgWSABufferArray[0].Length = _count; _wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaRecvMsgWSABufferArray, GCHandleType.Pinned); _ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaRecvMsgWSABufferArray, 0); } else { // Just pin the multi-buffer WSABuffer. _wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaBufferArray, GCHandleType.Pinned); _ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaBufferArray, 0); } // Fill in WSAMessageBuffer. unsafe { Interop.Winsock.WSAMsg* pMessage = (Interop.Winsock.WSAMsg*)_ptrWSAMessageBuffer; ; pMessage->socketAddress = _ptrSocketAddressBuffer; pMessage->addressLength = (uint)_socketAddress.Size; pMessage->buffers = _ptrWSARecvMsgWSABufferArray; if (_buffer != null) { pMessage->count = (uint)1; } else { pMessage->count = (uint)_wsaBufferArray.Length; } if (_controlBuffer != null) { pMessage->controlBuffer.Pointer = _ptrControlBuffer; pMessage->controlBuffer.Length = _controlBuffer.Length; } pMessage->flags = _socketFlags; } } internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle, out int bytesTransferred) { PrepareIOCPOperation(); SocketError socketError = socket.WSARecvMsg( handle, _ptrWSAMessageBuffer, out bytesTransferred, _ptrNativeOverlapped, IntPtr.Zero); if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationSend() { // WSASend uses a WSABuffer array describing buffers of data to send. // // Single and multiple buffers are handled differently so as to optimize // performance for the more common single buffer case. // // For a single buffer: // The Overlapped.UnsafePack method is used that takes a single object to pin. // A single WSABuffer that pre-exists in SocketAsyncEventArgs is used. // // For multiple buffers: // The Overlapped.UnsafePack method is used that takes an array of objects to pin. // An array to reference the multiple buffer is allocated. // An array of WSABuffer descriptors is allocated. } internal unsafe SocketError DoOperationSend(SafeCloseSocket handle, out int bytesTransferred) { PrepareIOCPOperation(); SocketError socketError; if (_buffer != null) { // Single buffer case. socketError = Interop.Winsock.WSASend( handle, ref _wsaBuffer, 1, out bytesTransferred, _socketFlags, _ptrNativeOverlapped, IntPtr.Zero); } else { // Multi buffer case. socketError = Interop.Winsock.WSASend( handle, _wsaBufferArray, _wsaBufferArray.Length, out bytesTransferred, _socketFlags, _ptrNativeOverlapped, IntPtr.Zero); } if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } return socketError; } private void InnerStartOperationSendPackets() { // Prevent mutithreaded manipulation of the list. if (_sendPacketsElements != null) { _sendPacketsElementsInternal = (SendPacketsElement[])_sendPacketsElements.Clone(); } // TransmitPackets uses an array of TRANSMIT_PACKET_ELEMENT structs as // descriptors for buffers and files to be sent. It also takes a send size // and some flags. The TRANSMIT_PACKET_ELEMENT for a file contains a native file handle. // This function basically opens the files to get the file handles, pins down any buffers // specified and builds the native TRANSMIT_PACKET_ELEMENT array that will be passed // to TransmitPackets. // Scan the elements to count files and buffers. _sendPacketsElementsFileCount = 0; _sendPacketsElementsBufferCount = 0; Debug.Assert(_sendPacketsElementsInternal != null); foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null) { if (spe._filePath != null) { _sendPacketsElementsFileCount++; } if (spe._buffer != null && spe._count > 0) { _sendPacketsElementsBufferCount++; } } } // Attempt to open the files if any were given. if (_sendPacketsElementsFileCount > 0) { // Create arrays for streams and handles. _sendPacketsFileStreams = new FileStream[_sendPacketsElementsFileCount]; _sendPacketsFileHandles = new SafeHandle[_sendPacketsElementsFileCount]; // Loop through the elements attempting to open each files and get its handle. int index = 0; foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null && spe._filePath != null) { Exception fileStreamException = null; try { // Create a FileStream to open the file. _sendPacketsFileStreams[index] = new FileStream(spe._filePath, FileMode.Open, FileAccess.Read, FileShare.Read); } catch (Exception ex) { // Save the exception to throw after closing any previous successful file opens. fileStreamException = ex; } if (fileStreamException != null) { // Got an exception opening a file - do some cleanup then throw. for (int i = 0; i < _sendPacketsElementsFileCount; i++) { // Drop handles. _sendPacketsFileHandles[i] = null; // Close any open streams. if (_sendPacketsFileStreams[i] != null) { _sendPacketsFileStreams[i].Dispose(); _sendPacketsFileStreams[i] = null; } } throw fileStreamException; } // Get the file handle from the stream. _sendPacketsFileHandles[index] = _sendPacketsFileStreams[index].SafeFileHandle; index++; } } } CheckPinSendPackets(); } internal SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle) { PrepareIOCPOperation(); bool result = socket.TransmitPackets( handle, _ptrSendPacketsDescriptor, _sendPacketsDescriptor.Length, _sendPacketsSendSize, _ptrNativeOverlapped); return result ? SocketError.Success : SocketPal.GetLastSocketError(); } private void InnerStartOperationSendTo() { // WSASendTo uses a WSABuffer array describing buffers in which to // receive data and from which to send data respectively. Single and multiple buffers // are handled differently so as to optimize performance for the more common single buffer case. // // For a single buffer: // The Overlapped.UnsafePack method is used that takes a single object to pin. // A single WSABuffer that pre-exists in SocketAsyncEventArgs is used. // // For multiple buffers: // The Overlapped.UnsafePack method is used that takes an array of objects to pin. // An array to reference the multiple buffer is allocated. // An array of WSABuffer descriptors is allocated. // // WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received. // The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack. PinSocketAddressBuffer(); } internal SocketError DoOperationSendTo(SafeCloseSocket handle, out int bytesTransferred) { PrepareIOCPOperation(); SocketError socketError; if (_buffer != null) { // Single buffer case. socketError = Interop.Winsock.WSASendTo( handle, ref _wsaBuffer, 1, out bytesTransferred, _socketFlags, _ptrSocketAddressBuffer, _socketAddress.Size, _ptrNativeOverlapped, IntPtr.Zero); } else { socketError = Interop.Winsock.WSASendTo( handle, _wsaBufferArray, _wsaBufferArray.Length, out bytesTransferred, _socketFlags, _ptrSocketAddressBuffer, _socketAddress.Size, _ptrNativeOverlapped, IntPtr.Zero); } if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } return socketError; } // Ensures Overlapped object exists for operations that need no data buffer. private void CheckPinNoBuffer() { // PreAllocatedOverlapped will be reused. if (_pinState == PinState.None) { SetupOverlappedSingle(true); } } // Maintains pinned state of single buffer. private void CheckPinSingleBuffer(bool pinUsersBuffer) { if (pinUsersBuffer) { // Using app supplied buffer. if (_buffer == null) { // No user buffer is set so unpin any existing single buffer pinning. if (_pinState == PinState.SingleBuffer) { FreeOverlapped(false); } } else { if (_pinState == PinState.SingleBuffer && _pinnedSingleBuffer == _buffer) { // This buffer is already pinned - update if offset or count has changed. if (_offset != _pinnedSingleBufferOffset) { _pinnedSingleBufferOffset = _offset; _ptrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, _offset); _wsaBuffer.Pointer = _ptrSingleBuffer; } if (_count != _pinnedSingleBufferCount) { _pinnedSingleBufferCount = _count; _wsaBuffer.Length = _count; } } else { FreeOverlapped(false); SetupOverlappedSingle(true); } } } else { // Using internal accept buffer. if (!(_pinState == PinState.SingleAcceptBuffer) || !(_pinnedSingleBuffer == _acceptBuffer)) { // Not already pinned - so pin it. FreeOverlapped(false); SetupOverlappedSingle(false); } } } // Ensures Overlapped object exists with appropriate multiple buffers pinned. private void CheckPinMultipleBuffers() { if (_bufferList == null) { // No buffer list is set so unpin any existing multiple buffer pinning. if (_pinState == PinState.MultipleBuffer) { FreeOverlapped(false); } } else { if (!(_pinState == PinState.MultipleBuffer) || _bufferListChanged) { // Need to setup a new Overlapped. _bufferListChanged = false; FreeOverlapped(false); try { SetupOverlappedMultiple(); } catch (Exception) { FreeOverlapped(false); throw; } } } } // Ensures Overlapped object exists with appropriate buffers pinned. private void CheckPinSendPackets() { if (_pinState != PinState.None) { FreeOverlapped(false); } SetupOverlappedSendPackets(); } // Ensures appropriate SocketAddress buffer is pinned. private void PinSocketAddressBuffer() { // Check if already pinned. if (_pinnedSocketAddress == _socketAddress) { return; } // Unpin any existing. if (_socketAddressGCHandle.IsAllocated) { _socketAddressGCHandle.Free(); } // Pin down the new one. _socketAddressGCHandle = GCHandle.Alloc(_socketAddress.Buffer, GCHandleType.Pinned); _socketAddress.CopyAddressSizeIntoBuffer(); _ptrSocketAddressBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, 0); _ptrSocketAddressBufferSize = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, _socketAddress.GetAddressSizeOffset()); _pinnedSocketAddress = _socketAddress; } // Cleans up any existing Overlapped object and related state variables. private void FreeOverlapped(bool checkForShutdown) { if (!checkForShutdown || !Environment.HasShutdownStarted) { // Free the overlapped object. if (_ptrNativeOverlapped != null && !_ptrNativeOverlapped.IsInvalid) { _ptrNativeOverlapped.Dispose(); _ptrNativeOverlapped = null; } // Free the preallocated overlapped object. This in turn will unpin // any pinned buffers. if (_preAllocatedOverlapped != null) { _preAllocatedOverlapped.Dispose(); _preAllocatedOverlapped = null; _pinState = PinState.None; _pinnedAcceptBuffer = null; _pinnedSingleBuffer = null; _pinnedSingleBufferOffset = 0; _pinnedSingleBufferCount = 0; } // Free any allocated GCHandles. if (_socketAddressGCHandle.IsAllocated) { _socketAddressGCHandle.Free(); _pinnedSocketAddress = null; } if (_wsaMessageBufferGCHandle.IsAllocated) { _wsaMessageBufferGCHandle.Free(); _ptrWSAMessageBuffer = IntPtr.Zero; } if (_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated) { _wsaRecvMsgWSABufferArrayGCHandle.Free(); _ptrWSARecvMsgWSABufferArray = IntPtr.Zero; } if (_controlBufferGCHandle.IsAllocated) { _controlBufferGCHandle.Free(); _ptrControlBuffer = IntPtr.Zero; } } } // Sets up an Overlapped object with either _buffer or _acceptBuffer pinned. unsafe private void SetupOverlappedSingle(bool pinSingleBuffer) { // Pin buffer, get native pointers, and fill in WSABuffer descriptor. if (pinSingleBuffer) { if (_buffer != null) { _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _buffer); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, non-null buffer: " + LoggingHash.HashString(_preAllocatedOverlapped)); } _pinnedSingleBuffer = _buffer; _pinnedSingleBufferOffset = _offset; _pinnedSingleBufferCount = _count; _ptrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, _offset); _ptrAcceptBuffer = IntPtr.Zero; _wsaBuffer.Pointer = _ptrSingleBuffer; _wsaBuffer.Length = _count; _pinState = PinState.SingleBuffer; } else { _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, null); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, null buffer: " + LoggingHash.HashString(_preAllocatedOverlapped)); } _pinnedSingleBuffer = null; _pinnedSingleBufferOffset = 0; _pinnedSingleBufferCount = 0; _ptrSingleBuffer = IntPtr.Zero; _ptrAcceptBuffer = IntPtr.Zero; _wsaBuffer.Pointer = _ptrSingleBuffer; _wsaBuffer.Length = _count; _pinState = PinState.NoBuffer; } } else { _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _acceptBuffer); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=false: " + LoggingHash.HashString(_preAllocatedOverlapped)); } _pinnedAcceptBuffer = _acceptBuffer; _ptrAcceptBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_acceptBuffer, 0); _ptrSingleBuffer = IntPtr.Zero; _pinState = PinState.SingleAcceptBuffer; } } // Sets up an Overlapped object with multiple buffers pinned. unsafe private void SetupOverlappedMultiple() { ArraySegment<byte>[] tempList = new ArraySegment<byte>[_bufferList.Count]; _bufferList.CopyTo(tempList, 0); // Number of things to pin is number of buffers. // Ensure we have properly sized object array. if (_objectsToPin == null || (_objectsToPin.Length != tempList.Length)) { _objectsToPin = new object[tempList.Length]; } // Fill in object array. for (int i = 0; i < (tempList.Length); i++) { _objectsToPin[i] = tempList[i].Array; } if (_wsaBufferArray == null || _wsaBufferArray.Length != tempList.Length) { _wsaBufferArray = new WSABuffer[tempList.Length]; } // Pin buffers and fill in WSABuffer descriptor pointers and lengths. _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedMultiple: new PreAllocatedOverlapped." + LoggingHash.HashString(_preAllocatedOverlapped)); } for (int i = 0; i < tempList.Length; i++) { ArraySegment<byte> localCopy = tempList[i]; RangeValidationHelpers.ValidateSegment(localCopy); _wsaBufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array, localCopy.Offset); _wsaBufferArray[i].Length = localCopy.Count; } _pinState = PinState.MultipleBuffer; } // Sets up an Overlapped object for SendPacketsAsync. unsafe private void SetupOverlappedSendPackets() { int index; // Alloc native descriptor. _sendPacketsDescriptor = new Interop.Winsock.TransmitPacketsElement[_sendPacketsElementsFileCount + _sendPacketsElementsBufferCount]; // Number of things to pin is number of buffers + 1 (native descriptor). // Ensure we have properly sized object array. if (_objectsToPin == null || (_objectsToPin.Length != _sendPacketsElementsBufferCount + 1)) { _objectsToPin = new object[_sendPacketsElementsBufferCount + 1]; } // Fill in objects to pin array. Native descriptor buffer first and then user specified buffers. _objectsToPin[0] = _sendPacketsDescriptor; index = 1; foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null && spe._buffer != null && spe._count > 0) { _objectsToPin[index] = spe._buffer; index++; } } // Pin buffers. _preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin); if (GlobalLog.IsEnabled) { GlobalLog.Print( "SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSendPackets: new PreAllocatedOverlapped: " + LoggingHash.HashString(_preAllocatedOverlapped)); } // Get pointer to native descriptor. _ptrSendPacketsDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(_sendPacketsDescriptor, 0); // Fill in native descriptor. int descriptorIndex = 0; int fileIndex = 0; foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null) { if (spe._buffer != null && spe._count > 0) { // This element is a buffer. _sendPacketsDescriptor[descriptorIndex].buffer = Marshal.UnsafeAddrOfPinnedArrayElement(spe._buffer, spe._offset); _sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count; _sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags; descriptorIndex++; } else if (spe._filePath != null) { // This element is a file. _sendPacketsDescriptor[descriptorIndex].fileHandle = _sendPacketsFileHandles[fileIndex].DangerousGetHandle(); _sendPacketsDescriptor[descriptorIndex].fileOffset = spe._offset; _sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count; _sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags; fileIndex++; descriptorIndex++; } } } _pinState = PinState.SendPackets; } internal void LogBuffer(int size) { switch (_pinState) { case PinState.SingleAcceptBuffer: SocketsEventSource.Dump(_acceptBuffer, 0, size); break; case PinState.SingleBuffer: SocketsEventSource.Dump(_buffer, _offset, size); break; case PinState.MultipleBuffer: foreach (WSABuffer wsaBuffer in _wsaBufferArray) { SocketsEventSource.Dump(wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size)); if ((size -= wsaBuffer.Length) <= 0) { break; } } break; default: break; } } internal void LogSendPacketsBuffers(int size) { foreach (SendPacketsElement spe in _sendPacketsElementsInternal) { if (spe != null) { if (spe._buffer != null && spe._count > 0) { // This element is a buffer. SocketsEventSource.Dump(spe._buffer, spe._offset, Math.Min(spe._count, size)); } else if (spe._filePath != null) { // This element is a file. SocketsEventSource.Log.NotLoggedFile(spe._filePath, LoggingHash.HashInt(_currentSocket), _completedOperation); } } } } private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress) { SocketError socketError; IntPtr localAddr; int localAddrLength; IntPtr remoteAddr; try { _currentSocket.GetAcceptExSockaddrs( _ptrSingleBuffer != IntPtr.Zero ? _ptrSingleBuffer : _ptrAcceptBuffer, _count != 0 ? _count - _acceptAddressBufferCount : 0, _acceptAddressBufferCount / 2, _acceptAddressBufferCount / 2, out localAddr, out localAddrLength, out remoteAddr, out remoteSocketAddress.InternalSize ); Marshal.Copy(remoteAddr, remoteSocketAddress.Buffer, 0, remoteSocketAddress.Size); // Set the socket context. IntPtr handle = _currentSocket.SafeHandle.DangerousGetHandle(); socketError = Interop.Winsock.setsockopt( _acceptSocket.SafeHandle, SocketOptionLevel.Socket, SocketOptionName.UpdateAcceptContext, ref handle, Marshal.SizeOf(handle)); if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } } catch (ObjectDisposedException) { socketError = SocketError.OperationAborted; } return socketError; } private SocketError FinishOperationConnect() { SocketError socketError; // Update the socket context. try { socketError = Interop.Winsock.setsockopt( _currentSocket.SafeHandle, SocketOptionLevel.Socket, SocketOptionName.UpdateConnectContext, null, 0); if (socketError == SocketError.SocketError) { socketError = SocketPal.GetLastSocketError(); } } catch (ObjectDisposedException) { socketError = SocketError.OperationAborted; } return socketError; } private unsafe int GetSocketAddressSize() { return *(int*)_ptrSocketAddressBufferSize; } private unsafe void FinishOperationReceiveMessageFrom() { IPAddress address = null; Interop.Winsock.WSAMsg* PtrMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0); if (_controlBuffer.Length == s_controlDataSize) { // IPv4. Interop.Winsock.ControlData controlData = Marshal.PtrToStructure<Interop.Winsock.ControlData>(PtrMessage->controlBuffer.Pointer); if (controlData.length != UIntPtr.Zero) { address = new IPAddress((long)controlData.address); } _receiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.None), (int)controlData.index); } else if (_controlBuffer.Length == s_controlDataIPv6Size) { // IPv6. Interop.Winsock.ControlDataIPv6 controlData = Marshal.PtrToStructure<Interop.Winsock.ControlDataIPv6>(PtrMessage->controlBuffer.Pointer); if (controlData.length != UIntPtr.Zero) { address = new IPAddress(controlData.address); } _receiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.IPv6None), (int)controlData.index); } else { // Other. _receiveMessageFromPacketInfo = new IPPacketInformation(); } } private void FinishOperationSendPackets() { // Close the files if open. if (_sendPacketsFileStreams != null) { for (int i = 0; i < _sendPacketsElementsFileCount; i++) { // Drop handles. _sendPacketsFileHandles[i] = null; // Close any open streams. if (_sendPacketsFileStreams[i] != null) { _sendPacketsFileStreams[i].Dispose(); _sendPacketsFileStreams[i] = null; } } } _sendPacketsFileStreams = null; _sendPacketsFileHandles = null; } private unsafe void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { #if DEBUG GlobalLog.SetThreadSource(ThreadKinds.CompletionPort); using (GlobalLog.SetThreadKind(ThreadKinds.System)) { if (GlobalLog.IsEnabled) { GlobalLog.Enter( "CompletionPortCallback", "errorCode: " + errorCode + ", numBytes: " + numBytes + ", overlapped#" + ((IntPtr)nativeOverlapped).ToString("x")); } #endif SocketFlags socketFlags = SocketFlags.None; SocketError socketError = (SocketError)errorCode; // This is the same NativeOverlapped* as we already have a SafeHandle for, re-use the original. Debug.Assert((IntPtr)nativeOverlapped == _ptrNativeOverlapped.DangerousGetHandle(), "Handle mismatch"); if (socketError == SocketError.Success) { FinishOperationSuccess(socketError, (int)numBytes, socketFlags); } else { if (socketError != SocketError.OperationAborted) { if (_currentSocket.CleanedUp) { socketError = SocketError.OperationAborted; } else { try { // The Async IO completed with a failure. // here we need to call WSAGetOverlappedResult() just so Marshal.GetLastWin32Error() will return the correct error. bool success = Interop.Winsock.WSAGetOverlappedResult( _currentSocket.SafeHandle, _ptrNativeOverlapped, out numBytes, false, out socketFlags); socketError = SocketPal.GetLastSocketError(); } catch { // _currentSocket.CleanedUp check above does not always work since this code is subject to race conditions. socketError = SocketError.OperationAborted; } } } FinishOperationAsyncFailure(socketError, (int)numBytes, socketFlags); } #if DEBUG if (GlobalLog.IsEnabled) { GlobalLog.Leave("CompletionPortCallback"); } } #endif } } }
/// QAS Pro Web > (c) Experian > www.edq.com /// Intranet > Rapid Addressing > Standard > RapidSearch /// Main searching dialog, perform searching commands namespace Experian.Qas.Prowebintegration { using System; using System.Web; using System.Web.UI.WebControls; using Experian.Qas.Proweb; /// <summary> /// Intranet > Rapid Addressing > Standard > Full QAS searching with hierarchical picklists /// Perform searching, display the list of results, respond to actions, go to the format address page /// /// Main actions: /// - Initialise: arriving from calling window /// - Recreate: arriving from next (formatted address) page /// - New search, fresh search, step back: caused by click/change to page controls /// - Main search: text has been submitted for a non-dynamic search /// - Step in: picklist item containing a sub-picklist has been clicked /// - Format: picklist item containing a final address has been clicked /// /// This page is based on RapidBasePage, which provides functionality common to the scenario /// </summary> public partial class RapidSearch : RapidBasePage { /** Page members **/ // Current picklist, to display protected Picklist m_Picklist = null; // Are we at the initial search stage? private bool m_bInitial; // Is searching dynamic (responds to individual key presses) private bool m_bDynamic = true; // Current Data ID private string m_sDataID = ""; // Page controls /** Methods **/ /// <summary> /// Pick up values transfered from other pages /// </summary> override protected void Page_Load(object sender, System.EventArgs e) { base.Page_Load(sender, e); DataID = Request.Form[Constants.FIELD_DATA_ID]; if ( DataID == "" ) { DataID = StoredDataID; } else { StoredDataID = DataID; } // Load datasets from server if ( StoredDataMapList == null ) { try { m_atDatasets = AddressLookup.GetAllDatasets(); StoredDataMapList = m_atDatasets; } catch( Exception x ) { GoErrorPage(x); } } else { m_atDatasets = StoredDataMapList; } PopulateDatasets(); if ( country.Items.Count > 0 && m_sDataID.Length > 0 ) { country.SelectedValue = m_sDataID; } m_bInitial = (m_aHistory.Count == 0); if (!IsPostBack) { // Pick up values from outer/other pages StoredCallback = Request[FIELD_CALLBACK]; SearchEngine = StoredSearchEngine; StepBackRecreate(); } // Else leave it to the event handlers (New, Back, Change engine/country, Hyperlink commands) } protected void PopulateDatasets() { // Populate drop down list of countries country.Items.Clear(); country.Attributes.CssStyle["width"] = SELECT_WIDTH; ListItem itemheader1 = new ListItem("-- Datamaps Available --", ""); itemheader1.Attributes["class"] = "heading"; country.Items.Add(itemheader1); string sDatamapName; foreach (Dataset dset in m_atDatasets) { sDatamapName = dset.Name; if (sDatamapName.Length > MAX_DATAMAP_NAME_LENGTH) { sDatamapName = sDatamapName.Substring(0, MAX_DATAMAP_NAME_LENGTH - 3) + "..."; } ListItem litem = new ListItem(sDatamapName, dset.ID); country.Items.Add(litem); } ListItem itemheader2 = new ListItem("-- Other --", ""); itemheader2.Attributes["class"] = "heading"; country.Items.Add(itemheader2); foreach (Dataset dset in Constants.CoreCountries) { bool bDuplicate = false; foreach (Dataset serverDset in m_atDatasets) { if (serverDset.Name == dset.Name || serverDset.ID == dset.ID) { bDuplicate = true; break; } } if (!bDuplicate) { sDatamapName = dset.Name; if (sDatamapName.Length > MAX_DATAMAP_NAME_LENGTH) { sDatamapName = sDatamapName.Substring(0, MAX_DATAMAP_NAME_LENGTH - 3) + "..."; } ListItem litem = new ListItem(sDatamapName, dset.ID); country.Items.Add(litem); } } if (DataID.Length > 0) { country.SelectedValue = m_sDataID; } else { country.SelectedIndex = 1; DataID = country.SelectedValue; } } /// <summary> /// Update page controls prior to drawing /// </summary> protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ButtonBack.Disabled = (IsInitialSearch); // Submit button is titled 'Select' except for non-dynamic page ('Search') SearchButton = (IsSearchDynamic) ? "Select" : "Search"; /* // Prevent clicking on current engine from firing an event if ( RadioTypedown.Checked ) { RadioTypedown.Attributes["onclick"] = "return false;"; } if ( RadioSingleline.Checked ) { RadioSingleline.Attributes["onclick"] = "return false;"; } if ( RadioKeyfinder.Checked ) { RadioKeyfinder.Attributes["onclick"] = "return false;"; } */ if (m_Picklist != null) { TotalMatches = m_Picklist.Total; Moniker = m_Picklist.Moniker; Prompt = m_Picklist.Prompt; } } /// <summary> /// Start a new search - initialise/blank values /// </summary> protected void NewSearch() { SearchString = ""; ResetWarningMessage(); m_aHistory.Clear(); // Start new search indirectly, through StepBackRecreate StepBackRecreate(); } /// <summary> /// Start a new search, but retrieve the search string from the history top /// </summary> protected void FreshSearch() { // Cut down history - to keep just initial search string for new search m_aHistory.Truncate(1); ResetWarningMessage(); StepBackRecreate(); } /// <summary> /// Grab details from the history and recreate the previous picklist, or start a new one /// </summary> protected void StepBackRecreate() { ResetWarningMessage(); if (m_aHistory.Count > 0) { // Grab search text from the last history entry SearchString = m_aHistory.Peek().Refine; m_aHistory.Pop(); } if (m_aHistory.Count > 0) { // Recreate last picklist shown Moniker = m_aHistory.Peek().Moniker; StepinSearch(); } else { // Otherwise start a new searc InitialSearch(); } } /// <summary> /// Perform search initialisation - check availability and perform initial dynamic search /// </summary> protected void InitialSearch() { CanSearch result = null; try { // Perform a pre-search check, to ensure user can proceed all the way to getting a formatted address AddressLookup.CurrentEngine.EngineType = SearchEngine; StoredSearchEngine = SearchEngine; AddressLookup.CurrentEngine.Flatten = false; result = AddressLookup.CanSearch(DataID, GetLayout(), null); if (result.IsOk) { // Get initial prompt PromptSet prompts = AddressLookup.GetPromptSet(DataID, PromptSet.Types.Default); IsSearchDynamic = prompts.IsDynamic; m_aHistory.Clear(); if (IsSearchDynamic) { m_Picklist = AddressLookup.Search(DataID, SearchString, PromptSet.Types.Default, GetLayout()).Picklist; } else { TotalMatches = 0; Moniker = ""; string thePrompt = ""; foreach (PromptLine line in prompts.Lines) { thePrompt = thePrompt + line.Prompt + " "; } Prompt = thePrompt; } } } catch (Exception x) { GoErrorPage(x); } if (!result.IsOk) { GoErrorPage(Constants.Routes.PreSearchFailed, result.ErrorMessage); } // else: Display results picklist: done by page } /// <summary> /// Perform a submitted non-dynamic search, handling auto-step in and format /// </summary> protected void SubmitSearch() { // Step in all the way to the final address page? bool bFinalAddress = false; StepinWarnings eWarn = StepinWarnings.None; try { // Perform initial static (Singleline) search AddressLookup.CurrentEngine.EngineType = SearchEngine; m_Picklist = AddressLookup.Search(DataID, SearchString, PromptSet.Types.Default, GetLayout()).Picklist; Moniker = m_Picklist.Moniker; // Initialise the history m_aHistory.Clear(); m_aHistory.Push(Moniker, "Searching on... '" + SearchString + "'", "", "", SearchString); SearchString = ""; // Auto-step-in logic AutoStep(ref bFinalAddress, ref eWarn); } catch (Exception x) { GoErrorPage(x); } if (bFinalAddress) { // Display final formatted address GoFormatPage(DataID, SearchEngine, Moniker, eWarn); } // else: Display results picklist: done by page } /// <summary> /// Step in to a picklist item / Recreate picklist /// </summary> protected void StepinSearch() { // Step in all the way to the final address page? bool bFinalAddress = false; StepinWarnings eWarn = StepinWarnings.None; try { // Get picklist: step-in/recreate from Moniker m_Picklist = AddressLookup.Refine(Moniker, SearchString, GetLayout()); // Special case: initial (dynamic searching) step-in can require auto-step-in if (m_bInitial) { AutoStep(ref bFinalAddress, ref eWarn); } } catch (Exception x) { GoErrorPage(x); } if (bFinalAddress) { // Display final formatted address GoFormatPage(DataID, SearchEngine, Moniker, eWarn); } // else: Display results picklist: done by page } /** Helper methods **/ /// <summary> /// Automatically step through picklists which do not need to be displayed /// </summary> /// <param name="bFinalAddress">Step in all the way to the final address page?</param> /// <param name="eWarn">Any warnings associated with picklists we've stepped through</param> protected void AutoStep(ref bool bFinalAddress, ref StepinWarnings eWarn) { // Remember warnings caused by auto-stepping through picklist items: bool bStepPastClose = false; // have we auto-stepped past close matches? bool bCrossBorder = false; // have we auto-stepped through a cross-border warning? bool bPostcodeRecode = false; // have we auto-stepped through a postcode recode? try { // Auto-step-in logic while (m_Picklist.IsAutoStepinSafe || m_Picklist.IsAutoStepinPastClose) { Moniker = m_Picklist.PicklistItems[0].Moniker; bStepPastClose = bStepPastClose || m_Picklist.IsAutoStepinPastClose; bCrossBorder = bCrossBorder || m_Picklist.PicklistItems[0].IsCrossBorderMatch; bPostcodeRecode = bPostcodeRecode || m_Picklist.PicklistItems[0].IsPostcodeRecoded; // Add this step-in to history m_aHistory.Push(m_Picklist.PicklistItems[0]); // Auto-step into first item m_Picklist = AddressLookup.StepIn(Moniker, GetLayout()); } // Auto-formatting logic if (m_Picklist.IsAutoFormatSafe || m_Picklist.IsAutoFormatPastClose) { Moniker = m_Picklist.PicklistItems[0].Moniker; bStepPastClose = bStepPastClose || m_Picklist.IsAutoFormatPastClose; bCrossBorder = bCrossBorder || m_Picklist.PicklistItems[0].IsCrossBorderMatch; bPostcodeRecode = bPostcodeRecode || m_Picklist.PicklistItems[0].IsPostcodeRecoded; // Add this step-in to history m_aHistory.Push(m_Picklist.PicklistItems[0]); // Go straight to formatted address page bFinalAddress = true; } } catch (Exception x) { GoErrorPage(x); } // Convert flags into a single step-in warning enumeration eWarn = AsWarning(bStepPastClose, bCrossBorder, bPostcodeRecode); SetWarningMessage(eWarn); } /// <summary> /// Return the warning enumeration based on properties of the picklist item stepped through /// </summary> /// <param name="bStepPastClose">Have we stepped past close matches</param> /// <param name="bCrossBorder">Is this item a match in a different locality to the entered search</param> /// <param name="bPostcodeRecode">Is this item's postcode a recode of the entered search</param> protected static StepinWarnings AsWarning(bool bStepPastClose, bool bCrossBorder, bool bPostcodeRecode) { if (bStepPastClose) { return StepinWarnings.CloseMatches; } else if (bCrossBorder) { return StepinWarnings.CrossBorder; } else if (bPostcodeRecode) { return StepinWarnings.PostcodeRecode; } else { return StepinWarnings.None; } } /// <summary> /// Update the warning message displayed in the status bar, depending on preceding step-in /// </summary> /// <param name="eWarn">Warning enumeration</param> private void SetWarningMessage(StepinWarnings eWarn) { // Set the step-in message depending on the warning switch (eWarn) { case StepinWarnings.CloseMatches: infoStatus.InnerHtml = "There are also close matches available &#8211; click <a href=\"javascript:stepBack();\">back</a> to see them"; statusData.Attributes["class"] += " message"; break; case StepinWarnings.CrossBorder: infoStatus.InnerHtml = "Address selected is outside of the entered locality"; statusData.Attributes["class"] += " message"; break; case StepinWarnings.PostcodeRecode: infoStatus.InnerHtml = "Postal code has been updated by the Postal Authority"; statusData.Attributes["class"] += " message"; break; default: ResetWarningMessage(); break; } } private void ResetWarningMessage() { // Clear any warning info infoStatus.InnerHtml = "&nbsp;"; statusData.Attributes["Class"] = "status"; StoredWarning = StepinWarnings.None; } /// <summary> /// Write the picklist history as table rows, indenting as you go /// </summary> protected void RenderHistory() { if (m_aHistory.Count > 0) { Response.Write("<table class=\"history picklist\">\n"); for (int i = 0; i < m_aHistory.Count; i++) { string sIndent = "indent" + i.ToString(); string sText = Server.HtmlEncode(m_aHistory[i].Text); Response.Write("<tr class=\"picklist\">"); Response.Write("<td class=\"pickitem opened " + sIndent + "\"><a href=\"javascript:stepBack();\" tabindex=\"-1\"><div>" + sText + "</div></a></td>"); Response.Write("<td class=\"postcode\">" + m_aHistory[i].Postcode + "</td>"); Response.Write("<td class=\"score\">" + m_aHistory[i].Score + "</td>"); Response.Write("</tr>\n"); } Response.Write("</table>"); } } /** Page events **/ #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() { } #endregion /// <summary> /// 'New' button clicked: start a new blank search /// </summary> protected void ButtonNew_ServerClick(object sender, System.EventArgs e) { NewSearch(); } /// <summary> /// 'Back' button clicked: display last picklist shown /// </summary> protected void ButtonBack_ServerClick(object sender, System.EventArgs e) { StepBackRecreate(); } /// <summary> /// Search engine changed: start a fresh search (retain initial search string) /// </summary> protected void RadioEngine_Changed(object sender, System.EventArgs e) { FreshSearch(); } /// <summary> /// Country database changed: start a fresh search (retain initial search string) /// </summary> protected void country_SelectedIndexChanged(object sender, System.EventArgs e) { FreshSearch(); } /// <summary> /// 'Search' button clicked: perform a non-dynamic search /// </summary> protected void ButtonSearch_ServerClick(object sender, System.EventArgs e) { SubmitSearch(); } /// <summary> /// Final address picklistitem hyperlink hit: format the selected picklist item /// </summary> protected void ActionFormat_Click(object sender, System.EventArgs e) { // Add this step-in to history m_aHistory.Push(Moniker, PickText, PickPostcode, PickScore, SearchString); // Transfer to the formatting page GoFormatPage(DataID, SearchEngine, Moniker, StepinWarning); } /// <summary> /// Multiple address picklistitem hyperlink hit: step in to the selected picklist item /// </summary> protected void ActionStepIn_Click(object sender, System.EventArgs e) { // Add this step-in to history m_aHistory.Push(Moniker, PickText, PickPostcode, PickScore, SearchString); // Stepping in, so clear refine text UNLESS it was an informational (i.e. 'Click to Show All') if (!StepinWarning.Equals(StepinWarnings.Info)) { SearchString = ""; } // Display warnings from item selected SetWarningMessage(StepinWarning); // Perform step-in StepinSearch(); } /** Page controls **/ /// Country data identifier (i.e. AUS) protected string DataID { get { if (m_sDataID == null) { return ""; } return m_sDataID; } set { if (value == null) { m_sDataID = ""; } else { m_sDataID = value; } } } /// Whether auto-complete should be enabled in the browser protected string IsAutoComplete { get { return m_bDynamic ? "off" : "on"; } } /// Whether this is an initial search (no history yet): affects selection of search terms text box protected bool IsInitialSearch { get { return (m_aHistory.Count == 0); } } /// Whether we are searching dynamically (updating picklist as you type) protected bool IsSearchDynamic { get { return m_bDynamic; } set { m_bDynamic = value; } } /// Page control: update match count shown in div private int TotalMatches { set { matchCount.InnerText = (value >= 9999) ? "Too many" : "Matches: " + value.ToString(); } } /// Moniker of the picklist item selected (set by browser Javascript) protected string Moniker { get { return HttpUtility.HtmlDecode(HiddenMoniker.Value); } set { HiddenMoniker.Value = value; } } /// Postcode of the picklist item selected (set by browser Javascript) private string PickPostcode { get { return HttpUtility.HtmlDecode(HiddenPostcode.Value); } } /// Score of the picklist item selected (set by browser Javascript) private string PickScore { get { return HttpUtility.HtmlDecode(HiddenScore.Value); } } /// Display text of the picklist item selected (set by browser Javascript) private string PickText { get { return HttpUtility.HtmlDecode(HiddenPickText.Value); } } /// Page control: update the searching prompt private string Prompt { set { LabelPrompt.Text = value; } } /// Search engine selected private Engine.EngineTypes SearchEngine { get { if (RadioSingleline.Checked) { return Engine.EngineTypes.Singleline; } if (RadioTypedown.Checked) { return Engine.EngineTypes.Typedown; } if (RadioKeyfinder.Checked) { return Engine.EngineTypes.Keyfinder; } return Engine.EngineTypes.Singleline; } set { RadioSingleline.Checked = (value == Engine.EngineTypes.Singleline); RadioTypedown.Checked = (value == Engine.EngineTypes.Typedown); RadioKeyfinder.Checked = (value == Engine.EngineTypes.Keyfinder); StoredSearchEngine = value; } } /// Title of the Search button private string SearchButton { set { ButtonSearch.Value = value; } } /// Search/refinement terms protected string SearchString { get { return HttpUtility.HtmlDecode(searchText.Text); } set { searchText.Text = value; } } /// Warning relating to the picklist item selected (set by browser Javascript) private StepinWarnings StepinWarning { get { string sValue = HiddenWarning.Value; return (sValue != null) ? (StepinWarnings) Enum.Parse(typeof(StepinWarnings), sValue) : StepinWarnings.None; } } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Log.DestinationArcSightBinding", Namespace="urn:iControl")] public partial class LogDestinationArcSight : iControlInterface { public LogDestinationArcSight() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationArcSight", RequestNamespace="urn:iControl:Log/DestinationArcSight", ResponseNamespace="urn:iControl:Log/DestinationArcSight")] public void create( string [] destinations, string [] forwarding_destinations ) { this.Invoke("create", new object [] { destinations, forwarding_destinations}); } public System.IAsyncResult Begincreate(string [] destinations,string [] forwarding_destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { destinations, forwarding_destinations}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_arcsight_destinations //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationArcSight", RequestNamespace="urn:iControl:Log/DestinationArcSight", ResponseNamespace="urn:iControl:Log/DestinationArcSight")] public void delete_all_arcsight_destinations( ) { this.Invoke("delete_all_arcsight_destinations", new object [0]); } public System.IAsyncResult Begindelete_all_arcsight_destinations(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_arcsight_destinations", new object[0], callback, asyncState); } public void Enddelete_all_arcsight_destinations(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_arcsight_destination //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationArcSight", RequestNamespace="urn:iControl:Log/DestinationArcSight", ResponseNamespace="urn:iControl:Log/DestinationArcSight")] public void delete_arcsight_destination( string [] destinations ) { this.Invoke("delete_arcsight_destination", new object [] { destinations}); } public System.IAsyncResult Begindelete_arcsight_destination(string [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_arcsight_destination", new object[] { destinations}, callback, asyncState); } public void Enddelete_arcsight_destination(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationArcSight", RequestNamespace="urn:iControl:Log/DestinationArcSight", ResponseNamespace="urn:iControl:Log/DestinationArcSight")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] destinations ) { object [] results = this.Invoke("get_description", new object [] { destinations}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { destinations}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_forwarding_destination //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationArcSight", RequestNamespace="urn:iControl:Log/DestinationArcSight", ResponseNamespace="urn:iControl:Log/DestinationArcSight")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_forwarding_destination( string [] destinations ) { object [] results = this.Invoke("get_forwarding_destination", new object [] { destinations}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_forwarding_destination(string [] destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_forwarding_destination", new object[] { destinations}, callback, asyncState); } public string [] Endget_forwarding_destination(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationArcSight", RequestNamespace="urn:iControl:Log/DestinationArcSight", ResponseNamespace="urn:iControl:Log/DestinationArcSight")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationArcSight", RequestNamespace="urn:iControl:Log/DestinationArcSight", ResponseNamespace="urn:iControl:Log/DestinationArcSight")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationArcSight", RequestNamespace="urn:iControl:Log/DestinationArcSight", ResponseNamespace="urn:iControl:Log/DestinationArcSight")] public void set_description( string [] destinations, string [] descriptions ) { this.Invoke("set_description", new object [] { destinations, descriptions}); } public System.IAsyncResult Beginset_description(string [] destinations,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { destinations, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_forwarding_destination //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Log/DestinationArcSight", RequestNamespace="urn:iControl:Log/DestinationArcSight", ResponseNamespace="urn:iControl:Log/DestinationArcSight")] public void set_forwarding_destination( string [] destinations, string [] forwarding_destinations ) { this.Invoke("set_forwarding_destination", new object [] { destinations, forwarding_destinations}); } public System.IAsyncResult Beginset_forwarding_destination(string [] destinations,string [] forwarding_destinations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_forwarding_destination", new object[] { destinations, forwarding_destinations}, callback, asyncState); } public void Endset_forwarding_destination(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= }
//#define Trace // ParallelBZip2OutputStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2011 Dino Chiesa. // 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: <2011-August-02 16:44:24> // // ------------------------------------------------------------------ // // This module defines the ParallelBZip2OutputStream class, which is a // BZip2 compressing stream. This code was derived in part from Apache // commons source code. The license below applies to the original Apache // code. // // ------------------------------------------------------------------ // flymake: csc.exe /t:module BZip2InputStream.cs BZip2Compressor.cs Rand.cs BCRC32.cs @@FILE@@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ // Design Notes: // // This class follows the classic Decorator pattern: it is a Stream that // wraps itself around a Stream, and in doing so provides bzip2 // compression as callers Write into it. It is exactly the same in // outward function as the BZip2OutputStream, except that this class can // perform compression using multiple independent threads. Because of // that, and because of the CPU-intensive nature of BZip2 compression, // this class can perform significantly better (in terms of wall-click // time) than the single-threaded variant, at the expense of memory and // CPU utilization. // // BZip2 is a straightforward data format: there are 4 magic bytes at // the top of the file, followed by 1 or more compressed blocks. There // is a small "magic byte" trailer after all compressed blocks. // // In concept parallelizing BZip2 is simple: do the CPU-intensive // compression for each block in a separate thread, then emit the // compressed output, in order, to the output stream. Each block can be // compressed independently, so a block is the natural candidate for the // parcel of work that can be passed to an independent worker thread. // // The design approach used here is simple: within the Write() method of // the stream, fill a block. When the block is full, pass it to a // background worker thread for compression. When the compressor thread // completes its work, the main thread (the application thread that // calls Write()) can send the compressed data to the output stream, // being careful to respect the order of the compressed blocks. // // The challenge of ordering the compressed data is a solved and // well-understood problem - it is the same approach here as DotNetZip // uses in the ParallelDeflateOutputStream. It is a map/reduce approach // in design intent. // // One new twist for BZip2 is that the compressor output is not // byte-aligned. In other words the final output of a compressed block // will in general be a number of bits that is not a multiple of // 8. Therefore, combining the ordered results of the N compressor // threads requires additional byte-shredding by the parent // stream. Hence this stream uses a BitWriter to adapt bit-oriented // BZip2 output to the byte-oriented .NET Stream. // // The approach used here creates N instances of the BZip2Compressor // type, where N is governed by the number of cores (cpus) and limited // by the MaxWorkers property exposed by this class. Each // BZip2Compressor instance gets its own MemoryStream, to which it // writes its data, via a BitWriter. // // along with the bit accumulator described above. The MemoryStream // would gather the byte-aligned compressed output of the compressor. // When reducing the output of the various workers, this class must // again do the byte-shredding thing. The data from the compressors is // therefore shredded twice: once when being placed into the // MemoryStream, and again when emitted into the final output stream // that this class decorates. This is an unfortunate and seemingly // unavoidable inefficiency. Two rounds of byte-shredding will use more // CPU than we'd like, but I haven't imagined a way to avoid it. // // The BZip2Compressor is designed to write directly into the parent // stream's accumulator (BitWriter) when possible, and write into a // distinct BitWriter when necessary. The former can be used in a // single-thread scenario, while the latter is required in a // multi-thread scenario. // // ---- // // Regarding the Apache code base: Most of the code in this particular // class is related to stream operations and thread synchronization, and // is my own code. It largely does not rely on any code obtained from // Apache commons. If you compare this code with the Apache commons // BZip2OutputStream, you will see very little code that is common, // except for the nearly-boilerplate structure that is common to all // subtypes of System.IO.Stream. There may be some small remnants of // code in this module derived from the Apache stuff, which is why I // left the license in here. Most of the Apache commons compressor magic // has been ported into the BZip2Compressor class. // using System; using System.IO; using System.Collections.Generic; using System.Threading; namespace Ionic.BZip2 { internal class WorkItem { public int index; public BZip2Compressor Compressor { get; private set; } public MemoryStream ms; public int ordinal; public BitWriter bw; public WorkItem(int ix, int blockSize) { // compressed data gets written to a MemoryStream this.ms = new MemoryStream(); this.bw = new BitWriter(ms); this.Compressor = new BZip2Compressor(bw, blockSize); this.index = ix; } } /// <summary> /// A write-only decorator stream that compresses data as it is /// written using the BZip2 algorithm. This stream compresses by /// block using multiple threads. /// </summary> /// <para> /// This class performs BZIP2 compression through writing. For /// more information on the BZIP2 algorithm, see /// <see href="http://en.wikipedia.org/wiki/BZIP2"/>. /// </para> /// /// <para> /// This class is similar to <see cref="Ionic.BZip2.BZip2OutputStream"/>, /// except that this implementation uses an approach that employs multiple /// worker threads to perform the compression. On a multi-cpu or multi-core /// computer, the performance of this class can be significantly higher than /// the single-threaded BZip2OutputStream, particularly for larger streams. /// How large? Anything over 10mb is a good candidate for parallel /// compression. /// </para> /// /// <para> /// The tradeoff is that this class uses more memory and more CPU than the /// vanilla <c>BZip2OutputStream</c>. Also, for small files, the /// <c>ParallelBZip2OutputStream</c> can be much slower than the vanilla /// <c>BZip2OutputStream</c>, because of the overhead associated to using the /// thread pool. /// </para> /// /// <seealso cref="Ionic.BZip2.BZip2OutputStream" /> public class ParallelBZip2OutputStream : System.IO.Stream { private static readonly int BufferPairsPerCore = 4; private int _maxWorkers; private bool firstWriteDone; private int lastFilled; private int lastWritten; private int latestCompressed; private int currentlyFilling; private volatile Exception pendingException; private bool handlingException; private bool emitting; private System.Collections.Generic.Queue<int> toWrite; private System.Collections.Generic.Queue<int> toFill; private System.Collections.Generic.List<WorkItem> pool; private object latestLock = new object(); private object eLock = new object(); // for exceptions private object outputLock = new object(); // for multi-thread output private AutoResetEvent newlyCompressedBlob; long totalBytesWrittenIn; long totalBytesWrittenOut; bool leaveOpen; uint combinedCRC; Stream output; BitWriter bw; int blockSize100k; // 0...9 private TraceBits desiredTrace = TraceBits.Crc | TraceBits.Write; /// <summary> /// Constructs a new <c>ParallelBZip2OutputStream</c>, that sends its /// compressed output to the given output stream. /// </summary> /// /// <param name='output'> /// The destination stream, to which compressed output will be sent. /// </param> /// /// <example> /// /// This example reads a file, then compresses it with bzip2 file, /// and writes the compressed data into a newly created file. /// /// <code> /// var fname = "logfile.log"; /// using (var fs = File.OpenRead(fname)) /// { /// var outFname = fname + ".bz2"; /// using (var output = File.Create(outFname)) /// { /// using (var compressor = new Ionic.BZip2.ParallelBZip2OutputStream(output)) /// { /// byte[] buffer = new byte[2048]; /// int n; /// while ((n = fs.Read(buffer, 0, buffer.Length)) > 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// </example> public ParallelBZip2OutputStream(Stream output) : this(output, BZip2.MaxBlockSize, false) { } /// <summary> /// Constructs a new <c>ParallelBZip2OutputStream</c> with specified blocksize. /// </summary> /// <param name = "output">the destination stream.</param> /// <param name = "blockSize"> /// The blockSize in units of 100000 bytes. /// The valid range is 1..9. /// </param> public ParallelBZip2OutputStream(Stream output, int blockSize) : this(output, blockSize, false) { } /// <summary> /// Constructs a new <c>ParallelBZip2OutputStream</c>. /// </summary> /// <param name = "output">the destination stream.</param> /// <param name = "leaveOpen"> /// whether to leave the captive stream open upon closing this stream. /// </param> public ParallelBZip2OutputStream(Stream output, bool leaveOpen) : this(output, BZip2.MaxBlockSize, leaveOpen) { } /// <summary> /// Constructs a new <c>ParallelBZip2OutputStream</c> with specified blocksize, /// and explicitly specifies whether to leave the wrapped stream open. /// </summary> /// /// <param name = "output">the destination stream.</param> /// <param name = "blockSize"> /// The blockSize in units of 100000 bytes. /// The valid range is 1..9. /// </param> /// <param name = "leaveOpen"> /// whether to leave the captive stream open upon closing this stream. /// </param> public ParallelBZip2OutputStream(Stream output, int blockSize, bool leaveOpen) { if (blockSize < BZip2.MinBlockSize || blockSize > BZip2.MaxBlockSize) { var msg = String.Format("blockSize={0} is out of range; must be between {1} and {2}", blockSize, BZip2.MinBlockSize, BZip2.MaxBlockSize); throw new ArgumentException(msg, "blockSize"); } this.output = output; if (!this.output.CanWrite) throw new ArgumentException("The stream is not writable.", "output"); this.bw = new BitWriter(this.output); this.blockSize100k = blockSize; this.leaveOpen = leaveOpen; this.combinedCRC = 0; this.MaxWorkers = 16; // default EmitHeader(); } private void InitializePoolOfWorkItems() { this.toWrite = new Queue<int>(); this.toFill = new Queue<int>(); this.pool = new System.Collections.Generic.List<WorkItem>(); int nWorkers = BufferPairsPerCore * Environment.ProcessorCount; nWorkers = Math.Min(nWorkers, this.MaxWorkers); for(int i=0; i < nWorkers; i++) { this.pool.Add(new WorkItem(i, this.blockSize100k)); this.toFill.Enqueue(i); } this.newlyCompressedBlob = new AutoResetEvent(false); this.currentlyFilling = -1; this.lastFilled = -1; this.lastWritten = -1; this.latestCompressed = -1; } /// <summary> /// The maximum number of concurrent compression worker threads to use. /// </summary> /// /// <remarks> /// <para> /// This property sets an upper limit on the number of concurrent worker /// threads to employ for compression. The implementation of this stream /// employs multiple threads from the .NET thread pool, via /// ThreadPool.QueueUserWorkItem(), to compress the incoming data by /// block. As each block of data is compressed, this stream re-orders the /// compressed blocks and writes them to the output stream. /// </para> /// /// <para> /// A higher number of workers enables a higher degree of /// parallelism, which tends to increase the speed of compression on /// multi-cpu computers. On the other hand, a higher number of buffer /// pairs also implies a larger memory consumption, more active worker /// threads, and a higher cpu utilization for any compression. This /// property enables the application to limit its memory consumption and /// CPU utilization behavior depending on requirements. /// </para> /// /// <para> /// By default, DotNetZip allocates 4 workers per CPU core, subject to the /// upper limit specified in this property. For example, suppose the /// application sets this property to 16. Then, on a machine with 2 /// cores, DotNetZip will use 8 workers; that number does not exceed the /// upper limit specified by this property, so the actual number of /// workers used will be 4 * 2 = 8. On a machine with 4 cores, DotNetZip /// will use 16 workers; again, the limit does not apply. On a machine /// with 8 cores, DotNetZip will use 16 workers, because of the limit. /// </para> /// /// <para> /// For each compression "worker thread" that occurs in parallel, there is /// up to 2mb of memory allocated, for buffering and processing. The /// actual number depends on the <see cref="BlockSize"/> property. /// </para> /// /// <para> /// CPU utilization will also go up with additional workers, because a /// larger number of buffer pairs allows a larger number of background /// threads to compress in parallel. If you find that parallel /// compression is consuming too much memory or CPU, you can adjust this /// value downward. /// </para> /// /// <para> /// The default value is 16. Different values may deliver better or /// worse results, depending on your priorities and the dynamic /// performance characteristics of your storage and compute resources. /// </para> /// /// <para> /// The application can set this value at any time, but it is effective /// only before the first call to Write(), which is when the buffers are /// allocated. /// </para> /// </remarks> public int MaxWorkers { get { return _maxWorkers; } set { if (value < 4) throw new ArgumentException("MaxWorkers", "Value must be 4 or greater."); _maxWorkers = value; } } protected override void Dispose(bool disposing) { if (this.pendingException != null) { this.handlingException = true; var pe = this.pendingException; this.pendingException = null; throw pe; } if (this.handlingException) return; if (disposing) { Stream output = this.output; if (output != null) { try { FlushOutput(true); if (!leaveOpen) output.Dispose(); } finally { this.output = null; this.bw = null; } } } base.Dispose(disposing); } private void FlushOutput(bool lastInput) { if (this.emitting) return; // compress and write whatever is ready if (this.currentlyFilling >= 0) { WorkItem workitem = this.pool[this.currentlyFilling]; CompressOne(workitem); this.currentlyFilling = -1; // get a new buffer next Write() } if (lastInput) { EmitPendingBuffers(true, false); EmitTrailer(); } else { EmitPendingBuffers(false, false); } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { if (this.output != null) { FlushOutput(false); this.bw.Flush(); this.output.Flush(); } } private void EmitHeader() { var magic = new byte[] { (byte) 'B', (byte) 'Z', (byte) 'h', (byte) ('0' + this.blockSize100k) }; // not necessary to shred the initial magic bytes this.output.Write(magic, 0, magic.Length); } private void EmitTrailer() { // A magic 48-bit number, 0x177245385090, to indicate the end // of the last block. (sqrt(pi), if you want to know) TraceOutput(TraceBits.Write, "total written out: {0} (0x{0:X})", this.bw.TotalBytesWrittenOut); // must shred this.bw.WriteByte(0x17); this.bw.WriteByte(0x72); this.bw.WriteByte(0x45); this.bw.WriteByte(0x38); this.bw.WriteByte(0x50); this.bw.WriteByte(0x90); this.bw.WriteInt(this.combinedCRC); this.bw.FinishAndPad(); TraceOutput(TraceBits.Write, "final total : {0} (0x{0:X})", this.bw.TotalBytesWrittenOut); } /// <summary> /// The blocksize parameter specified at construction time. /// </summary> public int BlockSize { get { return this.blockSize100k; } } /// <summary> /// Write data to the stream. /// </summary> /// <remarks> /// /// <para> /// Use the <c>ParallelBZip2OutputStream</c> to compress data while /// writing: create a <c>ParallelBZip2OutputStream</c> with a writable /// output stream. Then call <c>Write()</c> on that /// <c>ParallelBZip2OutputStream</c>, providing uncompressed data as /// input. The data sent to the output stream will be the compressed /// form of the input data. /// </para> /// /// <para> /// A <c>ParallelBZip2OutputStream</c> can be used only for /// <c>Write()</c> not for <c>Read()</c>. /// </para> /// /// </remarks> /// /// <param name="buffer">The buffer holding data to write to the stream.</param> /// <param name="offset">the offset within that data array to find the first byte to write.</param> /// <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { bool mustWait = false; // This method does this: // 0. handles any pending exceptions // 1. write any buffers that are ready to be written // 2. fills a compressor buffer; when full, flip state to 'Filled', // 3. if more data to be written, goto step 1 if (this.output == null) throw new IOException("the stream is not open"); // dispense any exceptions that occurred on the BG threads if (this.pendingException != null) { this.handlingException = true; var pe = this.pendingException; this.pendingException = null; throw pe; } if (offset < 0) throw new IndexOutOfRangeException(String.Format("offset ({0}) must be > 0", offset)); if (count < 0) throw new IndexOutOfRangeException(String.Format("count ({0}) must be > 0", count)); if (offset + count > buffer.Length) throw new IndexOutOfRangeException(String.Format("offset({0}) count({1}) bLength({2})", offset, count, buffer.Length)); if (count == 0) return; // nothing to do if (!this.firstWriteDone) { // Want to do this on first Write, first session, and not in the // constructor. Must allow the MaxWorkers to change after // construction, but before first Write(). InitializePoolOfWorkItems(); this.firstWriteDone = true; } int bytesWritten = 0; int bytesRemaining = count; do { // may need to make buffers available EmitPendingBuffers(false, mustWait); mustWait = false; // get a compressor to fill int ix = -1; if (this.currentlyFilling >= 0) { ix = this.currentlyFilling; } else { if (this.toFill.Count == 0) { // No compressors available to fill, so... need to emit // compressed buffers. mustWait = true; continue; } ix = this.toFill.Dequeue(); ++this.lastFilled; } WorkItem workitem = this.pool[ix]; workitem.ordinal = this.lastFilled; int n = workitem.Compressor.Fill(buffer, offset, bytesRemaining); if (n != bytesRemaining) { if (!ThreadPool.QueueUserWorkItem( CompressOne, workitem )) throw new Exception("Cannot enqueue workitem"); this.currentlyFilling = -1; // will get a new buffer next time offset += n; } else this.currentlyFilling = ix; bytesRemaining -= n; bytesWritten += n; } while (bytesRemaining > 0); totalBytesWrittenIn += bytesWritten; return; } private void EmitPendingBuffers(bool doAll, bool mustWait) { // When combining parallel compression with a ZipSegmentedStream, it's // possible for the ZSS to throw from within this method. In that // case, Close/Dispose will be called on this stream, if this stream // is employed within a using or try/finally pair as required. But // this stream is unaware of the pending exception, so the Close() // method invokes this method AGAIN. This can lead to a deadlock. // Therefore, failfast if re-entering. if (emitting) return; emitting = true; if (doAll || mustWait) this.newlyCompressedBlob.WaitOne(); do { int firstSkip = -1; int millisecondsToWait = doAll ? 200 : (mustWait ? -1 : 0); int nextToWrite = -1; do { if (Monitor.TryEnter(this.toWrite, millisecondsToWait)) { nextToWrite = -1; try { if (this.toWrite.Count > 0) nextToWrite = this.toWrite.Dequeue(); } finally { Monitor.Exit(this.toWrite); } if (nextToWrite >= 0) { WorkItem workitem = this.pool[nextToWrite]; if (workitem.ordinal != this.lastWritten + 1) { // out of order. requeue and try again. lock(this.toWrite) { this.toWrite.Enqueue(nextToWrite); } if (firstSkip == nextToWrite) { // We went around the list once. // None of the items in the list is the one we want. // Now wait for a compressor to signal again. this.newlyCompressedBlob.WaitOne(); firstSkip = -1; } else if (firstSkip == -1) firstSkip = nextToWrite; continue; } firstSkip = -1; TraceOutput(TraceBits.Write, "Writing block {0}", workitem.ordinal); // write the data to the output var bw2 = workitem.bw; bw2.Flush(); // not bw2.FinishAndPad()! var ms = workitem.ms; ms.Seek(0,SeekOrigin.Begin); // cannot dump bytes!! // ms.WriteTo(this.output); // // must do byte shredding: int n; int y = -1; long totOut = 0; var buffer = new byte[1024]; while ((n = ms.Read(buffer,0,buffer.Length)) > 0) { #if Trace if (y == -1) // diagnostics only { var sb1 = new System.Text.StringBuilder(); sb1.Append("first 16 whole bytes in block: "); for (int z=0; z < 16; z++) sb1.Append(String.Format(" {0:X2}", buffer[z])); TraceOutput(TraceBits.Write, sb1.ToString()); } #endif y = n; for (int k=0; k < n; k++) { this.bw.WriteByte(buffer[k]); } totOut += n; } #if Trace TraceOutput(TraceBits.Write,"out block length (bytes): {0} (0x{0:X})", totOut); var sb = new System.Text.StringBuilder(); sb.Append("final 16 whole bytes in block: "); for (int z=0; z < 16; z++) sb.Append(String.Format(" {0:X2}", buffer[y-1-12+z])); TraceOutput(TraceBits.Write, sb.ToString()); #endif // and now any remaining bits TraceOutput(TraceBits.Write, " remaining bits: {0} 0x{1:X}", bw2.NumRemainingBits, bw2.RemainingBits); if (bw2.NumRemainingBits > 0) { this.bw.WriteBits(bw2.NumRemainingBits, bw2.RemainingBits); } TraceOutput(TraceBits.Crc," combined CRC (before): {0:X8}", this.combinedCRC); this.combinedCRC = (this.combinedCRC << 1) | (this.combinedCRC >> 31); this.combinedCRC ^= (uint) workitem.Compressor.Crc32; TraceOutput(TraceBits.Crc, " block CRC : {0:X8}", workitem.Compressor.Crc32); TraceOutput(TraceBits.Crc, " combined CRC (after) : {0:X8}", this.combinedCRC); TraceOutput(TraceBits.Write, "total written out: {0} (0x{0:X})", this.bw.TotalBytesWrittenOut); TraceOutput(TraceBits.Write | TraceBits.Crc, ""); this.totalBytesWrittenOut += totOut; bw2.Reset(); this.lastWritten = workitem.ordinal; workitem.ordinal = -1; this.toFill.Enqueue(workitem.index); // don't wait next time through if (millisecondsToWait == -1) millisecondsToWait = 0; } } else nextToWrite = -1; } while (nextToWrite >= 0); } while (doAll && (this.lastWritten != this.latestCompressed)); if (doAll) { TraceOutput(TraceBits.Crc, " combined CRC (final) : {0:X8}", this.combinedCRC); } emitting = false; } private void CompressOne(Object wi) { // compress and one buffer WorkItem workitem = (WorkItem) wi; try { // compress and write to the compressor's MemoryStream workitem.Compressor.CompressAndWrite(); lock(this.latestLock) { if (workitem.ordinal > this.latestCompressed) this.latestCompressed = workitem.ordinal; } lock (this.toWrite) { this.toWrite.Enqueue(workitem.index); } this.newlyCompressedBlob.Set(); } catch (System.Exception exc1) { lock(this.eLock) { // expose the exception to the main thread if (this.pendingException!=null) this.pendingException = exc1; } } } /// <summary> /// Indicates whether the stream can be read. /// </summary> /// <remarks> /// The return value is always false. /// </remarks> public override bool CanRead { get { return false; } } /// <summary> /// Indicates whether the stream supports Seek operations. /// </summary> /// <remarks> /// Always returns false. /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream can be written. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports writing. /// </remarks> public override bool CanWrite { get { if (this.output == null) throw new ObjectDisposedException("BZip2Stream"); return this.output.CanWrite; } } /// <summary> /// Reading this property always throws a <see cref="NotImplementedException"/>. /// </summary> public override long Length { get { throw new NotImplementedException(); } } /// <summary> /// The position of the stream pointer. /// </summary> /// /// <remarks> /// Setting this property always throws a <see /// cref="NotImplementedException"/>. Reading will return the /// total number of uncompressed bytes written through. /// </remarks> public override long Position { get { return this.totalBytesWrittenIn; } set { throw new NotImplementedException(); } } /// <summary> /// The total number of bytes written out by the stream. /// </summary> /// <remarks> /// This value is meaningful only after a call to Close(). /// </remarks> public Int64 BytesWrittenOut { get { return totalBytesWrittenOut; } } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="offset">this is irrelevant, since it will always throw!</param> /// <param name="origin">this is irrelevant, since it will always throw!</param> /// <returns>irrelevant!</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotImplementedException(); } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="value">this is irrelevant, since it will always throw!</param> public override void SetLength(long value) { throw new NotImplementedException(); } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name='buffer'>this parameter is never used</param> /// <param name='offset'>this parameter is never used</param> /// <param name='count'>this parameter is never used</param> /// <returns>never returns anything; always throws</returns> public override int Read(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } // used only when Trace is defined [Flags] enum TraceBits : uint { None = 0, Crc = 1, Write = 2, All = 0xffffffff, } [System.Diagnostics.ConditionalAttribute("Trace")] private void TraceOutput(TraceBits bits, string format, params object[] varParams) { if ((bits & this.desiredTrace) != 0) { lock(outputLock) { int tid = Thread.CurrentThread.GetHashCode(); #if FEATURE_FULL_CONSOLE Console.ForegroundColor = (ConsoleColor) (tid % 8 + 10); #endif Console.Write("{0:000} PBOS ", tid); Console.WriteLine(format, varParams); #if FEATURE_FULL_CONSOLE Console.ResetColor(); #endif } } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Reflection; using NUnit.Framework; #if NET_CORE using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Emit; using CS = Microsoft.CodeAnalysis.CSharp; #endif namespace Mono.Cecil.Tests { struct CompilationResult { internal DateTime source_write_time; internal string result_file; public CompilationResult (DateTime write_time, string result_file) { this.source_write_time = write_time; this.result_file = result_file; } } public static class Platform { public static bool OnMono { get { return TryGetType ("Mono.Runtime") != null; } } public static bool OnCoreClr { get { return TryGetType ("System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") != null; } } public static bool OnWindows { get { return Environment.OSVersion.Platform == PlatformID.Win32NT; } } public static bool HasNativePdbSupport { get { return OnWindows && !OnMono; } } static Type TryGetType (string assemblyQualifiedName) { try { // Note that throwOnError=false only suppresses some exceptions, not all. return Type.GetType(assemblyQualifiedName, throwOnError: false); } catch { return null; } } } abstract class CompilationService { Dictionary<string, CompilationResult> files = new Dictionary<string, CompilationResult> (); bool TryGetResult (string name, out string file_result) { file_result = null; CompilationResult result; if (!files.TryGetValue (name, out result)) return false; if (result.source_write_time != File.GetLastWriteTime (name)) return false; file_result = result.result_file; return true; } public string Compile (string name) { string result_file; if (TryGetResult (name, out result_file)) return result_file; result_file = CompileFile (name); RegisterFile (name, result_file); return result_file; } void RegisterFile (string name, string result_file) { files [name] = new CompilationResult (File.GetLastWriteTime (name), result_file); } protected abstract string CompileFile (string name); public static string CompileResource (string name) { var extension = Path.GetExtension (name); if (extension == ".il") return IlasmCompilationService.Instance.Compile (name); if (extension == ".cs") #if NET_CORE return RoslynCompilationService.Instance.Compile (name); #else return CodeDomCompilationService.Instance.Compile (name); #endif throw new NotSupportedException (extension); } protected static string GetCompiledFilePath (string file_name) { var tmp_cecil = Path.Combine (Path.GetTempPath (), "cecil"); if (!Directory.Exists (tmp_cecil)) Directory.CreateDirectory (tmp_cecil); return Path.Combine (tmp_cecil, Path.GetFileName (file_name) + ".dll"); } public static void Verify (string name) { #if !NET_CORE var output = Platform.OnMono ? ShellService.PEDump (name) : ShellService.PEVerify (name); if (output.ExitCode != 0) Assert.Fail (output.ToString ()); #endif } } class IlasmCompilationService : CompilationService { public static readonly IlasmCompilationService Instance = new IlasmCompilationService (); protected override string CompileFile (string name) { string file = GetCompiledFilePath (name); var output = ShellService.ILAsm (name, file); AssertAssemblerResult (output); return file; } static void AssertAssemblerResult (ShellService.ProcessOutput output) { if (output.ExitCode != 0) Assert.Fail (output.ToString ()); } } #if NET_CORE class RoslynCompilationService : CompilationService { public static readonly RoslynCompilationService Instance = new RoslynCompilationService (); protected override string CompileFile (string name) { var compilation = GetCompilation (name); var outputName = GetCompiledFilePath (name); var result = compilation.Emit (outputName); Assert.IsTrue (result.Success, GetErrorMessage (result)); return outputName; } static Compilation GetCompilation (string name) { var assemblyName = Path.GetFileNameWithoutExtension (name); var source = File.ReadAllText (name); var tpa = BaseAssemblyResolver.TrustedPlatformAssemblies.Value; var references = new [] { MetadataReference.CreateFromFile (tpa ["netstandard"]), MetadataReference.CreateFromFile (tpa ["mscorlib"]), MetadataReference.CreateFromFile (tpa ["System.Private.CoreLib"]), MetadataReference.CreateFromFile (tpa ["System.Runtime"]), MetadataReference.CreateFromFile (tpa ["System.Console"]), MetadataReference.CreateFromFile (tpa ["System.Security.AccessControl"]), }; var extension = Path.GetExtension (name); switch (extension) { case ".cs": return CS.CSharpCompilation.Create ( assemblyName, new [] { CS.SyntaxFactory.ParseSyntaxTree (source, new CS.CSharpParseOptions (preprocessorSymbols: new string [] { "NET_CORE" })) }, references, new CS.CSharpCompilationOptions (OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release)); default: throw new NotSupportedException (); } } static string GetErrorMessage (EmitResult result) { if (result.Success) return string.Empty; var builder = new StringBuilder (); foreach (var diagnostic in result.Diagnostics) builder.AppendLine (diagnostic.ToString ()); return builder.ToString (); } } #else class CodeDomCompilationService : CompilationService { public static readonly CodeDomCompilationService Instance = new CodeDomCompilationService (); protected override string CompileFile (string name) { string file = GetCompiledFilePath (name); using (var provider = GetProvider (name)) { var parameters = GetDefaultParameters (name); parameters.IncludeDebugInformation = false; parameters.GenerateExecutable = false; parameters.OutputAssembly = file; var results = provider.CompileAssemblyFromFile (parameters, name); AssertCompilerResults (results); } return file; } static void AssertCompilerResults (CompilerResults results) { Assert.IsFalse (results.Errors.HasErrors, GetErrorMessage (results)); } static string GetErrorMessage (CompilerResults results) { if (!results.Errors.HasErrors) return string.Empty; var builder = new StringBuilder (); foreach (CompilerError error in results.Errors) builder.AppendLine (error.ToString ()); return builder.ToString (); } static CompilerParameters GetDefaultParameters (string name) { return GetCompilerInfo (name).CreateDefaultCompilerParameters (); } static CodeDomProvider GetProvider (string name) { return GetCompilerInfo (name).CreateProvider (); } static CompilerInfo GetCompilerInfo (string name) { return CodeDomProvider.GetCompilerInfo ( CodeDomProvider.GetLanguageFromExtension (Path.GetExtension (name))); } } #endif class ShellService { public class ProcessOutput { public int ExitCode; public string StdOut; public string StdErr; public ProcessOutput (int exitCode, string stdout, string stderr) { ExitCode = exitCode; StdOut = stdout; StdErr = stderr; } public override string ToString () { return StdOut + StdErr; } } static ProcessOutput RunProcess (string target, params string [] arguments) { var stdout = new StringWriter (); var stderr = new StringWriter (); var process = new Process { StartInfo = new ProcessStartInfo { FileName = target, Arguments = string.Join (" ", arguments), CreateNoWindow = true, UseShellExecute = false, RedirectStandardError = true, RedirectStandardInput = true, RedirectStandardOutput = true, }, }; process.Start (); process.OutputDataReceived += (_, args) => stdout.Write (args.Data); process.ErrorDataReceived += (_, args) => stderr.Write (args.Data); process.BeginOutputReadLine (); process.BeginErrorReadLine (); process.WaitForExit (); return new ProcessOutput (process.ExitCode, stdout.ToString (), stderr.ToString ()); } public static ProcessOutput ILAsm (string source, string output) { var ilasm = "ilasm"; if (Platform.OnWindows) ilasm = NetFrameworkTool ("ilasm"); return RunProcess (ilasm, "/nologo", "/dll", "/out:" + Quote (output), Quote (source)); } static string Quote (string file) { return "\"" + file + "\""; } public static ProcessOutput PEVerify (string source) { return RunProcess (WinSdkTool ("peverify"), "/nologo", Quote (source)); } public static ProcessOutput PEDump (string source) { return RunProcess ("pedump", "--verify code,metadata", Quote (source)); } static string NetFrameworkTool (string tool) { #if NET_CORE return Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Windows), "Microsoft.NET", "Framework", "v4.0.30319", tool + ".exe"); #else return Path.Combine ( Path.GetDirectoryName (typeof (object).Assembly.Location), tool + ".exe"); #endif } static string WinSdkTool (string tool) { var sdks = new [] { @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.1 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.2 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools", @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools", @"Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools", @"Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools", @"Microsoft SDKs\Windows\v7.0A\Bin", }; foreach (var sdk in sdks) { var pgf = IntPtr.Size == 8 ? Environment.GetEnvironmentVariable("ProgramFiles(x86)") : Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); var exe = Path.Combine ( Path.Combine (pgf, sdk), tool + ".exe"); if (File.Exists(exe)) return exe; } return tool; } } }
using System; using UIKit; using SpriteKit; using Foundation; using CoreGraphics; namespace SpriteKitPhysicsCollisions { public class SpaceScene : SKScene, ISKPhysicsContactDelegate { const float collisionDamageThreshold = 1.0f; const int missileDamage = 1; bool[] actions = new bool [5]; bool contentCreated; ShipSprite controlledShip; static readonly Random rand = new Random (); static float myRand (float low, float high) { return (float)rand.NextDouble () * (high - low) + low; } public SpaceScene (CGSize size) : base (size) { } public override void DidMoveToView (SKView view) { if (!contentCreated) { CreateSceneContents (); contentCreated = true; } } void CreateSceneContents () { BackgroundColor = UIColor.Black; ScaleMode = SKSceneScaleMode.AspectFit; // Give the scene an edge and configure other physics info on the scene. var body = SKPhysicsBody.CreateEdgeLoop (Frame); body.CategoryBitMask = Category.Edge; body.CollisionBitMask = 0; body.ContactTestBitMask = 0; PhysicsBody = body; PhysicsWorld.Gravity = new CGVector (0, 0); PhysicsWorld.ContactDelegate = this; // In this sample, the positions of everything is hard coded. In an actual game, you might implement this in an archive that is loaded from a file. controlledShip = new ShipSprite (new CGPoint (100, 300)); AddChild (controlledShip); // this ship isn't connected to any controls so it doesn't move, except when it collides with something. AddChild (new ShipSprite (new CGPoint (200, 300))); AddChild (new AsteroidNode (new CGPoint (100, 200))); AddChild (new PlanetNode (new CGPoint (300, 100))); } #region Physics Handling and Game Logic void AttackTarget (SKPhysicsBody target, SKNode missile) { // Only ships take damage from missiles. if ((target.CategoryBitMask & Category.Ship) != 0) ((ShipSprite)target.Node).ApplyDamage (missileDamage); DetonateMissile (missile); } void DetonateMissile(SKNode missile) { SKEmitterNode explosion = new ExplosionNode (this); explosion.Position = missile.Position; AddChild (explosion); missile.RemoveFromParent (); } [Export ("didBeginContact:")] public void DidBeginContact (SKPhysicsContact contact) { // Handle contacts between two physics bodies. // Contacts are often a double dispatch problem; the effect you want is based // on the type of both bodies in the contact. This sample solves // this in a brute force way, by checking the types of each. A more complicated // example might use methods on objects to perform the type checking. SKPhysicsBody firstBody; SKPhysicsBody secondBody; // The contacts can appear in either order, and so normally you'd need to check // each against the other. In this example, the category types are well ordered, so // the code swaps the two bodies if they are out of order. This allows the code // to only test collisions once. if (contact.BodyA.CategoryBitMask < contact.BodyB.CategoryBitMask) { firstBody = contact.BodyA; secondBody = contact.BodyB; } else { firstBody = contact.BodyB; secondBody = contact.BodyA; } // Missiles attack whatever they hit, then explode. if ((firstBody.CategoryBitMask & Category.Missile) != 0) AttackTarget (secondBody, firstBody.Node); // Ships collide and take damage. The collision damage is based on the strength of the collision. if ((firstBody.CategoryBitMask & Category.Ship) != 0) { // The edge exists just to keep all gameplay on one screen, // so ships should not take damage when they hit the edge. if (contact.CollisionImpulse > collisionDamageThreshold && (secondBody.CategoryBitMask & Category.Edge) == 0) { int damage = (int) (contact.CollisionImpulse / collisionDamageThreshold); ((ShipSprite)firstBody.Node).ApplyDamage (damage); if ((secondBody.CategoryBitMask == Category.Ship)) ((ShipSprite)secondBody.Node).ApplyDamage (damage); } } // Asteroids that hit planets are destroyed. if ((firstBody.CategoryBitMask & Category.Asteroid) != 0 && (secondBody.CategoryBitMask & Category.Planet) != 0) firstBody.Node.RemoveFromParent (); } #endregion #region Controls and Control Logic public override void Update (double currentTime) { // This runs once every frame. Other sorts of logic might run from here. For example, // if the target ship was controlled by the computer, you might run AI from this routine. // Use the stored key information to control the ship. if (actions [(int)PlayerActions.Forward]) controlledShip.ActivateMainEngine (); else controlledShip.DeactivateMainEngine (); if (actions [(int)PlayerActions.Back]) controlledShip.ReverseThrust (); if (actions [(int)PlayerActions.Left]) controlledShip.RotateShipLeft (); if (actions [(int)PlayerActions.Right]) controlledShip.RotateShipRight (); if (actions [(int)PlayerActions.Action]) controlledShip.AttemptMissileLaunch (currentTime); } #endregion public override void TouchesBegan (NSSet touches, UIEvent evt) { base.TouchesMoved (touches, evt); actions [(int)PlayerActions.Action] = false; actions [(int)PlayerActions.Left] = false; actions [(int)PlayerActions.Right] = false; actions [(int)PlayerActions.Forward] = false; actions [(int)PlayerActions.Back] = false; UITouch touch = (UITouch)touches.AnyObject; var location = touch.LocationInView (View); var deltaX = location.X - controlledShip.Position.X; var deltaY = (View.Bounds.Height - location.Y) - controlledShip.Position.Y; if (Math.Abs (deltaX) < 30 && Math.Abs (deltaY) < 30) { actions [(int)PlayerActions.Action] = true; } else if (Math.Abs (deltaX) > Math.Abs (deltaY)) { if (deltaX < 0) actions [(int)PlayerActions.Left] = true; else actions [(int)PlayerActions.Right] = true; } else { if (deltaY < 0) actions [(int)PlayerActions.Forward] = true; else actions [(int)PlayerActions.Back] = true; } } public override void TouchesMoved (NSSet touches, UIEvent evt) { base.TouchesMoved (touches, evt); actions [(int)PlayerActions.Action] = false; actions [(int)PlayerActions.Left] = false; actions [(int)PlayerActions.Right] = false; actions [(int)PlayerActions.Forward] = false; actions [(int)PlayerActions.Back] = false; UITouch touch = (UITouch)touches.AnyObject; var location = touch.LocationInView (View); var deltaX = location.X - controlledShip.Position.X; var deltaY = (View.Bounds.Height - location.Y) - controlledShip.Position.Y; if (Math.Abs (deltaX) < 30 && Math.Abs (deltaY) < 30) actions [(int)PlayerActions.Action] = true; else if (Math.Abs (deltaX) > Math.Abs (deltaY)) { if (deltaX < 0) actions [(int)PlayerActions.Left] = true; else actions [(int)PlayerActions.Right] = true; } else { if (deltaY < 0) actions [(int)PlayerActions.Forward] = true; else actions [(int)PlayerActions.Back] = true; } } public override void TouchesEnded (NSSet touches, UIEvent evt) { base.TouchesMoved (touches, evt); actions [(int)PlayerActions.Action] = false; actions [(int)PlayerActions.Left] = false; actions [(int)PlayerActions.Right] = false; actions [(int)PlayerActions.Forward] = false; actions [(int)PlayerActions.Back] = false; } } }
// Copyright 2010 Chris Patterson // // 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 Stact.Specs.Workflow { using Magnum.TestFramework; using Stact.Workflow; [Scenario] public class When_creating_a_new_workflow { WorkflowInstance<TestWorkflow> _instance; StateMachineWorkflow<TestWorkflow, TestInstance> _workflow; [When] public void Creating_a_new_workflow() { _workflow = StateMachineWorkflow.New<TestWorkflow, TestInstance>(x => { x.AccessCurrentState(y => y.CurrentState); }); _instance = _workflow.GetInstance(new TestInstance()); } [Then] public void Initial_state_should_be_found() { State initial = _workflow.GetState("Initial"); initial.ShouldNotBeNull(); initial.Name.ShouldEqual("Initial"); } [Then] public void Initial_state_should_be_automatically_created() { State current = _instance.CurrentState; current.Name.ShouldEqual("Initial"); } class TestInstance { public State CurrentState { get; set; } } interface TestWorkflow { } } [Scenario] public class When_an_event_causing_a_state_transition { WorkflowInstance<TestWorkflow> _instance; StateMachineWorkflow<TestWorkflow, TestInstance> _workflow; [When] public void An_event_causing_a_state_transition() { _workflow = StateMachineWorkflow.New<TestWorkflow, TestInstance>(x => { x.AccessCurrentState(y => y.CurrentState); x.During(y => y.Initial) .When(y => y.Finish) .TransitionTo(y => y.Completed); }); _instance = _workflow.GetInstance(new TestInstance()); _instance.RaiseEvent(x => x.Finish); } [Then] public void Should_result_in_the_target_state() { State current = _instance.CurrentState; current.ShouldEqual(_workflow.GetState(x => x.Completed)); } class TestInstance { public State CurrentState { get; set; } } interface TestWorkflow { State Initial { get; } State Completed { get; } Event Finish { get; } } } [Scenario] public class When_a_message_event_changes_the_state { WorkflowInstance<TestWorkflow> _instance; StateMachineWorkflow<TestWorkflow, TestInstance> _workflow; [When] public void A_message_event_changes_the_state() { _workflow = StateMachineWorkflow.New<TestWorkflow, TestInstance>(x => { x.AccessCurrentState(y => y.CurrentState); x.During(y => y.Initial) .When(y => y.Finish) .TransitionTo(y => y.Completed); }); _instance = _workflow.GetInstance(new TestInstance()); _instance.RaiseEvent(x => x.Finish, new Result { Value = "Success" }); } [Then] public void Should_result_in_the_target_state() { State current = _instance.CurrentState; current.ShouldEqual(_workflow.GetState(x => x.Completed)); } class TestInstance { public State CurrentState { get; set; } } class Result { public string Value { get; set; } } interface TestWorkflow { State Initial { get; } State Completed { get; } Event<Result> Finish { get; } } } [Scenario] public class When_raising_multiple_events { WorkflowInstance<TestWorkflow> _instance; StateMachineWorkflow<TestWorkflow, TestInstance> _workflow; [When] public void Raising_multiple_events() { _workflow = StateMachineWorkflow.New<TestWorkflow, TestInstance>(x => { x.AccessCurrentState(y => y.CurrentState); x.During(y => y.Initial) .When(y => y.Start) .TransitionTo(y => y.Running); x.During(y => y.Running) .When(y => y.Finish) .TransitionTo(y => y.Completed); }); _instance = _workflow.GetInstance(new TestInstance()); _instance.RaiseEvent(x => x.Start); _instance.RaiseEvent(x => x.Finish); } [Then] public void Should_result_in_the_target_state() { State current = _instance.CurrentState; current.ShouldEqual(_workflow.GetState(x => x.Completed)); } class TestInstance { public State CurrentState { get; set; } } interface TestWorkflow { State Initial { get; } State Running { get; } State Completed { get; } Event Start { get; } Event Finish { get; } } /* [Test] public void Typed_events_should_carry_their_data_to_the_expression() { ExampleStateMachine example = new ExampleStateMachine(); example.SubmitCommentCard(new CommentCard { IsComplaint = true }); Assert.AreEqual(ExampleStateMachine.WaitingForManager, example.CurrentState); } [Test] public void Multiple_expressions_per_event_should_run_in_order() { ExampleStateMachine example = new ExampleStateMachine(); example.SubmitCommentCard(new CommentCard { IsComplaint = true }); Assert.AreEqual(ExampleStateMachine.WaitingForManager, example.CurrentState); example.BurnCommentCard(); Assert.AreEqual(ExampleStateMachine.Completed, example.CurrentState); } [Test] public void Typed_events_should_carry_their_data_to_the_expression_other() { ExampleStateMachine example = new ExampleStateMachine(); example.SubmitCommentCard(new CommentCard { IsComplaint = false }); Assert.AreEqual(ExampleStateMachine.Completed, example.CurrentState); } */ } }
// 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, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Numerics; using System.Reflection; using System.Runtime.Remoting; using System.Text; using IronPython.Hosting; using IronPython.Modules; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using Microsoft.PythonTools.Interpreter; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Hosting; using Microsoft.Scripting.Hosting.Providers; using Microsoft.Scripting.Runtime; using Microsoft.Win32; namespace Microsoft.IronPythonTools.Interpreter { /// <summary> /// Wraps a Python interpreter which is loaded into a remote app domain. Provides lots of helper /// methods for inspecting various IronPython objects in the domain and returning results w/o causing /// type loads in the local domain. We use ObjectIdentityHandle's to pass the objects back and forth /// which allows the local domain to cache based upon object identity w/o transitioning to this domain /// to do comparisons. /// </summary> class RemoteInterpreter { private readonly ScriptEngine _engine; private readonly CodeContext _codeContext; private readonly CodeContext _codeContextCls; private readonly TopNamespaceTracker _namespaceTracker; private readonly Dictionary<object, ObjectIdentityHandle> _members = new Dictionary<object, ObjectIdentityHandle>(); private readonly List<object> _reverseMembers = new List<object>(); private readonly HashSet<string> _assembliesLoadedFromDirectories = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, Assembly> _referencedAssemblies = new Dictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase); private string[] _analysisDirs; private const string _codeCtxType = "IronPython.Runtime.CodeContext"; public RemoteInterpreter() : this(Python.CreateEngine(new Dictionary<string, object> { { "NoAssemblyResolveHook", true } })) { } public RemoteInterpreter(ScriptEngine engine) { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; _engine = engine; var pythonContext = HostingHelpers.GetLanguageContext(_engine) as PythonContext; _codeContextCls = new ModuleContext(new PythonDictionary(), pythonContext).GlobalContext; _codeContextCls.ModuleContext.ShowCls = true; _codeContext = new ModuleContext( new PythonDictionary(), HostingHelpers.GetLanguageContext(_engine) as PythonContext ).GlobalContext; _namespaceTracker = new TopNamespaceTracker(_codeContext.LanguageContext.DomainManager); AddAssembly(LoadAssemblyInfo(typeof(string).Assembly)); AddAssembly(LoadAssemblyInfo(typeof(Debug).Assembly)); string installDir = GetPythonInstallDir(); if (installDir != null) { var dllDir = Path.Combine(installDir, "DLLs"); if (Directory.Exists(dllDir)) { foreach (var assm in Directory.GetFiles(dllDir)) { try { var asm = Assembly.LoadFile(Path.Combine(dllDir, assm)); _engine.Runtime.LoadAssembly(asm); AddAssembly(LoadAssemblyInfo(asm)); } catch { } } } } LoadAssemblies(); } private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { if (new AssemblyName(args.Name).FullName == typeof(RemoteInterpreterProxy).Assembly.FullName) { return typeof(RemoteInterpreterProxy).Assembly; } if (_analysisDirs != null) { foreach (var dir in _analysisDirs) { var name = new AssemblyName(args.Name).Name; var asm = TryLoad(dir, name, ""); if (asm != null) { AddLoadedAssembly(dir); return asm; } asm = TryLoad(dir, name, ".dll"); if (asm != null) { AddLoadedAssembly(dir); return asm; } asm = TryLoad(dir, name, ".exe"); if (asm != null) { AddLoadedAssembly(dir); return asm; } } } return null; } private void AddLoadedAssembly(string dir) { lock (_assembliesLoadedFromDirectories) { _assembliesLoadedFromDirectories.Add(dir); } } private Assembly TryLoad(string dir, string name, string ext) { string path = Path.Combine(dir, name + ext); if (File.Exists(path)) { try { return Assembly.Load(File.ReadAllBytes(path)); } catch { } } return null; } internal string[] GetBuiltinModuleNames() { var names = _engine.Operations.GetMember<PythonTuple>(_engine.GetSysModule(), "builtin_module_names"); string[] res = new string[names.Count]; for (int i = 0; i < res.Length; i++) { res[i] = (string)names[i]; } return res; } internal ObjectIdentityHandle ImportBuiltinModule(string modName) { PythonModule mod = Importer.Import(_codeContextCls, modName, PythonOps.EmptyTuple, 0) as PythonModule; Debug.Assert(mod != null); return MakeHandle(mod); } /// <summary> /// VS seems to load extensions via Assembly.LoadFrom. When an assembly is being loaded via Assembly.Load the CLR fusion probes privatePath /// set in App.config (devenv.exe.config) first and then tries the code base of the assembly that called Assembly.Load if it was itself loaded via LoadFrom. /// In order to locate IronPython.Modules correctly, the call to Assembly.Load must originate from an assembly in IronPythonTools installation folder. /// Although Microsoft.Scripting is also in that folder it can be loaded first by IronRuby and that causes the Assembly.Load to search in IronRuby's /// installation folder. Adding a reference to IronPython.Modules also makes sure that the assembly is loaded from the same location as IronPythonToolsCore. /// </summary> private static void LoadAssemblies() { GC.KeepAlive(typeof(IronPython.Modules.ArrayModule)); // IronPython.Modules } internal static string GetPythonInstallDir() { using (var ipy = Registry.LocalMachine.OpenSubKey("SOFTWARE\\IronPython")) { if (ipy != null) { using (var twoSeven = ipy.OpenSubKey("2.7")) { if (twoSeven != null) { var installPath = twoSeven.OpenSubKey("InstallPath"); if (installPath != null) { var res = installPath.GetValue("") as string; if (res != null) { return res; } } } } } } var paths = Environment.GetEnvironmentVariable("PATH"); if (paths != null) { foreach (string dir in paths.Split(Path.PathSeparator)) { try { if (IronPythonExistsIn(dir)) { return dir; } } catch { // ignore } } } return null; } private static bool IronPythonExistsIn(string/*!*/ dir) { return File.Exists(Path.Combine(dir, "ipy.exe")); } public ScriptEngine Engine { get { return _engine; } } private KeyValuePair<Assembly, TopNamespaceTracker> LoadAssemblyInfo(Assembly assm) { var nsTracker = new TopNamespaceTracker(_codeContext.LanguageContext.DomainManager); nsTracker.LoadAssembly(assm); return new KeyValuePair<Assembly, TopNamespaceTracker>(assm, nsTracker); } #region CallAndHandle helpers private static ObjectHandle CallAndHandle(Func<ObjectHandle> action) { try { return action(); } catch (FileLoadException) { } catch (IOException) { } catch (CannotUnwrapHandleException) { } return null; } private static ObjectIdentityHandle CallAndHandle(Func<ObjectIdentityHandle> action) { try { return action(); } catch (FileLoadException) { } catch (IOException) { } catch (CannotUnwrapHandleException) { } return new ObjectIdentityHandle(); } private static string CallAndHandle(Func<string> action) { try { return action(); } catch (FileLoadException) { } catch (IOException) { } catch (CannotUnwrapHandleException) { } return string.Empty; } private static string[] CallAndHandle(Func<string[]> action) { try { return action(); } catch (FileLoadException) { } catch (IOException) { } catch (CannotUnwrapHandleException) { } return new string[0]; } private static T CallAndHandle<T>(Func<T> action, T defaultValue) { try { return action(); } catch (FileLoadException) { } catch (IOException) { } catch (CannotUnwrapHandleException) { } return defaultValue; } private static T CallAndHandle<T>(Func<T> action, Func<T> defaultValueCreator) { try { return action(); } catch (FileLoadException) { } catch (IOException) { } catch (CannotUnwrapHandleException) { } return defaultValueCreator(); } #endregion internal ObjectHandle LoadAssemblyByName(string name) { return CallAndHandle(() => { Assembly res; if (_referencedAssemblies.TryGetValue(name, out res) || (res = ClrModule.LoadAssemblyByName(CodeContext, name)) != null) { return new ObjectHandle(res); } return null; }); } internal ObjectHandle LoadAssemblyByPartialName(string name) { return CallAndHandle(() => { var res = ClrModule.LoadAssemblyByPartialName(name); if (res != null) { return new ObjectHandle(res); } return null; }); } internal ObjectHandle LoadAssemblyFromFile(string name) { return CallAndHandle(() => { var res = ClrModule.LoadAssemblyFromFile(CodeContext, name); if (res != null) { return new ObjectHandle(res); } return null; }); } internal ObjectHandle LoadAssemblyFromFileWithPath(string name) { return CallAndHandle(() => { var res = ClrModule.LoadAssemblyFromFileWithPath(CodeContext, name); if (res != null) { return new ObjectHandle(res); } return null; }); } internal ObjectHandle LoadAssemblyFrom(string path) { return CallAndHandle(() => { var res = Assembly.LoadFrom(path); if (res != null) { return new ObjectHandle(res); } return null; }); } private void AddAssembly(KeyValuePair<Assembly, TopNamespaceTracker> assembly) { _namespaceTracker.LoadAssembly(assembly.Key); } public bool AddAssembly(ObjectHandle assembly) { return CallAndHandle(() => { var asm = (Assembly)assembly.Unwrap(); return AddAssembly(asm); }, false); } private bool AddAssembly(Assembly asm) { if (asm != null && !_namespaceTracker.PackageAssemblies.Contains(asm)) { return _namespaceTracker.LoadAssembly(asm); } return false; } public bool LoadWpf() { return CallAndHandle(() => { var res = AddAssembly(typeof(System.Windows.Markup.XamlReader).Assembly); // PresentationFramework res |= AddAssembly(typeof(System.Windows.Clipboard).Assembly); // PresentationCore res |= AddAssembly(typeof(System.Windows.DependencyProperty).Assembly); // WindowsBase res |= AddAssembly(typeof(System.Xaml.XamlReader).Assembly); // System.Xaml return res; }, false); } public IList<string> GetModuleNames() { return CallAndHandle(() => { return _namespaceTracker.Keys.ToArray(); }); } public ObjectIdentityHandle LookupNamespace(string name) { if (!String.IsNullOrWhiteSpace(name)) { var ns = _namespaceTracker.TryGetPackage(name); if (ns != null) { return MakeHandle(ns); } } return new ObjectIdentityHandle(); } internal bool TryGetMember(object obj, string name, out object value) { return TryGetMember(_codeContext, obj, name, out value); } internal bool TryGetMember(object obj, string name, bool showClr, out object value) { var cctx = showClr ? _codeContextCls : _codeContext; return TryGetMember(cctx, obj, name, out value); } private bool TryGetMember(CodeContext codeContext, object obj, string name, out object value) { NamespaceTracker nt = obj as NamespaceTracker; if (nt != null) { value = NamespaceTrackerOps.GetCustomMember(codeContext, nt, name); return value != OperationFailed.Value; } object result = Builtin.getattr(codeContext, obj, name, this); if (result == this) { value = null; return false; } else { value = result; return true; } } public CodeContext CodeContext { get { return _codeContext; } } internal string[] DirHelper(ObjectIdentityHandle handle, bool showClr) { return CallAndHandle(() => { var obj = Unwrap(handle); NamespaceTracker nt = obj as NamespaceTracker; if (nt != null) { return nt.GetMemberNames().ToArray(); } var dir = TryDir(obj, showClr); int len = dir.__len__(); string[] result = new string[len]; for (int i = 0; i < len; i++) { // TODO: validate result[i] = dir[i] as string; } return result; }); } private static List TryDir(object obj, bool showClr) { try { return showClr ? ClrModule.DirClr(obj) : ClrModule.Dir(obj); } catch { // http://pytools.codeplex.com/discussions/279363#post697979 // Work around exceptions coming out of IronPython and the CLR, // one wouldn't normally expect dir() to throw but it can... return new List(); } } private ObjectIdentityHandle MakeHandle(object member) { if (member == null) { return new ObjectIdentityHandle(); } lock (_members) { ObjectIdentityHandle handle; if (!_members.TryGetValue(member, out handle)) { _members[member] = handle = new ObjectIdentityHandle(_members.Count + 1); _reverseMembers.Add(member); } return handle; } } [Serializable] private class CannotUnwrapHandleException : Exception { public CannotUnwrapHandleException() { } public CannotUnwrapHandleException(string message) : base(message) { } public CannotUnwrapHandleException(string message, Exception inner) : base(message, inner) { } protected CannotUnwrapHandleException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } private object Unwrap(ObjectIdentityHandle handle) { if (handle.IsNull) { throw new CannotUnwrapHandleException(); } lock (_members) { if (handle.Id > _reverseMembers.Count) { Debug.Fail("Invalid object identity handle"); throw new CannotUnwrapHandleException(); } var result = _reverseMembers[handle.Id - 1]; if (result == null) { throw new CannotUnwrapHandleException(); } return result; } } internal ObjectKind GetObjectKind(ObjectIdentityHandle value) { if (value.IsNull) { return ObjectKind.Constant; } var obj = Unwrap(value); if (obj is PythonModule) { return ObjectKind.Module; } else if (obj is PythonType) { return ObjectKind.Type; } else if (obj is ConstructorFunction) { return ObjectKind.ConstructorFunction; } else if (obj is BuiltinFunction) { return ObjectKind.BuiltinFunction; } else if (obj is BuiltinMethodDescriptor) { return ObjectKind.BuiltinMethodDesc; } else if (obj is ReflectedField) { return ObjectKind.ReflectedField; } else if (obj is ReflectedProperty) { return ObjectKind.ReflectedProperty; } else if (obj is ReflectedExtensionProperty) { return ObjectKind.ReflectedExtensionProperty; } else if (obj is NamespaceTracker) { return ObjectKind.NamespaceTracker; } else if (obj is Method) { return ObjectKind.Method; } else if (obj is ClassMethodDescriptor) { return ObjectKind.ClassMethod; } else if (obj is PythonTypeTypeSlot) { return ObjectKind.PythonTypeTypeSlot; } else if (obj is ReflectedEvent) { return ObjectKind.ReflectedEvent; } else if (obj is PythonTypeSlot) { return ObjectKind.PythonTypeSlot; } else if (obj is TypeGroup) { return ObjectKind.TypeGroup; } else if (obj is bool || obj is int || obj is Complex || obj is string || obj is long || obj is double || obj.GetType().IsEnum) { return ObjectKind.Constant; } return ObjectKind.Unknown; } #region BuiltinMethodDescriptor Helpers internal ObjectIdentityHandle GetBuiltinMethodDescriptorTemplate(ObjectIdentityHandle handle) { return CallAndHandle(() => { var func = PythonOps.GetBuiltinMethodDescriptorTemplate((BuiltinMethodDescriptor)Unwrap(handle)); return MakeHandle(func); }); } #endregion #region PythonModule Helpers internal string GetModuleDocumentation(ObjectIdentityHandle handle) { return CallAndHandle(() => { PythonModule module = (PythonModule)Unwrap(handle); object docValue; if (!module.Get__dict__().TryGetValue("__doc__", out docValue) || !(docValue is string)) { return String.Empty; } return (string)docValue; }); } internal string GetModuleName(ObjectIdentityHandle handle) { return CallAndHandle(() => { PythonModule module = (PythonModule)Unwrap(handle); object name; if (!module.Get__dict__().TryGetValue("__name__", out name) || !(name is string)) { name = ""; } return (string)name; }); } #endregion #region PythonType Helpers internal string GetPythonTypeName(ObjectIdentityHandle handle) { return CallAndHandle(() => { return PythonType.Get__name__((PythonType)Unwrap(handle)); }); } internal string GetPythonTypeDocumentation(ObjectIdentityHandle handle) { return CallAndHandle(() => { try { return PythonType.Get__doc__(CodeContext, (PythonType)Unwrap(handle)) as string; } catch (ArgumentException) { // IronPython can throw here if it can't figure out the // path of the assembly this type is defined in. return null; } }); } internal ObjectIdentityHandle[] GetPythonTypeMro(ObjectIdentityHandle handle) { return CallAndHandle(() => { var mro = PythonType.Get__mro__((PythonType)Unwrap(handle)); var mroHandles = new List<ObjectIdentityHandle>(); foreach (var item in mro.OfType<PythonType>()) { mroHandles.Add(MakeHandle(item)); } return mroHandles.ToArray(); }, () => new ObjectIdentityHandle[0]); } internal BuiltinTypeId PythonTypeGetBuiltinTypeId(ObjectIdentityHandle handle) { return CallAndHandle(() => { var value = (PythonType)Unwrap(handle); var clrType = value.__clrtype__(); switch (Type.GetTypeCode(value.__clrtype__())) { case TypeCode.Boolean: return BuiltinTypeId.Bool; case TypeCode.Int32: return BuiltinTypeId.Int; case TypeCode.String: return BuiltinTypeId.Unicode; case TypeCode.Double: return BuiltinTypeId.Float; case TypeCode.Object: if (clrType == typeof(object)) { return BuiltinTypeId.Object; } else if (clrType == typeof(PythonFunction)) { return BuiltinTypeId.Function; } else if (clrType == typeof(BuiltinFunction)) { return BuiltinTypeId.BuiltinFunction; } else if (clrType == typeof(BuiltinMethodDescriptor)) { return BuiltinTypeId.BuiltinMethodDescriptor; } else if (clrType == typeof(Complex)) { return BuiltinTypeId.Complex; } else if (clrType == typeof(PythonDictionary)) { return BuiltinTypeId.Dict; } else if (clrType == typeof(BigInteger)) { return BuiltinTypeId.Long; } else if (clrType == typeof(List)) { return BuiltinTypeId.List; } else if (clrType == typeof(PythonGenerator)) { return BuiltinTypeId.Generator; } else if (clrType == typeof(SetCollection)) { return BuiltinTypeId.Set; } else if (clrType == typeof(PythonType)) { return BuiltinTypeId.Type; } else if (clrType == typeof(PythonTuple)) { return BuiltinTypeId.Tuple; } else if (clrType == typeof(Bytes)) { return BuiltinTypeId.Bytes; } break; } return BuiltinTypeId.Unknown; }, BuiltinTypeId.Unknown); } internal string GetTypeDeclaringModule(ObjectIdentityHandle pythonType) { return CallAndHandle(() => { var value = (PythonType)Unwrap(pythonType); return (string)PythonType.Get__module__(CodeContext, value); }); } internal bool IsPythonTypeArray(ObjectIdentityHandle pythonType) { return CallAndHandle(() => { var value = (PythonType)Unwrap(pythonType); return value.__clrtype__().IsArray; }, false); } internal ObjectIdentityHandle GetPythonTypeElementType(ObjectIdentityHandle pythonType) { return CallAndHandle(() => { var value = (PythonType)Unwrap(pythonType); return MakeHandle(DynamicHelpers.GetPythonTypeFromType(value.__clrtype__().GetElementType())); }); } internal bool IsDelegateType(ObjectIdentityHandle pythonType) { return CallAndHandle(() => { var value = (PythonType)Unwrap(pythonType); return typeof(Delegate).IsAssignableFrom(value.__clrtype__()); }, false); } internal ObjectIdentityHandle[] GetEventInvokeArgs(ObjectIdentityHandle pythonType) { return CallAndHandle(() => { var value = (PythonType)Unwrap(pythonType); var type = value.__clrtype__(); return GetEventInvokeArgs(type); }, () => new ObjectIdentityHandle[0]); } private ObjectIdentityHandle[] GetEventInvokeArgs(Type type) { return CallAndHandle(() => { var p = type.GetMethod("Invoke").GetParameters(); var args = new ObjectIdentityHandle[p.Length]; for (int i = 0; i < p.Length; i++) { args[i] = MakeHandle(DynamicHelpers.GetPythonTypeFromType(p[i].ParameterType)); } return args; }, () => new ObjectIdentityHandle[0]); } internal PythonMemberType GetPythonTypeMemberType(ObjectIdentityHandle pythonType) { return CallAndHandle(() => { var value = (PythonType)Unwrap(pythonType); var type = value.__clrtype__(); if (type.IsEnum) { return PythonMemberType.Enum; } else if (typeof(Delegate).IsAssignableFrom(type)) { return PythonMemberType.Delegate; } else { return PythonMemberType.Class; } }, PythonMemberType.Class); } internal bool PythonTypeHasNewOrInitMethods(ObjectIdentityHandle pythonType) { return CallAndHandle(() => { var value = (PythonType)Unwrap(pythonType); return PythonTypeHasNewOrInitMethods(value); }, false); } private static bool PythonTypeHasNewOrInitMethods(PythonType value) { return CallAndHandle(() => { var clrType = ClrModule.GetClrType(value); if (!(value == TypeCache.String || value == TypeCache.Object || value == TypeCache.Double || value == TypeCache.Complex || value == TypeCache.Boolean)) { var newMethods = clrType.GetMember("__new__", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static); if (newMethods.Length == 0) { var initMethods = clrType.GetMember("__init__", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance); return initMethods.Length != 0; } return true; } else if (clrType == typeof(object)) { return false; } return true; }, false); } internal ObjectIdentityHandle PythonTypeMakeGenericType(ObjectIdentityHandle pythonType, ObjectIdentityHandle[] types) { return CallAndHandle(() => { var value = (PythonType)Unwrap(pythonType); Type[] realTypes = new Type[types.Length]; for (int i = 0; i < types.Length; i++) { realTypes[i] = ((PythonType)Unwrap(types[i])).__clrtype__(); } return MakeHandle(DynamicHelpers.GetPythonTypeFromType(value.__clrtype__().MakeGenericType(realTypes))); }); } internal ObjectIdentityHandle[] GetPythonTypeConstructors(ObjectIdentityHandle pythonType) { return CallAndHandle(() => { var value = (PythonType)Unwrap(pythonType); Type clrType = ClrModule.GetClrType(value); var ctors = clrType.GetConstructors(BindingFlags.Public | BindingFlags.CreateInstance | BindingFlags.Instance); if (ctors.Length > 0) { ObjectIdentityHandle[] res = new ObjectIdentityHandle[ctors.Length]; for (int i = 0; i < res.Length; i++) { res[i] = MakeHandle(ctors[i]); } return res; } return null; }, () => new ObjectIdentityHandle[0]); } internal bool IsPythonTypeGenericTypeDefinition(ObjectIdentityHandle pythonType) { return CallAndHandle(() => { var value = (PythonType)Unwrap(pythonType); return value.__clrtype__().IsGenericTypeDefinition; }, false); } #endregion #region ReflectedField Helpers internal string GetFieldDocumentation(ObjectIdentityHandle field) { return CallAndHandle(() => { var value = (ReflectedField)Unwrap(field); try { return value.__doc__; } catch (ArgumentException) { // IronPython can throw here if it can't figure out the // path of the assembly this type is defined in. return ""; } }); } /// <summary> /// Returns an ObjectIdentityHandle which contains a PythonType /// </summary> internal ObjectIdentityHandle GetFieldType(ObjectIdentityHandle field) { return CallAndHandle(() => { var value = (ReflectedField)Unwrap(field); return MakeHandle(value.FieldType); }); } internal bool IsFieldStatic(ObjectIdentityHandle field) { return CallAndHandle(() => { var value = (ReflectedField)Unwrap(field); return value.Info.IsStatic; }, false); } #endregion #region BuiltinFunction Helpers internal string GetBuiltinFunctionName(ObjectIdentityHandle function) { return CallAndHandle(() => { BuiltinFunction func = (BuiltinFunction)Unwrap(function); return func.__name__; }); } internal string GetBuiltinFunctionDocumentation(ObjectIdentityHandle function) { return CallAndHandle(() => { BuiltinFunction func = (BuiltinFunction)Unwrap(function); try { return func.__doc__; } catch (ArgumentException) { // IronPython can throw here if it can't figure out the // path of the assembly this type is defined in. return ""; } }); } internal string GetBuiltinFunctionModule(ObjectIdentityHandle function) { return CallAndHandle(() => { BuiltinFunction func = (BuiltinFunction)Unwrap(function); return func.Get__module__(CodeContext); }); } internal ObjectIdentityHandle GetBuiltinFunctionDeclaringPythonType(ObjectIdentityHandle function) { return CallAndHandle(() => { BuiltinFunction func = (BuiltinFunction)Unwrap(function); return MakeHandle(DynamicHelpers.GetPythonTypeFromType(func.DeclaringType)); }); } internal ObjectIdentityHandle[] GetBuiltinFunctionOverloads(ObjectIdentityHandle function) { return CallAndHandle(() => { BuiltinFunction func = (BuiltinFunction)Unwrap(function); var result = new List<ObjectIdentityHandle>(); foreach (var ov in func.Overloads.Functions) { BuiltinFunction overload = (ov as BuiltinFunction); if (overload.Overloads.Targets[0].DeclaringType.IsAssignableFrom(func.DeclaringType) || (overload.Overloads.Targets[0].DeclaringType.FullName != null && overload.Overloads.Targets[0].DeclaringType.FullName.StartsWith("IronPython.Runtime.Operations."))) { result.Add(MakeHandle(overload.Targets[0])); } } return result.ToArray(); }, () => new ObjectIdentityHandle[0]); } internal ObjectIdentityHandle[] GetConstructorFunctionTargets(ObjectIdentityHandle function) { return CallAndHandle(() => { return ((ConstructorFunction)Unwrap(function)).Overloads.Targets .Select(x => MakeHandle(x)) .ToArray(); }, () => Array.Empty<ObjectIdentityHandle>()); } internal ObjectIdentityHandle GetConstructorFunctionDeclaringType(ObjectIdentityHandle function) { return CallAndHandle(() => MakeHandle( GetTypeFromType( ((ConstructorFunction)Unwrap(function)).Overloads.Targets .First() .DeclaringType ) ) ); } #endregion #region ReflectedProperty Helpers internal ObjectIdentityHandle GetPropertyType(ObjectIdentityHandle property) { return CallAndHandle(() => { ReflectedProperty prop = (ReflectedProperty)Unwrap(property); return MakeHandle(prop.PropertyType); }); } internal bool IsPropertyStatic(ObjectIdentityHandle property) { return CallAndHandle(() => { ReflectedProperty prop = (ReflectedProperty)Unwrap(property); var method = prop.Info.GetGetMethod() ?? prop.Info.GetSetMethod(); if (method != null) { return method.IsStatic; } return false; }, false); } internal string GetPropertyDocumentation(ObjectIdentityHandle property) { return CallAndHandle(() => { ReflectedProperty prop = (ReflectedProperty)Unwrap(property); try { return prop.__doc__; } catch (ArgumentException) { // IronPython can throw here if it can't figure out the // path of the assembly this type is defined in. return ""; } }); } #endregion #region Object Helpers internal ObjectIdentityHandle GetObjectPythonType(ObjectIdentityHandle value) { return CallAndHandle(() => { return MakeHandle(DynamicHelpers.GetPythonType(Unwrap(value))); }); } internal bool IsEnumValue(ObjectIdentityHandle value) { return CallAndHandle(() => { var obj = Unwrap(value).GetType(); return obj.IsEnum; }, false); } internal ObjectIdentityHandle GetMember(ObjectIdentityHandle from, string name) { return CallAndHandle(() => { var obj = Unwrap(from); PythonType pyType = (obj as PythonType); if (pyType != null) { foreach (var baseType in pyType.mro()) { PythonType curType = (baseType as PythonType); if (curType != null) { IDictionary<object, object> dict = new DictProxy(curType); object bresult; // reflection can throw while resolving references, ignore the member... // http://pytools.codeplex.com/workitem/612 try { if (dict.TryGetValue(name, out bresult)) { return MakeHandle(bresult); } } catch { } } } } var tracker = obj as NamespaceTracker; if (tracker != null) { object value = NamespaceTrackerOps.GetCustomMember(CodeContext, tracker, name); if (value != OperationFailed.Value) { return MakeHandle(value); } else { return MakeHandle(obj); } } object result; if (TryGetMember(obj, name, true, out result)) { return MakeHandle(result); } return MakeHandle(obj); }); } #endregion #region ReflectedEvent Helpers internal string GetEventDocumentation(ObjectIdentityHandle value) { return CallAndHandle(() => { var eventObj = (ReflectedEvent)Unwrap(value); try { return eventObj.__doc__; } catch (ArgumentException) { // IronPython can throw here if it can't figure out the // path of the assembly this type is defined in. return ""; } }); } internal ObjectIdentityHandle GetEventPythonType(ObjectIdentityHandle value) { return CallAndHandle(() => { var eventObj = (ReflectedEvent)Unwrap(value); return MakeHandle(DynamicHelpers.GetPythonTypeFromType(eventObj.Info.EventHandlerType)); }); } internal ObjectIdentityHandle[] GetEventParameterPythonTypes(ObjectIdentityHandle value) { return CallAndHandle(() => { var eventObj = (ReflectedEvent)Unwrap(value); var parameters = eventObj.Info.EventHandlerType.GetMethod("Invoke").GetParameters(); var res = new ObjectIdentityHandle[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { res[i] = MakeHandle(DynamicHelpers.GetPythonTypeFromType(parameters[i].ParameterType)); } return res; }, () => new ObjectIdentityHandle[0]); } #endregion #region NamespaceTracker Helpers internal string GetNamespaceName(ObjectIdentityHandle ns) { return CallAndHandle(() => { var reflNs = (NamespaceTracker)Unwrap(ns); return reflNs.Name; }); } internal string[] GetNamespaceChildren(ObjectIdentityHandle ns) { return CallAndHandle(() => { List<string> names = new List<string>(); var reflNs = (NamespaceTracker)Unwrap(ns); foreach (var name in reflNs.GetMemberNames() ?? Enumerable.Empty<string>()) { if (reflNs[name] is NamespaceTracker) { names.Add(name); } } return names.ToArray(); }); } #endregion #region TypeGroup Helpers internal bool TypeGroupHasNewOrInitMethods(ObjectIdentityHandle typeGroup) { return CallAndHandle(() => { var value = (TypeGroup)Unwrap(typeGroup); foreach (var type in value.Types) { if (PythonTypeHasNewOrInitMethods(DynamicHelpers.GetPythonTypeFromType(type))) { return true; } } return false; }, false); } internal ObjectIdentityHandle TypeGroupMakeGenericType(ObjectIdentityHandle typeGroup, ObjectIdentityHandle[] types) { return CallAndHandle(() => { var value = (TypeGroup)Unwrap(typeGroup); var genType = value.GetTypeForArity(types.Length); if (genType != null) { Type[] genTypes = new Type[types.Length]; for (int i = 0; i < types.Length; i++) { var o = Unwrap(types[i]); genTypes[i] = o as Type ?? (PythonType)o; } return MakeHandle(DynamicHelpers.GetPythonTypeFromType(genType.Type.MakeGenericType(genTypes))); } return new ObjectIdentityHandle(); }); } internal bool TypeGroupIsGenericTypeDefinition(ObjectIdentityHandle typeGroup) { return CallAndHandle(() => { var value = (TypeGroup)Unwrap(typeGroup); foreach (var type in value.Types) { if (type.IsGenericTypeDefinition) { return true; } } return false; }, false); } internal string GetTypeGroupDocumentation(ObjectIdentityHandle typeGroup) { return CallAndHandle(() => { var value = (TypeGroup)Unwrap(typeGroup); StringBuilder res = new StringBuilder(); foreach (var type in value.Types) { try { res.Append(PythonType.Get__doc__(CodeContext, DynamicHelpers.GetPythonTypeFromType(type)) as string); } catch (ArgumentException) { // IronPython can throw here if it can't figure out the // path of the assembly this type is defined in. } } return res.ToString(); }); } internal string GetTypeGroupName(ObjectIdentityHandle typeGroup) { return CallAndHandle(() => { var value = (TypeGroup)Unwrap(typeGroup); return value.Name; }); } internal string GetTypeGroupDeclaringModule(ObjectIdentityHandle typeGroup) { return CallAndHandle(() => { var value = (TypeGroup)Unwrap(typeGroup); return (string)PythonType.Get__module__( CodeContext, DynamicHelpers.GetPythonTypeFromType(value.Types.First()) ); }); } internal PythonMemberType GetTypeGroupMemberType(ObjectIdentityHandle typeGroup) { return CallAndHandle(() => { var value = (TypeGroup)Unwrap(typeGroup); foreach (var type in value.Types) { if (type.IsEnum) { return PythonMemberType.Enum; } else if (typeof(Delegate).IsAssignableFrom(type)) { return PythonMemberType.Delegate; } } return PythonMemberType.Class; }, PythonMemberType.Class); } internal ObjectIdentityHandle[] GetTypeGroupConstructors(ObjectIdentityHandle typeGroup, out ObjectIdentityHandle declaringType) { var innerDeclaringType = new ObjectIdentityHandle(); declaringType = new ObjectIdentityHandle(); var result = CallAndHandle(() => { var self = (TypeGroup)Unwrap(typeGroup); foreach (var clrType in self.Types) { // just a normal .NET type... var ctors = clrType.GetConstructors(BindingFlags.Public | BindingFlags.CreateInstance | BindingFlags.Instance); if (ctors.Length > 0) { var res = new ObjectIdentityHandle[ctors.Length]; for (int i = 0; i < res.Length; i++) { res[i] = MakeHandle(ctors[i]); } innerDeclaringType = MakeHandle(clrType); return res; } } innerDeclaringType = default(ObjectIdentityHandle); return null; }, (ObjectIdentityHandle[])null); declaringType = innerDeclaringType; return result; } internal ObjectIdentityHandle[] GetTypeGroupEventInvokeArgs(ObjectIdentityHandle typeGroup) { return CallAndHandle(() => { var self = (TypeGroup)Unwrap(typeGroup); foreach (var type in self.Types) { if (typeof(Delegate).IsAssignableFrom(type)) { return GetEventInvokeArgs(type); } } return null; }, (ObjectIdentityHandle[])null); } #endregion #region ReflectedExtensionProperty Helpers internal ObjectIdentityHandle GetExtensionPropertyType(ObjectIdentityHandle value) { return CallAndHandle(() => { var property = (ReflectedExtensionProperty)Unwrap(value); return MakeHandle(property.PropertyType); }); } internal string GetExtensionPropertyDocumentation(ObjectIdentityHandle value) { return CallAndHandle(() => { var property = (ReflectedExtensionProperty)Unwrap(value); try { return property.__doc__; } catch (ArgumentException) { // IronPython can throw here if it can't figure out the // path of the assembly this type is defined in. return ""; } }); } #endregion internal PythonType GetTypeFromType(Type type) { if (type.IsGenericParameter && type.GetInterfaces().Length != 0) { // generic parameter with constraints, IronPython will throw an // exception while constructing the PythonType // http://ironpython.codeplex.com/workitem/30905 // Return the type for the interface return GetTypeFromType(type.GetInterfaces()[0]); } return DynamicHelpers.GetPythonTypeFromType(type); } internal ObjectIdentityHandle GetBuiltinType(BuiltinTypeId id) { return CallAndHandle(() => { switch (id) { case BuiltinTypeId.Bool: return MakeHandle(GetTypeFromType(typeof(bool))); case BuiltinTypeId.BuiltinFunction: return MakeHandle(GetTypeFromType(typeof(BuiltinFunction))); case BuiltinTypeId.BuiltinMethodDescriptor: return MakeHandle(GetTypeFromType(typeof(BuiltinMethodDescriptor))); case BuiltinTypeId.Complex: return MakeHandle(GetTypeFromType(typeof(Complex))); case BuiltinTypeId.Dict: return MakeHandle(GetTypeFromType(typeof(PythonDictionary))); case BuiltinTypeId.Float: return MakeHandle(GetTypeFromType(typeof(double))); case BuiltinTypeId.Function: return MakeHandle(GetTypeFromType(typeof(PythonFunction))); case BuiltinTypeId.Generator: return MakeHandle(GetTypeFromType(typeof(PythonGenerator))); case BuiltinTypeId.Int: return MakeHandle(GetTypeFromType(typeof(int))); case BuiltinTypeId.List: return MakeHandle(GetTypeFromType(typeof(List))); case BuiltinTypeId.Long: return MakeHandle(GetTypeFromType(typeof(System.Numerics.BigInteger))); case BuiltinTypeId.Unknown: return MakeHandle(GetTypeFromType(typeof(DynamicNull))); case BuiltinTypeId.Object: return MakeHandle(GetTypeFromType(typeof(object))); case BuiltinTypeId.Set: return MakeHandle(GetTypeFromType(typeof(SetCollection))); case BuiltinTypeId.FrozenSet: return MakeHandle(GetTypeFromType(typeof(FrozenSetCollection))); case BuiltinTypeId.Str: return MakeHandle(GetTypeFromType(typeof(string))); case BuiltinTypeId.Unicode: return MakeHandle(GetTypeFromType(typeof(string))); case BuiltinTypeId.Bytes: return MakeHandle(GetTypeFromType(typeof(string))); // keep strings and bytes the same on Ipy because '' and u'abc' create the same type case BuiltinTypeId.Tuple: return MakeHandle(GetTypeFromType(typeof(PythonTuple))); case BuiltinTypeId.Type: return MakeHandle(GetTypeFromType(typeof(PythonType))); case BuiltinTypeId.NoneType: return MakeHandle(GetTypeFromType(typeof(DynamicNull))); case BuiltinTypeId.Ellipsis: return MakeHandle(GetTypeFromType(typeof(Ellipsis))); case BuiltinTypeId.DictKeys: return MakeHandle(GetTypeFromType(typeof(DictionaryKeyEnumerator))); case BuiltinTypeId.DictValues: return MakeHandle(GetTypeFromType(typeof(DictionaryValueEnumerator))); case BuiltinTypeId.DictItems: return MakeHandle(GetTypeFromType(typeof(DictionaryItemEnumerator))); case BuiltinTypeId.Module: return MakeHandle(GetTypeFromType(typeof(PythonModule))); case BuiltinTypeId.ListIterator: return MakeHandle(GetTypeFromType(typeof(ListIterator))); case BuiltinTypeId.TupleIterator: return MakeHandle(GetTypeFromType(typeof(TupleEnumerator))); case BuiltinTypeId.SetIterator: return MakeHandle(GetTypeFromType(typeof(SetIterator))); case BuiltinTypeId.StrIterator: return MakeHandle(GetTypeFromType(typeof(IEnumeratorOfTWrapper<string>))); case BuiltinTypeId.BytesIterator: return MakeHandle(GetTypeFromType(typeof(IEnumeratorOfTWrapper<string>))); case BuiltinTypeId.UnicodeIterator: return MakeHandle(GetTypeFromType(typeof(IEnumeratorOfTWrapper<string>))); case BuiltinTypeId.CallableIterator: return MakeHandle(GetTypeFromType(typeof(SentinelIterator))); case BuiltinTypeId.Property: return MakeHandle(GetTypeFromType(typeof(PythonProperty))); case BuiltinTypeId.ClassMethod: return MakeHandle(GetTypeFromType(typeof(classmethod))); case BuiltinTypeId.StaticMethod: return MakeHandle(GetTypeFromType(typeof(staticmethod))); default: return new ObjectIdentityHandle(); } }); } #region MethodBase Helpers internal ObjectIdentityHandle GetBuiltinFunctionOverloadReturnType(ObjectIdentityHandle value) { return CallAndHandle(() => { var overload = (MethodBase)Unwrap(value); MethodInfo mi = overload as MethodInfo; if (mi != null) { return MakeHandle(GetTypeFromType(mi.ReturnType)); } return MakeHandle(GetTypeFromType(overload.DeclaringType)); }); } internal bool IsInstanceExtensionMethod(ObjectIdentityHandle methodBase, ObjectIdentityHandle declaringType) { return CallAndHandle(() => { var target = (MethodBase)Unwrap(methodBase); var type = (PythonType)Unwrap(declaringType); bool isInstanceExtensionMethod = false; if (!target.DeclaringType.IsAssignableFrom(type.__clrtype__())) { isInstanceExtensionMethod = !target.IsDefined(typeof(StaticExtensionMethodAttribute), false); } return isInstanceExtensionMethod; }, false); } internal ObjectIdentityHandle[] GetParametersNoCodeContext(ObjectIdentityHandle methodBase) { return CallAndHandle(() => { var target = (MethodBase)Unwrap(methodBase); var parameters = target.GetParameters(); var res = new List<ObjectIdentityHandle>(parameters.Length); for (int i = 0; i < parameters.Length; i++) { if (res.Count == 0 && parameters[i].ParameterType.FullName == _codeCtxType) { // skip CodeContext variable continue; } res.Add(MakeHandle(parameters[i])); } return res.ToArray(); }, () => new ObjectIdentityHandle[0]); } #endregion #region ParameterInfo Helpers internal string GetParameterName(ObjectIdentityHandle handle) { return CallAndHandle(() => { var parameterInfo = (ParameterInfo)Unwrap(handle); return parameterInfo.Name; }); } internal ParameterKind GetParameterKind(ObjectIdentityHandle handle) { return CallAndHandle(() => { var parameterInfo = (ParameterInfo)Unwrap(handle); if (parameterInfo.IsDefined(typeof(ParamArrayAttribute), false)) { return ParameterKind.List; } else if (parameterInfo.IsDefined(typeof(ParamDictionaryAttribute), false)) { return ParameterKind.Dictionary; } return ParameterKind.Normal; }, ParameterKind.Normal); } internal ObjectIdentityHandle GetParameterPythonType(ObjectIdentityHandle handle) { return CallAndHandle(() => { var parameterInfo = (ParameterInfo)Unwrap(handle); return MakeHandle(DynamicHelpers.GetPythonTypeFromType(parameterInfo.ParameterType)); }); } internal string GetParameterDefaultValue(ObjectIdentityHandle handle) { return CallAndHandle(() => { var parameterInfo = (ParameterInfo)Unwrap(handle); if (parameterInfo.DefaultValue != DBNull.Value && !(parameterInfo.DefaultValue is Missing)) { return PythonOps.Repr(_codeContext, parameterInfo.DefaultValue); } else if (parameterInfo.IsOptional) { object missing = CompilerHelpers.GetMissingValue(parameterInfo.ParameterType); if (missing != Missing.Value) { return PythonOps.Repr(_codeContext, missing); } else { return ""; } } return null; }); } #endregion #region ConstructorInfo Helpers internal ObjectIdentityHandle GetConstructorDeclaringPythonType(ObjectIdentityHandle ctor) { return CallAndHandle(() => { var method = (MethodBase)Unwrap(ctor); return MakeHandle(DynamicHelpers.GetPythonTypeFromType(method.DeclaringType)); }); } #endregion /// <summary> /// Used for assertions only, making sure we're constructing things w/ the correct types. /// </summary> internal bool TypeIs<T>(ObjectIdentityHandle handle) { return CallAndHandle(() => { return Unwrap(handle) is T; }, false); } /// <summary> /// Sets the current list of analysis directories. Returns true if the list changed and the /// module changed event should be raised to the analysis engine. /// </summary> internal SetAnalysisDirectoriesResult SetAnalysisDirectories(string[] dirs) { return CallAndHandle(() => { SetAnalysisDirectoriesResult raiseModuleChangedEvent = SetAnalysisDirectoriesResult.NoChange; if (_analysisDirs != null) { // check if we're removing any dirs, and if we are, re-initialize our namespace object... var newDirs = new HashSet<string>(dirs, StringComparer.OrdinalIgnoreCase); foreach (var dir in _analysisDirs) { lock (_assembliesLoadedFromDirectories) { if (!newDirs.Contains(dir) && _assembliesLoadedFromDirectories.Contains(dir)) { // this directory was removed raiseModuleChangedEvent = SetAnalysisDirectoriesResult.Reload; _assembliesLoadedFromDirectories.Remove(dir); } } } // check if we're adding new dirs, in which case we need to raise the modules change event // in IronPythonInterpreter so that we'll re-analyze all of the files and we can pick up // the new assemblies. if (raiseModuleChangedEvent == SetAnalysisDirectoriesResult.NoChange) { HashSet<string> existing = new HashSet<string>(_analysisDirs); foreach (var dir in dirs) { if (!existing.Contains(dir)) { raiseModuleChangedEvent = SetAnalysisDirectoriesResult.ModulesChanged; break; } } } } else if (dirs.Length > 0) { raiseModuleChangedEvent = SetAnalysisDirectoriesResult.ModulesChanged; } _analysisDirs = dirs; return raiseModuleChangedEvent; }, SetAnalysisDirectoriesResult.NoChange); } internal bool LoadAssemblyReference(string assembly) { try { byte[] symbolStore = null; try { // If PTVS is being debugged, then that debugger will lock // the pdb of the assembly we are loading here. This is a // problem that PTVS developers will see, but PTVS users shouldn't. // Loading the symbol store and passing it in prevents this locking. string symbolStorePath = Path.ChangeExtension(assembly, ".pdb"); if (File.Exists(symbolStorePath)) { symbolStore = File.ReadAllBytes(symbolStorePath); } } catch { } var asm = Assembly.Load(File.ReadAllBytes(assembly), symbolStore); if (asm != null) { _referencedAssemblies[asm.FullName] = asm; _referencedAssemblies[new AssemblyName(asm.FullName).Name] = asm; _referencedAssemblies[assembly] = asm; return true; } } catch { } return false; } internal bool UnloadAssemblyReference(string name) { return CallAndHandle(() => { return _referencedAssemblies.ContainsKey(name); }, false); } internal ObjectIdentityHandle GetBuiltinTypeFromType(Type type) { return CallAndHandle(() => { return MakeHandle(DynamicHelpers.GetPythonTypeFromType(type)); }); } } enum ParameterKind { Unknown, Normal, List, Dictionary } enum ObjectKind { None, Module, Type, ClrType, BuiltinFunction, BuiltinMethodDesc, ReflectedField, ReflectedProperty, ReflectedExtensionProperty, NamespaceTracker, Method, ClassMethod, PythonTypeTypeSlot, ReflectedEvent, PythonTypeSlot, TypeGroup, Constant, ConstructorFunction, Unknown, } enum SetAnalysisDirectoriesResult { NoChange, Reload, ModulesChanged } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace JustRunnerChat.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Media; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.PropertyEditors.ValueConverters; using Umbraco.Extensions; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Web.Common { [TestFixture] public class ImageCropperTest { private const string CropperJson1 = "{\"focalPoint\": {\"left\": 0.96,\"top\": 0.80827067669172936},\"src\": \"/media/1005/img_0671.jpg\",\"crops\": [{\"alias\":\"thumb\",\"width\": 100,\"height\": 100,\"coordinates\": {\"x1\": 0.58729977382575338,\"y1\": 0.055768992440203169,\"x2\": 0,\"y2\": 0.32457553600198386}}]}"; private const string CropperJson2 = "{\"focalPoint\": {\"left\": 0.98,\"top\": 0.80827067669172936},\"src\": \"/media/1005/img_0672.jpg\",\"crops\": [{\"alias\":\"thumb\",\"width\": 100,\"height\": 100,\"coordinates\": {\"x1\": 0.58729977382575338,\"y1\": 0.055768992440203169,\"x2\": 0,\"y2\": 0.32457553600198386}}]}"; private const string CropperJson3 = "{\"focalPoint\": {\"left\": 0.5,\"top\": 0.5},\"src\": \"/media/1005/img_0672.jpg\",\"crops\": []}"; private const string MediaPath = "/media/1005/img_0671.jpg"; [Test] public void CanConvertImageCropperDataSetSrcToString() { // cropperJson3 - has no crops ImageCropperValue cropperValue = CropperJson3.DeserializeImageCropperValue(); Attempt<string> serialized = cropperValue.TryConvertTo<string>(); Assert.IsTrue(serialized.Success); Assert.AreEqual("/media/1005/img_0672.jpg", serialized.Result); } [Test] public void CanConvertImageCropperDataSetJObject() { // cropperJson3 - has no crops ImageCropperValue cropperValue = CropperJson3.DeserializeImageCropperValue(); Attempt<JObject> serialized = cropperValue.TryConvertTo<JObject>(); Assert.IsTrue(serialized.Success); Assert.AreEqual(cropperValue, serialized.Result.ToObject<ImageCropperValue>()); } [Test] public void CanConvertImageCropperDataSetJsonToString() { ImageCropperValue cropperValue = CropperJson1.DeserializeImageCropperValue(); Attempt<string> serialized = cropperValue.TryConvertTo<string>(); Assert.IsTrue(serialized.Success); Assert.IsTrue(serialized.Result.DetectIsJson()); ImageCropperValue obj = JsonConvert.DeserializeObject<ImageCropperValue>(CropperJson1, new JsonSerializerSettings { Culture = CultureInfo.InvariantCulture, FloatParseHandling = FloatParseHandling.Decimal }); Assert.AreEqual(cropperValue, obj); } // [TestCase(CropperJson1, CropperJson1, true)] // [TestCase(CropperJson1, CropperJson2, false)] // public void CanConvertImageCropperPropertyEditor(string val1, string val2, bool expected) // { // try // { // var container = RegisterFactory.Create(); // var composition = new Composition(container, new TypeLoader(), Mock.Of<IProfilingLogger>(), ComponentTests.MockRuntimeState(RuntimeLevel.Run)); // // composition.WithCollectionBuilder<PropertyValueConverterCollectionBuilder>(); // // Current.Factory = composition.CreateFactory(); // // var logger = Mock.Of<ILogger>(); // var scheme = Mock.Of<IMediaPathScheme>(); // var config = Mock.Of<IContentSection>(); // // var mediaFileSystem = new MediaFileSystem(Mock.Of<IFileSystem>(), config, scheme, logger); // // var imageCropperConfiguration = new ImageCropperConfiguration() // { // Crops = new[] // { // new ImageCropperConfiguration.Crop() // { // Alias = "thumb", // Width = 100, // Height = 100 // } // } // }; // var dataTypeService = new TestObjects.TestDataTypeService( // new DataType(new ImageCropperPropertyEditor(Mock.Of<ILogger>(), mediaFileSystem, Mock.Of<IContentSection>(), Mock.Of<IDataTypeService>())) { Id = 1, Configuration = imageCropperConfiguration }); // // var factory = new PublishedContentTypeFactory(Mock.Of<IPublishedModelFactory>(), new PropertyValueConverterCollection(Array.Empty<IPropertyValueConverter>()), dataTypeService); // // var converter = new ImageCropperValueConverter(); // var result = converter.ConvertSourceToIntermediate(null, factory.CreatePropertyType("test", 1), val1, false); // does not use type for conversion // // var resultShouldMatch = val2.DeserializeImageCropperValue(); // if (expected) // { // Assert.AreEqual(resultShouldMatch, result); // } // else // { // Assert.AreNotEqual(resultShouldMatch, result); // } // } // finally // { // Current.Reset(); // } // } [Test] public void GetCropUrl_CropAliasTest() { var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, cropAlias: "Thumb", useCropDimensions: true); Assert.AreEqual(MediaPath + "?c=0.58729977382575338,0.055768992440203169,0,0.32457553600198386&w=100&h=100", urlString); } /// <summary> /// Test to ensure useCropDimensions is observed /// </summary> [Test] public void GetCropUrl_CropAliasIgnoreWidthHeightTest() { var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, cropAlias: "Thumb", useCropDimensions: true, width: 50, height: 50); Assert.AreEqual(MediaPath + "?c=0.58729977382575338,0.055768992440203169,0,0.32457553600198386&w=100&h=100", urlString); } [Test] public void GetCropUrl_WidthHeightTest() { var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 200, height: 300); Assert.AreEqual(MediaPath + "?f=0.80827067669172936,0.96&w=200&h=300", urlString); } [Test] public void GetCropUrl_FocalPointTest() { var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, cropAlias: "thumb", preferFocalPoint: true, useCropDimensions: true); Assert.AreEqual(MediaPath + "?f=0.80827067669172936,0.96&w=100&h=100", urlString); } [Test] public void GetCropUrlFurtherOptionsTest() { var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 200, height: 300, furtherOptions: "filter=comic&roundedcorners=radius-26|bgcolor-fff"); Assert.AreEqual(MediaPath + "?f=0.80827067669172936,0.96&w=200&h=300&filter=comic&roundedcorners=radius-26|bgcolor-fff", urlString); } /// <summary> /// Test that if a crop alias has been specified that doesn't exist the method returns null /// </summary> [Test] public void GetCropUrlNullTest() { var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, cropAlias: "Banner", useCropDimensions: true); Assert.AreEqual(null, urlString); } /// <summary> /// Test the GetCropUrl method on the ImageCropDataSet Model /// </summary> [Test] public void GetBaseCropUrlFromModelTest() { ImageCropperValue cropDataSet = CropperJson1.DeserializeImageCropperValue(); var urlString = cropDataSet.GetCropUrl("thumb", new TestImageUrlGenerator()); Assert.AreEqual("?c=0.58729977382575338,0.055768992440203169,0,0.32457553600198386&w=100&h=100", urlString); } /// <summary> /// Test the height ratio mode with predefined crop dimensions /// </summary> [Test] public void GetCropUrl_CropAliasHeightRatioModeTest() { var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, cropAlias: "Thumb", useCropDimensions: true); Assert.AreEqual(MediaPath + "?c=0.58729977382575338,0.055768992440203169,0,0.32457553600198386&w=100&h=100", urlString); } /// <summary> /// Test the height ratio mode with manual width/height dimensions /// </summary> [Test] public void GetCropUrl_WidthHeightRatioModeTest() { var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150); Assert.AreEqual(MediaPath + "?f=0.80827067669172936,0.96&w=300&h=150", urlString); } /// <summary> /// Test the height ratio mode with width/height dimensions /// </summary> [Test] public void GetCropUrl_HeightWidthRatioModeTest() { var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150); Assert.AreEqual(MediaPath + "?f=0.80827067669172936,0.96&w=300&h=150", urlString); } /// <summary> /// Test that if Crop mode is specified as anything other than Crop the image doesn't use the crop /// </summary> [Test] public void GetCropUrl_SpecifiedCropModeTest() { var urlStringMin = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, imageCropMode: ImageCropMode.Min); var urlStringBoxPad = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, imageCropMode: ImageCropMode.BoxPad); var urlStringPad = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, imageCropMode: ImageCropMode.Pad); var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, imageCropMode: ImageCropMode.Max); var urlStringStretch = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: CropperJson1, width: 300, height: 150, imageCropMode: ImageCropMode.Stretch); Assert.AreEqual(MediaPath + "?m=min&w=300&h=150", urlStringMin); Assert.AreEqual(MediaPath + "?m=boxpad&w=300&h=150", urlStringBoxPad); Assert.AreEqual(MediaPath + "?m=pad&w=300&h=150", urlStringPad); Assert.AreEqual(MediaPath + "?m=max&w=300&h=150", urlString); Assert.AreEqual(MediaPath + "?m=stretch&w=300&h=150", urlStringStretch); } /// <summary> /// Test for upload property type /// </summary> [Test] public void GetCropUrl_UploadTypeTest() { var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), width: 100, height: 270, imageCropMode: ImageCropMode.Crop, imageCropAnchor: ImageCropAnchor.Center); Assert.AreEqual(MediaPath + "?m=crop&a=center&w=100&h=270", urlString); } /// <summary> /// Test for preferFocalPoint when focal point is centered /// </summary> [Test] public void GetCropUrl_PreferFocalPointCenter() { const string cropperJson = "{\"focalPoint\": {\"left\": 0.5,\"top\": 0.5},\"src\": \"/media/1005/img_0671.jpg\",\"crops\": [{\"alias\":\"thumb\",\"width\": 100,\"height\": 100,\"coordinates\": {\"x1\": 0.58729977382575338,\"y1\": 0.055768992440203169,\"x2\": 0,\"y2\": 0.32457553600198386}}]}"; var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: cropperJson, width: 300, height: 150, preferFocalPoint: true); Assert.AreEqual(MediaPath + "?w=300&h=150", urlString); } /// <summary> /// Test to check if height ratio is returned for a predefined crop without coordinates and focal point in centre when a width parameter is passed /// </summary> [Test] public void GetCropUrl_PreDefinedCropNoCoordinatesWithWidth() { const string cropperJson = "{\"focalPoint\": {\"left\": 0.5,\"top\": 0.5},\"src\": \"/media/1005/img_0671.jpg\",\"crops\": [{\"alias\": \"home\",\"width\": 270,\"height\": 161}]}"; var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: cropperJson, cropAlias: "home", width: 200); Assert.AreEqual(MediaPath + "?w=200&h=119", urlString); } /// <summary> /// Test to check if height ratio is returned for a predefined crop without coordinates and focal point is custom when a width parameter is passed /// </summary> [Test] public void GetCropUrl_PreDefinedCropNoCoordinatesWithWidthAndFocalPoint() { const string cropperJson = "{\"focalPoint\": {\"left\": 0.4275,\"top\": 0.41},\"src\": \"/media/1005/img_0671.jpg\",\"crops\": [{\"alias\": \"home\",\"width\": 270,\"height\": 161}]}"; var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: cropperJson, cropAlias: "home", width: 200); Assert.AreEqual(MediaPath + "?f=0.41,0.4275&w=200&h=119", urlString); } /// <summary> /// Test to check if crop ratio is ignored if useCropDimensions is true /// </summary> [Test] public void GetCropUrl_PreDefinedCropNoCoordinatesWithWidthAndFocalPointIgnore() { const string cropperJson = "{\"focalPoint\": {\"left\": 0.4275,\"top\": 0.41},\"src\": \"/media/1005/img_0671.jpg\",\"crops\": [{\"alias\": \"home\",\"width\": 270,\"height\": 161}]}"; var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: cropperJson, cropAlias: "home", width: 200, useCropDimensions: true); Assert.AreEqual(MediaPath + "?f=0.41,0.4275&w=270&h=161", urlString); } /// <summary> /// Test to check if width ratio is returned for a predefined crop without coordinates and focal point in centre when a height parameter is passed /// </summary> [Test] public void GetCropUrl_PreDefinedCropNoCoordinatesWithHeight() { const string cropperJson = "{\"focalPoint\": {\"left\": 0.5,\"top\": 0.5},\"src\": \"/media/1005/img_0671.jpg\",\"crops\": [{\"alias\": \"home\",\"width\": 270,\"height\": 161}]}"; var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: cropperJson, cropAlias: "home", height: 200); Assert.AreEqual(MediaPath + "?w=335&h=200", urlString); } /// <summary> /// Test to check result when only a width parameter is passed, effectivly a resize only /// </summary> [Test] public void GetCropUrl_WidthOnlyParameter() { const string cropperJson = "{\"focalPoint\": {\"left\": 0.5,\"top\": 0.5},\"src\": \"/media/1005/img_0671.jpg\",\"crops\": [{\"alias\": \"home\",\"width\": 270,\"height\": 161}]}"; var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: cropperJson, width: 200); Assert.AreEqual(MediaPath + "?w=200", urlString); } /// <summary> /// Test to check result when only a height parameter is passed, effectivly a resize only /// </summary> [Test] public void GetCropUrl_HeightOnlyParameter() { const string cropperJson = "{\"focalPoint\": {\"left\": 0.5,\"top\": 0.5},\"src\": \"/media/1005/img_0671.jpg\",\"crops\": [{\"alias\": \"home\",\"width\": 270,\"height\": 161}]}"; var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), imageCropperValue: cropperJson, height: 200); Assert.AreEqual(MediaPath + "?h=200", urlString); } /// <summary> /// Test to check result when using a background color with padding /// </summary> [Test] public void GetCropUrl_BackgroundColorParameter() { var cropperJson = "{\"focalPoint\": {\"left\": 0.5,\"top\": 0.5},\"src\": \"" + MediaPath + "\",\"crops\": [{\"alias\": \"home\",\"width\": 270,\"height\": 161}]}"; var urlString = MediaPath.GetCropUrl(new TestImageUrlGenerator(), 400, 400, cropperJson, imageCropMode: ImageCropMode.Pad, furtherOptions: "bgcolor=fff"); Assert.AreEqual(MediaPath + "?m=pad&w=400&h=400&bgcolor=fff", urlString); } internal class TestImageUrlGenerator : IImageUrlGenerator { public IEnumerable<string> SupportedImageFileTypes => new[] { "jpeg", "jpg", "gif", "bmp", "png", "tiff", "tif" }; public string GetImageUrl(ImageUrlGenerationOptions options) { if (options == null) { return null; } var imageUrl = new StringBuilder(options.ImageUrl); bool queryStringHasStarted = false; void AppendQueryString(string value) { imageUrl.Append(queryStringHasStarted ? '&' : '?'); queryStringHasStarted = true; imageUrl.Append(value); } void AddQueryString(string key, params IConvertible[] values) => AppendQueryString(key + '=' + string.Join(",", values.Select(x => x.ToString(CultureInfo.InvariantCulture)))); if (options.Crop != null) { AddQueryString("c", options.Crop.Left, options.Crop.Top, options.Crop.Right, options.Crop.Bottom); } if (options.FocalPoint != null) { AddQueryString("f", options.FocalPoint.Top, options.FocalPoint.Left); } if (options.ImageCropMode.HasValue) { AddQueryString("m", options.ImageCropMode.Value.ToString().ToLowerInvariant()); } if (options.ImageCropAnchor.HasValue) { AddQueryString("a", options.ImageCropAnchor.Value.ToString().ToLowerInvariant()); } if (options.Width != null) { AddQueryString("w", options.Width.Value); } if (options.Height != null) { AddQueryString("h", options.Height.Value); } if (options.Quality.HasValue) { AddQueryString("q", options.Quality.Value); } if (options.FurtherOptions != null) { AppendQueryString(options.FurtherOptions.TrimStart('?', '&')); } if (options.CacheBusterValue != null) { AddQueryString("v", options.CacheBusterValue); } return imageUrl.ToString(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.NetCore.Extensions; namespace System.Tests { public class EnvironmentTests : RemoteExecutorTestBase { [Fact] public void CurrentDirectory_Null_Path_Throws_ArgumentNullException() { Assert.Throws<ArgumentNullException>("value", () => Environment.CurrentDirectory = null); } [Fact] public void CurrentDirectory_Empty_Path_Throws_ArgumentException() { Assert.Throws<ArgumentException>("value", () => Environment.CurrentDirectory = string.Empty); } [Fact] public void CurrentDirectory_SetToNonExistentDirectory_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => Environment.CurrentDirectory = GetTestFilePath()); } [Fact] public void CurrentDirectory_SetToValidOtherDirectory() { RemoteInvoke(() => { Environment.CurrentDirectory = TestDirectory; Assert.Equal(Directory.GetCurrentDirectory(), Environment.CurrentDirectory); if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current // directory to a symlinked path will result in GetCurrentDirectory returning the absolute // path that followed the symlink. Assert.Equal(TestDirectory, Directory.GetCurrentDirectory()); } return SuccessExitCode; }).Dispose(); } [Fact] public void CurrentManagedThreadId_Idempotent() { Assert.Equal(Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId); } [Fact] public void CurrentManagedThreadId_DifferentForActiveThreads() { var ids = new HashSet<int>(); Barrier b = new Barrier(10); Task.WaitAll((from i in Enumerable.Range(0, b.ParticipantCount) select Task.Factory.StartNew(() => { b.SignalAndWait(); lock (ids) ids.Add(Environment.CurrentManagedThreadId); b.SignalAndWait(); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray()); Assert.Equal(b.ParticipantCount, ids.Count); } [Fact] public void HasShutdownStarted_FalseWhileExecuting() { Assert.False(Environment.HasShutdownStarted); } [Fact] public void Is64BitProcess_MatchesIntPtrSize() { Assert.Equal(IntPtr.Size == 8, Environment.Is64BitProcess); } [Fact] public void Is64BitOperatingSystem_TrueIf64BitProcess() { if (Environment.Is64BitProcess) { Assert.True(Environment.Is64BitOperatingSystem); } } [Fact] [PlatformSpecific(Xunit.PlatformID.AnyUnix)] public void Is64BitOperatingSystem_Unix_TrueIff64BitProcess() { Assert.Equal(Environment.Is64BitProcess, Environment.Is64BitOperatingSystem); } [Fact] public void OSVersion_Idempotent() { Assert.Same(Environment.OSVersion, Environment.OSVersion); } [Fact] public void OSVersion_MatchesPlatform() { PlatformID id = Environment.OSVersion.Platform; Assert.Equal( RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PlatformID.Win32NT : PlatformID.Unix, id); } [Fact] public void OSVersion_ValidVersion() { Version version = Environment.OSVersion.Version; string versionString = Environment.OSVersion.VersionString; Assert.False(string.IsNullOrWhiteSpace(versionString), "Expected non-empty version string"); Assert.True(version.Major > 0); Assert.Contains(version.ToString(2), versionString); Assert.Contains(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" : "Unix", versionString); } [Fact] public void SystemPageSize_Valid() { int pageSize = Environment.SystemPageSize; Assert.Equal(pageSize, Environment.SystemPageSize); Assert.True(pageSize > 0, "Expected positive page size"); Assert.True((pageSize & (pageSize - 1)) == 0, "Expected power-of-2 page size"); } [Fact] public void UserInteractive_True() { Assert.True(Environment.UserInteractive); } [Fact] public void UserName_Valid() { Assert.False(string.IsNullOrWhiteSpace(Environment.UserName)); } [Fact] public void UserDomainName_Valid() { Assert.False(string.IsNullOrWhiteSpace(Environment.UserDomainName)); } [Fact] [PlatformSpecific(Xunit.PlatformID.AnyUnix)] public void UserDomainName_Unix_MatchesMachineName() { Assert.Equal(Environment.MachineName, Environment.UserDomainName); } [Fact] public void Version_MatchesFixedVersion() { Assert.Equal(new Version(4, 0, 30319, 42000), Environment.Version); } [Fact] public void WorkingSet_Valid() { Assert.True(Environment.WorkingSet > 0, "Expected positive WorkingSet value"); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process [OuterLoop] [Fact] public void FailFast_ExpectFailureExitCode() { using (Process p = RemoteInvoke(() => { Environment.FailFast("message"); return SuccessExitCode; }).Process) { p.WaitForExit(); Assert.NotEqual(SuccessExitCode, p.ExitCode); } using (Process p = RemoteInvoke(() => { Environment.FailFast("message", new Exception("uh oh")); return SuccessExitCode; }).Process) { p.WaitForExit(); Assert.NotEqual(SuccessExitCode, p.ExitCode); } } [Fact] [PlatformSpecific(Xunit.PlatformID.AnyUnix)] public void GetFolderPath_Unix_PersonalIsHomeAndUserProfile() { Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.Personal)); Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); } [Theory] [PlatformSpecific(Xunit.PlatformID.AnyUnix)] [InlineData(Environment.SpecialFolder.UserProfile, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.Personal, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.CommonTemplates, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Desktop, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.DesktopDirectory, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Templates, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyVideos, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyMusic, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Fonts, Environment.SpecialFolderOption.DoNotVerify)] public void GetFolderPath_Unix_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option) { Assert.NotEmpty(Environment.GetFolderPath(folder, option)); if (option == Environment.SpecialFolderOption.None) { Assert.NotEmpty(Environment.GetFolderPath(folder)); } } [Theory] [PlatformSpecific(Xunit.PlatformID.OSX)] [InlineData(Environment.SpecialFolder.Favorites, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.InternetCache, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.None)] public void GetFolderPath_OSX_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option) { Assert.NotEmpty(Environment.GetFolderPath(folder, option)); if (option == Environment.SpecialFolderOption.None) { Assert.NotEmpty(Environment.GetFolderPath(folder)); } } // The commented out folders aren't set on all systems. [Theory] [InlineData(Environment.SpecialFolder.ApplicationData)] [InlineData(Environment.SpecialFolder.CommonApplicationData)] [InlineData(Environment.SpecialFolder.LocalApplicationData)] [InlineData(Environment.SpecialFolder.Cookies)] [InlineData(Environment.SpecialFolder.Desktop)] [InlineData(Environment.SpecialFolder.Favorites)] [InlineData(Environment.SpecialFolder.History)] [InlineData(Environment.SpecialFolder.InternetCache)] [InlineData(Environment.SpecialFolder.Programs)] // [InlineData(Environment.SpecialFolder.MyComputer)] [InlineData(Environment.SpecialFolder.MyMusic)] [InlineData(Environment.SpecialFolder.MyPictures)] [InlineData(Environment.SpecialFolder.MyVideos)] [InlineData(Environment.SpecialFolder.Recent)] [InlineData(Environment.SpecialFolder.SendTo)] [InlineData(Environment.SpecialFolder.StartMenu)] [InlineData(Environment.SpecialFolder.Startup)] [InlineData(Environment.SpecialFolder.System)] [InlineData(Environment.SpecialFolder.Templates)] [InlineData(Environment.SpecialFolder.DesktopDirectory)] [InlineData(Environment.SpecialFolder.Personal)] [InlineData(Environment.SpecialFolder.ProgramFiles)] [InlineData(Environment.SpecialFolder.CommonProgramFiles)] [InlineData(Environment.SpecialFolder.AdminTools)] [InlineData(Environment.SpecialFolder.CDBurning)] [InlineData(Environment.SpecialFolder.CommonAdminTools)] [InlineData(Environment.SpecialFolder.CommonDocuments)] [InlineData(Environment.SpecialFolder.CommonMusic)] // [InlineData(Environment.SpecialFolder.CommonOemLinks)] [InlineData(Environment.SpecialFolder.CommonPictures)] [InlineData(Environment.SpecialFolder.CommonStartMenu)] [InlineData(Environment.SpecialFolder.CommonPrograms)] [InlineData(Environment.SpecialFolder.CommonStartup)] [InlineData(Environment.SpecialFolder.CommonDesktopDirectory)] [InlineData(Environment.SpecialFolder.CommonTemplates)] [InlineData(Environment.SpecialFolder.CommonVideos)] [InlineData(Environment.SpecialFolder.Fonts)] [InlineData(Environment.SpecialFolder.NetworkShortcuts)] // [InlineData(Environment.SpecialFolder.PrinterShortcuts)] [InlineData(Environment.SpecialFolder.UserProfile)] [InlineData(Environment.SpecialFolder.CommonProgramFilesX86)] [InlineData(Environment.SpecialFolder.ProgramFilesX86)] [InlineData(Environment.SpecialFolder.Resources)] // [InlineData(Environment.SpecialFolder.LocalizedResources)] [InlineData(Environment.SpecialFolder.SystemX86)] [InlineData(Environment.SpecialFolder.Windows)] [PlatformSpecific(Xunit.PlatformID.Windows)] public unsafe void GetFolderPath_Windows(Environment.SpecialFolder folder) { string knownFolder = Environment.GetFolderPath(folder); Assert.NotEmpty(knownFolder); // Call the older folder API to compare our results. char* buffer = stackalloc char[260]; SHGetFolderPathW(IntPtr.Zero, (int)folder, IntPtr.Zero, 0, buffer); string folderPath = new string(buffer); Assert.Equal(folderPath, knownFolder); } [Fact] [PlatformSpecific(Xunit.PlatformID.AnyUnix)] public void GetLogicalDrives_Unix_AtLeastOneIsRoot() { string[] drives = Environment.GetLogicalDrives(); Assert.NotNull(drives); Assert.True(drives.Length > 0, "Expected at least one drive"); Assert.All(drives, d => Assert.NotNull(d)); Assert.Contains(drives, d => d == "/"); } [Fact] [PlatformSpecific(Xunit.PlatformID.Windows)] public void GetLogicalDrives_Windows_MatchesExpectedLetters() { string[] drives = Environment.GetLogicalDrives(); uint mask = (uint)GetLogicalDrives(); var bits = new BitArray(new[] { (int)mask }); Assert.Equal(bits.Cast<bool>().Count(b => b), drives.Length); for (int bit = 0, d = 0; bit < bits.Length; bit++) { if (bits[bit]) { Assert.Contains((char)('A' + bit), drives[d++]); } } } [DllImport("api-ms-win-core-file-l1-1-0.dll", SetLastError = true)] internal static extern int GetLogicalDrives(); [DllImport("shell32.dll", SetLastError = false, BestFitMapping = false, ExactSpelling = true)] internal unsafe static extern int SHGetFolderPathW( IntPtr hwndOwner, int nFolder, IntPtr hToken, uint dwFlags, char* pszPath); } }
#region /* Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu. All rights reserved. http://code.google.com/p/msnp-sharp/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of Bas Geertsema or Xih Solutions nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.Text; using System.Collections; using System.Diagnostics; namespace MSNPSharp.Core { using MSNPSharp; using MSNPSharp.P2P; [Serializable()] public class NSMessage : MSNMessage, ICloneable { public NSMessage() : base() { } public NSMessage(string command, ArrayList commandValues) : base(command, commandValues) { } public NSMessage(string command, string[] commandValues) : base(command, new ArrayList(commandValues)) { } public NSMessage(string command) : base() { Command = command; } public override string ToString() { return base.ToString(); } /// <summary> /// /// </summary> /// <returns></returns> public override byte[] GetBytes() { switch (Command) { case "PNG": return System.Text.Encoding.UTF8.GetBytes("PNG\r\n"); default: return base.GetBytes(); } } public override void ParseBytes(byte[] data) { base.ParseBytes(data); if (InnerBody != null) { switch (Command) { case "MSG": ParseMSGMessage(this); break; case "SDG": ParseSDGMessage(this); break; default: ParseTextPayloadMessage(this); break; } } } private NetworkMessage ParseMSGMessage(NSMessage message) { MimeMessage mimeMessage = new MimeMessage(); mimeMessage.CreateFromParentMessage(message); string mime = mimeMessage.MimeHeader[MIMEContentHeaders.ContentType].ToString(); if (mime.IndexOf("text/x-msmsgsprofile") >= 0) { //This is profile, the content is nothing. } else { MimeMessage innerMimeMessage = new MimeMessage(false); innerMimeMessage.CreateFromParentMessage(mimeMessage); } return message; } private NetworkMessage ParseTextPayloadMessage(NSMessage message) { TextPayloadMessage txtPayLoad = new TextPayloadMessage(string.Empty); txtPayLoad.CreateFromParentMessage(message); return message; } private MultiMimeMessage ParseSDGCustomEmoticonMessage(MultiMimeMessage multiMimeMessage) { EmoticonMessage emoticonMessage = new EmoticonMessage(); emoticonMessage.CreateFromParentMessage(multiMimeMessage); emoticonMessage.EmoticonType = multiMimeMessage.ContentHeaders[MIMEContentHeaders.ContentType] == "text/x-mms-animemoticon" ? EmoticonType.AnimEmoticon : EmoticonType.StaticEmoticon; return multiMimeMessage; } private NetworkMessage ParseSDGMessage(NSMessage nsMessage) { MultiMimeMessage multiMimeMessage = new MultiMimeMessage(); multiMimeMessage.CreateFromParentMessage(nsMessage); if (multiMimeMessage.ContentHeaders.ContainsKey(MIMEContentHeaders.MessageType)) { switch (multiMimeMessage.ContentHeaders[MIMEContentHeaders.MessageType].ToString()) { default: Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, "[ParseSDGMessage] Cannot parse this type of SDG message: \r\n" + multiMimeMessage.ContentHeaders[MIMEContentHeaders.MessageType].ToString() + "\r\n\r\nMessage Body: \r\n\r\n" + multiMimeMessage.ToDebugString()); break; case MessageTypes.Nudge: case MessageTypes.ControlTyping: case MessageTypes.Wink: case MessageTypes.SignalCloseIMWindow: // Pure Text body, nothing to parse. ParseSDGTextPayloadMessage(multiMimeMessage); break; case MessageTypes.Text: // Set the TextMessage as its InnerMessage. ParseSDGTextMessage(multiMimeMessage); break; case MessageTypes.CustomEmoticon: // Set the EmoticonMessage as its InnerMessage. ParseSDGCustomEmoticonMessage(multiMimeMessage); break; case MessageTypes.SignalP2P: // Add the SLPMessage as its InnerMessage. ParseSDGP2PSignalMessage(multiMimeMessage); break; case MessageTypes.Data: //OnSDGDataMessageReceived(multiMimeMessage, sender, by, routingInfo); break; } } return nsMessage; } private MultiMimeMessage ParseSDGTextPayloadMessage(MultiMimeMessage multiMimeMessage) { TextPayloadMessage textPayloadMessage = new TextPayloadMessage(); textPayloadMessage.CreateFromParentMessage(multiMimeMessage); return multiMimeMessage; } private MultiMimeMessage ParseSDGTextMessage(MultiMimeMessage multiMimeMessage) { TextMessage txtMessage = new TextMessage(); txtMessage.CreateFromParentMessage(multiMimeMessage); return multiMimeMessage; } private MultiMimeMessage ParseSDGP2PSignalMessage(MultiMimeMessage multiMimeMessage) { SLPMessage slpMessage = SLPMessage.Parse(multiMimeMessage.InnerBody); slpMessage.CreateFromParentMessage(multiMimeMessage); return multiMimeMessage; } #region ICloneable object ICloneable.Clone() { NSMessage messageClone = new NSMessage(); messageClone.ParseBytes(GetBytes()); if (messageClone.InnerBody == null && InnerBody != null) { messageClone.InnerBody = new byte[InnerBody.Length]; Buffer.BlockCopy(InnerBody, 0, messageClone.InnerBody, 0, InnerBody.Length); } return messageClone; } #endregion } };
// Transport Security Layer (TLS) // Copyright (c) 2003-2004 Carlos Guzman Alvarez // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Mono.Security.Protocol.Tls.Handshake; namespace Mono.Security.Protocol.Tls { public class SslServerStream : Stream, IDisposable { #region Internal Events internal event CertificateValidationCallback ClientCertValidation; internal event PrivateKeySelectionCallback PrivateKeySelection; #endregion #region Fields private ServerRecordProtocol protocol; private BufferedStream inputBuffer; private ServerContext context; private Stream innerStream; private bool disposed; private bool ownsStream; private bool checkCertRevocationStatus; private object read; private object write; #endregion #region Properties public override bool CanRead { get { return this.innerStream.CanRead; } } public override bool CanWrite { get { return this.innerStream.CanWrite; } } public override bool CanSeek { get { return this.innerStream.CanSeek; } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } #endregion #region Security Properties public bool CheckCertRevocationStatus { get { return this.checkCertRevocationStatus ; } set { this.checkCertRevocationStatus = value; } } public CipherAlgorithmType CipherAlgorithm { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Cipher.CipherAlgorithmType; } return CipherAlgorithmType.None; } } public int CipherStrength { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Cipher.EffectiveKeyBits; } return 0; } } public X509Certificate ClientCertificate { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.ClientSettings.ClientCertificate; } return null; } } public HashAlgorithmType HashAlgorithm { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Cipher.HashAlgorithmType; } return HashAlgorithmType.None; } } public int HashStrength { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Cipher.HashSize * 8; } return 0; } } public int KeyExchangeStrength { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.ServerSettings.Certificates[0].RSA.KeySize; } return 0; } } public ExchangeAlgorithmType KeyExchangeAlgorithm { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Cipher.ExchangeAlgorithmType; } return ExchangeAlgorithmType.None; } } public SecurityProtocolType SecurityProtocol { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.SecurityProtocol; } return 0; } } public X509Certificate ServerCertificate { get { if (this.context.HandshakeState == HandshakeState.Finished) { if (this.context.ServerSettings.Certificates != null && this.context.ServerSettings.Certificates.Count > 0) { return new X509Certificate(this.context.ServerSettings.Certificates[0].RawData); } } return null; } } #endregion #region Callback Properties public CertificateValidationCallback ClientCertValidationDelegate { get { return this.ClientCertValidation; } set { this.ClientCertValidation = value; } } public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate { get { return this.PrivateKeySelection; } set { this.PrivateKeySelection = value; } } #endregion #region Constructors public SslServerStream( Stream stream, X509Certificate serverCertificate) : this( stream, serverCertificate, false, false, SecurityProtocolType.Default) { } public SslServerStream( Stream stream, X509Certificate serverCertificate, bool clientCertificateRequired, bool ownsStream): this( stream, serverCertificate, clientCertificateRequired, ownsStream, SecurityProtocolType.Default) { } public SslServerStream( Stream stream, X509Certificate serverCertificate, bool clientCertificateRequired, bool ownsStream, SecurityProtocolType securityProtocolType) { if (stream == null) { throw new ArgumentNullException("stream is null."); } if (!stream.CanRead || !stream.CanWrite) { throw new ArgumentNullException("stream is not both readable and writable."); } this.context = new ServerContext( this, securityProtocolType, serverCertificate, clientCertificateRequired); this.inputBuffer = new BufferedStream(new MemoryStream()); this.innerStream = stream; this.ownsStream = ownsStream; this.read = new object (); this.write = new object (); this.protocol = new ServerRecordProtocol(innerStream, context); } #endregion #region Finalizer ~SslServerStream() { this.Dispose(false); } #endregion #region IDisposable Methods void IDisposable.Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (this.innerStream != null) { if (this.context.HandshakeState == HandshakeState.Finished) { // Write close notify this.protocol.SendAlert(AlertDescription.CloseNotify); } if (this.ownsStream) { // Close inner stream this.innerStream.Close(); } } this.ownsStream = false; this.innerStream = null; this.ClientCertValidation = null; this.PrivateKeySelection = null; } this.disposed = true; } } #endregion #region Methods public override IAsyncResult BeginRead( byte[] buffer, int offset, int count, AsyncCallback callback, object state) { this.checkDisposed(); if (buffer == null) { throw new ArgumentNullException("buffer is a null reference."); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset is less than 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset is greater than the length of buffer."); } if (count < 0) { throw new ArgumentOutOfRangeException("count is less than 0."); } if (count > (buffer.Length - offset)) { throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter."); } lock (this) { if (this.context.HandshakeState == HandshakeState.None) { this.doHandshake(); // Handshake negotiation } } IAsyncResult asyncResult; lock (this.read) { try { // If actual buffer is full readed reset it if (this.inputBuffer.Position == this.inputBuffer.Length && this.inputBuffer.Length > 0) { this.resetBuffer(); } if (!this.context.ConnectionEnd) { // Check if we have space in the middle buffer // if not Read next TLS record and update the inputBuffer while ((this.inputBuffer.Length - this.inputBuffer.Position) < count) { // Read next record and write it into the inputBuffer long position = this.inputBuffer.Position; byte[] record = this.protocol.ReceiveRecord(this.innerStream); if (record != null && record.Length > 0) { // Write new data to the inputBuffer this.inputBuffer.Seek(0, SeekOrigin.End); this.inputBuffer.Write(record, 0, record.Length); // Restore buffer position this.inputBuffer.Seek(position, SeekOrigin.Begin); } else { if (record == null) { break; } } // TODO: Review if we need to check the Length // property of the innerStream for other types // of streams, to check that there are data available // for read if (this.innerStream is NetworkStream && !((NetworkStream)this.innerStream).DataAvailable) { break; } } } asyncResult = this.inputBuffer.BeginRead( buffer, offset, count, callback, state); } catch (TlsException ex) { this.protocol.SendAlert(ex.Alert); this.Close(); throw new IOException("The authentication or decryption has failed."); } catch (Exception) { throw new IOException("IO exception during read."); } } return asyncResult; } public override IAsyncResult BeginWrite( byte[] buffer, int offset, int count, AsyncCallback callback, object state) { this.checkDisposed(); if (buffer == null) { throw new ArgumentNullException("buffer is a null reference."); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset is less than 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset is greater than the length of buffer."); } if (count < 0) { throw new ArgumentOutOfRangeException("count is less than 0."); } if (count > (buffer.Length - offset)) { throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter."); } lock (this) { if (this.context.HandshakeState == HandshakeState.None) { // Start handshake negotiation this.doHandshake(); } } IAsyncResult asyncResult; lock (this.write) { try { // Send the buffer as a TLS record byte[] record = this.protocol.EncodeRecord( ContentType.ApplicationData, buffer, offset, count); asyncResult = this.innerStream.BeginWrite( record, 0, record.Length, callback, state); } catch (TlsException ex) { this.protocol.SendAlert(ex.Alert); this.Close(); throw new IOException("The authentication or decryption has failed."); } catch (Exception) { throw new IOException("IO exception during Write."); } } return asyncResult; } public override int EndRead(IAsyncResult asyncResult) { this.checkDisposed(); if (asyncResult == null) { throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead."); } return this.inputBuffer.EndRead(asyncResult); } public override void EndWrite(IAsyncResult asyncResult) { this.checkDisposed(); if (asyncResult == null) { throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead."); } this.innerStream.EndWrite (asyncResult); } public override void Close() { ((IDisposable)this).Dispose(); } public override void Flush() { this.checkDisposed(); this.innerStream.Flush(); } public int Read(byte[] buffer) { return this.Read(buffer, 0, buffer.Length); } public override int Read(byte[] buffer, int offset, int count) { IAsyncResult res = this.BeginRead(buffer, offset, count, null, null); return this.EndRead(res); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public void Write(byte[] buffer) { this.Write(buffer, 0, buffer.Length); } public override void Write(byte[] buffer, int offset, int count) { IAsyncResult res = this.BeginWrite (buffer, offset, count, null, null); this.EndWrite(res); } #endregion #region Misc Methods private void resetBuffer() { this.inputBuffer.SetLength(0); this.inputBuffer.Position = 0; } private void checkDisposed() { if (this.disposed) { throw new ObjectDisposedException("The SslClientStream is closed."); } } #endregion #region Handsake Methods /* Client Server ClientHello --------> ServerHello Certificate* ServerKeyExchange* CertificateRequest* <-------- ServerHelloDone Certificate* ClientKeyExchange CertificateVerify* [ChangeCipherSpec] Finished --------> [ChangeCipherSpec] <-------- Finished Application Data <-------> Application Data Fig. 1 - Message flow for a full handshake */ private void doHandshake() { try { // Reset the context if needed if (this.context.HandshakeState != HandshakeState.None) { this.context.Clear(); } // Obtain supported cipher suites this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(this.context.SecurityProtocol); // Set handshake state this.context.HandshakeState = HandshakeState.Started; // Receive Client Hello message this.protocol.ReceiveRecord (this.innerStream); // If received message is not an ClientHello send a // Fatal Alert if (this.context.LastHandshakeMsg != HandshakeType.ClientHello) { this.protocol.SendAlert(AlertDescription.UnexpectedMessage); } // Send ServerHello message this.protocol.SendRecord(HandshakeType.ServerHello); // Send ServerCertificate message this.protocol.SendRecord(HandshakeType.Certificate); // If the negotiated cipher is a KeyEx cipher send ServerKeyExchange if (this.context.Cipher.ExchangeAlgorithmType == ExchangeAlgorithmType.RsaKeyX) { this.protocol.SendRecord(HandshakeType.ServerKeyExchange); } // If the negotiated cipher is a KeyEx cipher or // the client certificate is required send the CertificateRequest message if (this.context.Cipher.ExchangeAlgorithmType == ExchangeAlgorithmType.RsaKeyX || this.context.ClientCertificateRequired) { this.protocol.SendRecord(HandshakeType.CertificateRequest); } // Send ServerHelloDone message this.protocol.SendRecord(HandshakeType.ServerHelloDone); // Receive client response, until the Client Finished message // is received while (this.context.LastHandshakeMsg != HandshakeType.Finished) { this.protocol.ReceiveRecord (this.innerStream); } // Send ChangeCipherSpec and ServerFinished messages this.protocol.SendChangeCipherSpec(); // The handshake is finished this.context.HandshakeState = HandshakeState.Finished; // Clear Key Info this.context.ClearKeyInfo(); } catch (TlsException ex) { this.protocol.SendAlert(ex.Alert); this.Close(); throw new IOException("The authentication or decryption has failed."); } catch (Exception) { this.protocol.SendAlert(AlertDescription.InternalError); this.Close(); throw new IOException("The authentication or decryption has failed."); } } #endregion #region Event Methods internal bool RaiseClientCertificateValidation( X509Certificate certificate, int[] certificateErrors) { if (this.ClientCertValidation != null) { return this.ClientCertValidation(certificate, certificateErrors); } return (certificateErrors != null && certificateErrors.Length == 0); } internal AsymmetricAlgorithm RaisePrivateKeySelection( X509Certificate certificate, string targetHost) { if (this.PrivateKeySelection != null) { return this.PrivateKeySelection(certificate, targetHost); } return null; } #endregion } }
#region File Description //----------------------------------------------------------------------------- // ScreenManager.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Linq; using System.Diagnostics; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input.Touch; using System.IO; #if WINDOWS8 using Windows.Storage; using System.Threading.Tasks; #else using System.IO.IsolatedStorage; #endif using XNA8DFramework; #if !IPHONE && !SILVERLIGHT using System.Xml.Linq; #endif #endregion namespace GameStateManagement { /// <summary> /// The screen manager is a component which manages one or more GameScreen /// instances. It maintains a stack of screens, calls their Update and Draw /// methods at the appropriate times, and automatically routes input to the /// topmost active screen. /// </summary> public class ScreenManager : DrawableGameComponent { #region Fields private const string StateFilename = "ScreenManagerState.xml"; readonly List<GameScreen> _screens = new List<GameScreen>(); readonly List<GameScreen> _tempScreensList = new List<GameScreen>(); readonly InputService _input; SpriteBatch _spriteBatch; SpriteFont _font; readonly string _fontName; Texture2D _blankTexture; GraphicsDeviceManager _graphics; ContentManager _content; bool _isInitialized; bool _traceEnabled; #endregion #region Properties /// <summary> /// A default SpriteBatch shared by all the screens. This saves /// each screen having to bother creating their own local instance. /// </summary> public SpriteBatch SpriteBatch { get { return _spriteBatch; } } /// <summary> /// A default font shared by all the screens. This saves /// each screen having to bother loading their own local copy. /// </summary> public SpriteFont Font { get { return _font; } } public GraphicsDeviceManager Graphics { get { return _graphics; } } /// <summary> /// If true, the manager prints out a list of all the screens /// each time it is updated. This can be useful for making sure /// everything is being added and removed at the right times. /// </summary> public bool TraceEnabled { get { return _traceEnabled; } set { _traceEnabled = value; } } public bool SuppressInputUpdate { get; set; } #if IPHONE public bool FixScaleIPhone { get; set; } #endif #endregion #region Initialization /// <summary> /// Constructs a new screen manager component. /// </summary> public ScreenManager(Game game, string fontName) : base(game) { _fontName = fontName; _input = new InputService(game); _input.Initialize(); SuppressInputUpdate = false; ScrollableGame.Input = _input; game.Services.AddService(typeof(InputService), _input); #if WINDOWS_PHONE || WINDOWS || ANDROID TouchPanel.EnabledGestures = GestureType.None; #endif #if IPHONE FixScaleIPhone = true; #endif } /// <summary> /// Initializes the screen manager component. /// </summary> public override void Initialize() { _graphics = Game.Services.GetService(typeof(IGraphicsDeviceManager)) as GraphicsDeviceManager; base.Initialize(); UpdateTouchPanelSize(); _isInitialized = true; } private void UpdateTouchPanelSize() { #if ANDROID if (GraphicsDevice.Viewport.Width != TouchPanel.DisplayWidth) TouchPanel.DisplayWidth = GraphicsDevice.Viewport.Width; if (GraphicsDevice.Viewport.Height != TouchPanel.DisplayHeight) TouchPanel.DisplayHeight = GraphicsDevice.Viewport.Height; #endif } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { _content = new ContentManager(Game.Services, Game.Content.RootDirectory); _spriteBatch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch; try { _font = _content.Load<SpriteFont>(_fontName).Fix(); } catch(Exception e) { Debug.WriteLine("ScreenManager's font not loaded. Error: " + e); } _blankTexture = new Texture2D(Game.GraphicsDevice, 1, 1); _blankTexture.SetData(new[] { Color.White }); // Tell each of the screens to load their content. foreach (GameScreen screen in _screens) { if (screen.content == null) screen.content = new ContentManager(Game.Services, Game.Content.RootDirectory); screen.Activate(false); } } /// <summary> /// Unload your graphics content. /// </summary> protected override void UnloadContent() { // Tell each of the screens to unload their content. foreach (GameScreen screen in _screens) { screen.Unload(); } } #endregion #region Update and Draw /// <summary> /// Allows each screen to run logic. /// </summary> public override void Update(GameTime gameTime) { UpdateTouchPanelSize(); // Read the keyboard and gamepad. if (!SuppressInputUpdate) _input.Update(gameTime); SuppressInputUpdate = false; // Make a copy of the master screen list, to avoid confusion if // the process of updating one screen adds or removes others. _tempScreensList.Clear(); foreach (GameScreen screen in _screens) _tempScreensList.Add(screen); bool otherScreenHasFocus = !Game.IsActive; bool coveredByOtherScreen = false; // Loop as long as there are screens waiting to be updated. while (_tempScreensList.Count > 0) { // Pop the topmost screen off the waiting list. GameScreen screen = _tempScreensList[_tempScreensList.Count - 1]; _tempScreensList.RemoveAt(_tempScreensList.Count - 1); // Update the screen. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); if (screen.ScreenState == ScreenState.TransitionOn || screen.ScreenState == ScreenState.Active) { // If this is the first active screen we came across, // give it a chance to handle input. if (!otherScreenHasFocus) { screen.HandleInput(gameTime, _input); otherScreenHasFocus = true; } // If this is an active non-popup, inform any subsequent // screens that they are covered by it. if (!screen.IsPopup) coveredByOtherScreen = true; } } ScrollableGame.End(); // Print debug trace? if (_traceEnabled) TraceScreens(); } /// <summary> /// Prints a list of all the screens, for debugging. /// </summary> void TraceScreens() { //var screenNames = new List<string>(); //foreach (GameScreen screen in _screens) // screenNames.Add(screen.GetType().Name); //Debug.WriteLine(string.Join(", ", screenNames.ToArray())); Debug.WriteLine(string.Join(", ", _screens.Select(screen => screen.GetType().Name).ToArray())); } /// <summary> /// Tells each screen to draw itself. /// </summary> public override void Draw(GameTime gameTime) { foreach (GameScreen screen in _screens) { if (screen.ScreenState == ScreenState.Hidden) continue; screen.Draw(gameTime); } } #endregion #region Public Methods /// <summary> /// Adds a new screen to the screen manager. /// </summary> public void AddScreen(GameScreen screen) { screen.ScreenManager = this; screen.IsExiting = false; // If we have a graphics device, tell the screen to load content. if (_isInitialized) { if (screen.content == null) screen.content = new ContentManager(Game.Services, Game.Content.RootDirectory); screen.Activate(false); } _screens.Add(screen); #if WINDOWS_PHONE || WINDOWS || ANDROID // update the TouchPanel to respond to gestures this screen is interested in TouchPanel.EnabledGestures = screen.EnabledGestures; #endif } public void AddOnlyOne<T>(T screen) where T : GameScreen { if (_screens.Count(s => s is T) == 0) AddScreen(screen); } /// <summary> /// Removes a screen from the screen manager. You should normally /// use GameScreen.ExitScreen instead of calling this directly, so /// the screen can gradually transition off rather than just being /// instantly removed. /// </summary> public void RemoveScreen(GameScreen screen) { // If we have a graphics device, tell the screen to unload content. if (_isInitialized) { screen.Unload(); } _screens.Remove(screen); _tempScreensList.Remove(screen); #if WINDOWS_PHONE || WINDOWS || ANDROID // if there is a screen still in the manager, update TouchPanel // to respond to gestures that screen is interested in. if (_screens.Count > 0) { TouchPanel.EnabledGestures = _screens[_screens.Count - 1].EnabledGestures; } #endif } /// <summary> /// Expose an array holding all the screens. We return a copy rather /// than the real master list, because screens should only ever be added /// or removed using the AddScreen and RemoveScreen methods. /// </summary> public GameScreen[] GetScreens() { return _screens.ToArray(); } /// <summary> /// Helper draws a translucent white fullscreen sprite, used for fading /// screens in and out, and for whitening the background behind popups. /// </summary> public void FadeBackBufferToWhite(float alpha) { FadeBackBufferToColor(Color.White, alpha); } /// <summary> /// Helper draws a translucent black fullscreen sprite, used for fading /// screens in and out, and for darkening the background behind popups. /// </summary> public void FadeBackBufferToBlack(float alpha) { FadeBackBufferToColor(Color.Black, alpha); } private void FadeBackBufferToColor(Color color, float alpha) { _spriteBatch.Begin(); #if SILVERLIGHT Color colorAlpha = new Color(color, alpha); #else Color colorAlpha = color * alpha; #endif //int Max = Math.Max(Graphics.PreferredBackBufferWidth, Graphics.PreferredBackBufferHeight); _spriteBatch.Draw(_blankTexture, new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height), colorAlpha); _spriteBatch.End(); } /// <summary> /// Informs the screen manager to serialize its state to disk. /// </summary> #if WINDOWS8 public async void Deactivate() #else public void Deactivate() #endif { #if !WINDOWS_PHONE && !WINDOWS8 && !ANDROID return; #else #if WINDOWS_PHONE || ANDROID // Open up isolated storage using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { #endif // Create an XML document to hold the list of screen types currently in the stack XDocument doc = new XDocument(); XElement root = new XElement("ScreenManager"); doc.Add(root); // Make a copy of the master screen list, to avoid confusion if // the process of deactivating one screen adds or removes others. _tempScreensList.Clear(); foreach (GameScreen screen in _screens) _tempScreensList.Add(screen); // Iterate the screens to store in our XML file and deactivate them foreach (GameScreen screen in _tempScreensList) { // Only add the screen to our XML if it is serializable if (screen.IsSerializable) { // We store the screen's controlling player so we can rehydrate that value root.Add(new XElement( "GameScreen", new XAttribute("Type", screen.GetType().AssemblyQualifiedName))); } // Deactivate the screen regardless of whether we serialized it screen.Deactivate(); } // Save the document #if WINDOWS8 StorageFolder folder = ApplicationData.Current.LocalFolder; using (Stream stream = await folder.OpenStreamForWriteAsync(StateFilename, CreationCollisionOption.ReplaceExisting)) { #else using (IsolatedStorageFileStream stream = storage.CreateFile(StateFilename)) { #endif doc.Save(stream); #if WINDOWS8 await stream.FlushAsync(); #endif } #if WINDOWS_PHONE || ANDROID } #endif #endif // !WINDOWS_PHONE && !WINDOWS8 && !ANDROID } #if WINDOWS8 public async Task<bool> Activate(bool instancePreserved) #else public bool Activate(bool instancePreserved) #endif { #if !WINDOWS_PHONE && !WINDOWS && !ANDROID return false; #else // If the game instance was preserved, the game wasn't dehydrated so our screens still exist. // We just need to activate them and we're ready to go. if (instancePreserved) { // Make a copy of the master screen list, to avoid confusion if // the process of activating one screen adds or removes others. _tempScreensList.Clear(); foreach (GameScreen screen in _screens) _tempScreensList.Add(screen); foreach (GameScreen screen in _tempScreensList) { screen.Activate(true); } } // Otherwise we need to refer to our saved file and reconstruct the screens that were present // when the game was deactivated. else { // Try to get the screen factory from the services, which is required to recreate the screens var screenFactory = Game.Services.GetService(typeof(IScreenFactory)) as IScreenFactory; if (screenFactory == null) { throw new InvalidOperationException( "Game.Services must contain an IScreenFactory in order to activate the ScreenManager."); } #if WINDOWS8 StorageFolder folder = ApplicationData.Current.LocalFolder; try { using (Stream file = await folder.OpenStreamForReadAsync(StateFilename)) { #else // Open up isolated storage using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { // Check for the file; if it doesn't exist we can't restore state if (!storage.FileExists(StateFilename)) return false; // Read the state file so we can build up our screens using (IsolatedStorageFileStream file = storage.OpenFile(StateFilename, FileMode.Open)) { #endif XDocument doc = XDocument.Load(file); // Iterate the document to recreate the screen stack foreach (XElement screenElem in doc.Root.Elements("GameScreen")) { // Use the factory to create the screen Type screenType = Type.GetType(screenElem.Attribute("Type").Value); GameScreen screen = screenFactory.CreateScreen(screenType); if (screen != null) { // Add the screen to the screens list and activate the screen screen.ScreenManager = this; _screens.Add(screen); if (screen.content == null) screen.content = new ContentManager(Game.Services, Game.Content.RootDirectory); screen.Activate(false); // update the TouchPanel to respond to gestures this screen is interested in TouchPanel.EnabledGestures = screen.EnabledGestures; } } } } #if WINDOWS8 catch (FileNotFoundException) { return false; } #endif } return true; #endif } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Globalization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.WebHooks.Metadata; using Microsoft.AspNetCore.WebHooks.Properties; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.WebHooks.Filters { /// <summary> /// <para> /// An <see cref="IResourceFilter"/> to verify required HTTP headers, <see cref="RouteValueDictionary"/> entries /// and query parameters are present in a WebHook request. Uses <see cref="IWebHookBindingMetadata"/> services to /// determine the requirements for the requested WebHook receiver. /// </para> /// <para> /// Short-circuits the request if required values are missing. The response in that case will have a 400 /// "Bad Request" status code. /// </para> /// </summary> /// <remarks> /// The <see cref="Routing.WebHookEventNameMapperConstraint"/> and <see cref="WebHookVerifyCodeFilter"/> also /// verify required HTTP headers, <see cref="RouteValueDictionary"/> entries and query parameters. But, those /// constraints and filters do not use <see cref="IWebHookBindingMetadata"/> information. /// </remarks> public class WebHookVerifyRequiredValueFilter : IResourceFilter, IOrderedFilter { private readonly IWebHookBindingMetadata _bindingMetadata; private readonly ILogger _logger; private readonly WebHookMetadataProvider _metadataProvider; /// <summary> /// Instantiates a new <see cref="WebHookVerifyRequiredValueFilter"/> instance to verify the given /// <paramref name="bindingMetadata"/>. /// </summary> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> /// <param name="bindingMetadata">The receiver's <see cref="IWebHookBindingMetadata"/>.</param> public WebHookVerifyRequiredValueFilter( ILoggerFactory loggerFactory, IWebHookBindingMetadata bindingMetadata) { if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } if (bindingMetadata == null) { throw new ArgumentNullException(nameof(bindingMetadata)); } _bindingMetadata = bindingMetadata; _logger = loggerFactory.CreateLogger<WebHookVerifyRequiredValueFilter>(); } /// <summary> /// Instantiates a new <see cref="WebHookVerifyRequiredValueFilter"/> instance to verify the receiver's /// <see cref="IWebHookBindingMetadata"/>. That metadata is found in <paramref name="metadataProvider"/>. /// </summary> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> /// <param name="metadataProvider"> /// The <see cref="WebHookMetadataProvider"/> service. Searched for applicable metadata per-request. /// </param> /// <remarks>This overload is intended for use with <see cref="GeneralWebHookAttribute"/>.</remarks> public WebHookVerifyRequiredValueFilter( ILoggerFactory loggerFactory, WebHookMetadataProvider metadataProvider) { if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } if (metadataProvider == null) { throw new ArgumentNullException(nameof(metadataProvider)); } _logger = loggerFactory.CreateLogger<WebHookVerifyRequiredValueFilter>(); _metadataProvider = metadataProvider; } /// <summary> /// Gets the <see cref="IOrderedFilter.Order"/> recommended for all /// <see cref="WebHookVerifyRequiredValueFilter"/> instances. The recommended filter sequence is /// <list type="number"> /// <item> /// Confirm WebHooks configuration is set up correctly (in <see cref="WebHookReceiverExistsFilter"/>). /// </item> /// <item> /// Confirm signature or <c>code</c> query parameter e.g. in <see cref="WebHookVerifyCodeFilter"/> or other /// <see cref="WebHookSecurityFilter"/> subclass. /// </item> /// <item> /// Confirm required headers, <see cref="RouteValueDictionary"/> entries and query parameters are provided (in /// this filter). /// </item> /// <item> /// Short-circuit GET or HEAD requests, if receiver supports either (in /// <see cref="WebHookGetHeadRequestFilter"/>). /// </item> /// <item>Confirm it's a POST request (in <see cref="WebHookVerifyMethodFilter"/>).</item> /// <item>Confirm body type (in <see cref="WebHookVerifyBodyTypeFilter"/>).</item> /// <item> /// Map event name(s), if not done in <see cref="Routing.WebHookEventNameMapperConstraint"/> for this receiver /// (in <see cref="WebHookEventNameMapperFilter"/>). /// </item> /// <item> /// Short-circuit ping requests, if not done in <see cref="WebHookGetHeadRequestFilter"/> for this receiver (in /// <see cref="WebHookPingRequestFilter"/>). /// </item> /// </list> /// </summary> public static int Order => WebHookSecurityFilter.Order + 10; /// <inheritdoc /> int IOrderedFilter.Order => Order; /// <inheritdoc /> public void OnResourceExecuting(ResourceExecutingContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var routeData = context.RouteData; var bindingMetadata = _bindingMetadata; if (bindingMetadata == null) { if (!routeData.TryGetWebHookReceiverName(out var requestReceiverName)) { return; } bindingMetadata = _metadataProvider.GetBindingMetadata(requestReceiverName); if (bindingMetadata == null) { return; } } var receiverName = bindingMetadata.ReceiverName; var request = context.HttpContext.Request; for (var i = 0; i < bindingMetadata.Parameters.Count; i++) { var parameter = bindingMetadata.Parameters[i]; if (parameter.IsRequired) { bool found; string message; var sourceName = parameter.SourceName; switch (parameter.ParameterType) { case WebHookParameterType.Header: found = VerifyHeader(request.Headers, sourceName, receiverName, out message); break; case WebHookParameterType.RouteValue: found = VerifyRouteData(routeData, sourceName, receiverName, out message); break; case WebHookParameterType.QueryParameter: found = VerifyQueryParameter(request.Query, sourceName, receiverName, out message); break; default: message = string.Format( CultureInfo.CurrentCulture, Resources.General_InvalidEnumValue, typeof(WebHookParameterType), parameter.ParameterType); throw new InvalidOperationException(message); } if (!found) { // Do not return after first error. Instead log about all issues. context.Result = new BadRequestObjectResult(message); } } } } /// <inheritdoc /> public void OnResourceExecuted(ResourceExecutedContext context) { // No-op } private bool VerifyRouteData(RouteData routeData, string keyName, string receiverName, out string message) { if (routeData.Values.TryGetValue(keyName, out var value) && !string.IsNullOrEmpty(value as string)) { message = null; return true; } _logger.LogWarning( 0, "A '{ReceiverName}' WebHook request must contain a '{KeyName}' value in the route data.", receiverName, keyName); message = string.Format( CultureInfo.CurrentCulture, Resources.VerifyRequiredValue_NoRouteValue, receiverName, keyName); return false; } private bool VerifyHeader( IHeaderDictionary headers, string headerName, string receiverName, out string message) { if (headers.TryGetValue(headerName, out var values) && !StringValues.IsNullOrEmpty(values)) { message = null; return true; } _logger.LogWarning( 1, "A '{ReceiverName}' WebHook request must contain a '{HeaderName}' HTTP header.", receiverName, headerName); message = string.Format( CultureInfo.CurrentCulture, Resources.VerifyRequiredValue_NoHeader, receiverName, headerName); return false; } private bool VerifyQueryParameter( IQueryCollection query, string parameterName, string receiverName, out string message) { if (query.TryGetValue(parameterName, out var values) && !StringValues.IsNullOrEmpty(values)) { message = null; return true; } _logger.LogWarning( 2, "A '{ReceiverName}' WebHook request must contain a '{QueryParameterName}' query parameter.", receiverName, parameterName); message = string.Format( CultureInfo.CurrentCulture, Resources.General_NoQueryParameter, receiverName, parameterName); return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Xml; using System.Xml.Schema; using System.Reflection; using System.Reflection.Emit; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Security; using System.Runtime.CompilerServices; namespace System.Runtime.Serialization { #if USE_REFEMIT public delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract); public delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract); public sealed class XmlFormatWriterGenerator #else internal delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract); internal delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract); internal sealed class XmlFormatWriterGenerator #endif { private CriticalHelper _helper; public XmlFormatWriterGenerator() { _helper = new CriticalHelper(); } internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { return _helper.GenerateClassWriter(classContract); } internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { return _helper.GenerateCollectionWriter(collectionContract); } /// <SecurityNote> /// Review - handles all aspects of IL generation including initializing the DynamicMethod. /// changes to how IL generated could affect how data is serialized and what gets access to data, /// therefore we mark it for review so that changes to generation logic are reviewed. /// </SecurityNote> private class CriticalHelper { #if !USE_REFEMIT private CodeGenerator _ilg; private ArgBuilder _xmlWriterArg; private ArgBuilder _contextArg; private ArgBuilder _dataContractArg; private LocalBuilder _objectLocal; // Used for classes private LocalBuilder _contractNamespacesLocal; private LocalBuilder _memberNamesLocal; private LocalBuilder _childElementNamespacesLocal; private int _typeIndex = 1; private int _childElementIndex = 0; #endif private XmlFormatClassWriterDelegate CreateReflectionXmlFormatClassWriterDelegate() { return new ReflectionXmlFormatWriter().ReflectionWriteClass; } internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract) { if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { return CreateReflectionXmlFormatClassWriterDelegate(); } else { #if USE_REFEMIT throw new InvalidOperationException("Cannot generate class writer"); #else _ilg = new CodeGenerator(); bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null); try { _ilg.BeginMethod("Write" + classContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatClassWriterDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { classContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } InitArgs(classContract.UnderlyingType); WriteClass(classContract); return (XmlFormatClassWriterDelegate)_ilg.EndMethod(); #endif } } private XmlFormatCollectionWriterDelegate CreateReflectionXmlFormatCollectionWriterDelegate() { return new ReflectionXmlFormatWriter().ReflectionWriteCollection; } internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract) { if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { return CreateReflectionXmlFormatCollectionWriterDelegate(); } else { #if USE_REFEMIT throw new InvalidOperationException("Cannot generate class writer"); #else _ilg = new CodeGenerator(); bool memberAccessFlag = collectionContract.RequiresMemberAccessForWrite(null); try { _ilg.BeginMethod("Write" + collectionContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatCollectionWriterDelegate, memberAccessFlag); } catch (SecurityException securityException) { if (memberAccessFlag) { collectionContract.RequiresMemberAccessForWrite(securityException); } else { throw; } } InitArgs(collectionContract.UnderlyingType); WriteCollection(collectionContract); return (XmlFormatCollectionWriterDelegate)_ilg.EndMethod(); #endif } } #if !USE_REFEMIT private void InitArgs(Type objType) { _xmlWriterArg = _ilg.GetArg(0); _contextArg = _ilg.GetArg(2); _dataContractArg = _ilg.GetArg(3); _objectLocal = _ilg.DeclareLocal(objType, "objSerialized"); ArgBuilder objectArg = _ilg.GetArg(1); _ilg.Load(objectArg); // Copy the data from the DataTimeOffset object passed in to the DateTimeOffsetAdapter. // DateTimeOffsetAdapter is used here for serialization purposes to bypass the ISerializable implementation // on DateTimeOffset; which does not work in partial trust. if (objType == Globals.TypeOfDateTimeOffsetAdapter) { _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfDateTimeOffset); _ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetAdapterMethod); } //Copy the KeyValuePair<K,T> to a KeyValuePairAdapter<K,T>. else if (objType.IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter) { ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType); _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments)); _ilg.New(dc.KeyValuePairAdapterConstructorInfo); } else { _ilg.ConvertValue(objectArg.ArgType, objType); } _ilg.Stloc(_objectLocal); } private void InvokeOnSerializing(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnSerializing(classContract.BaseContract); if (classContract.OnSerializing != null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnSerializing); } } private void InvokeOnSerialized(ClassDataContract classContract) { if (classContract.BaseContract != null) InvokeOnSerialized(classContract.BaseContract); if (classContract.OnSerialized != null) { _ilg.LoadAddress(_objectLocal); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnSerialized); } } private void WriteClass(ClassDataContract classContract) { InvokeOnSerializing(classContract); if (classContract.IsISerializable) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteISerializableMethod, _xmlWriterArg, _objectLocal); } else { if (classContract.ContractNamespaces.Length > 1) { _contractNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "contractNamespaces"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ContractNamespacesField); _ilg.Store(_contractNamespacesLocal); } _memberNamesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "memberNames"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.MemberNamesField); _ilg.Store(_memberNamesLocal); for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++) { if (classContract.ChildElementNamespaces[i] != null) { _childElementNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "childElementNamespaces"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespacesProperty); _ilg.Store(_childElementNamespacesLocal); } } if (classContract.HasExtensionData) { LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData"); _ilg.Load(_objectLocal); _ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfIExtensibleDataObject); _ilg.LoadMember(XmlFormatGeneratorStatics.ExtensionDataProperty); _ilg.Store(extensionDataLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteExtensionDataMethod, _xmlWriterArg, extensionDataLocal, -1); WriteMembers(classContract, extensionDataLocal, classContract); } else { WriteMembers(classContract, null, classContract); } } InvokeOnSerialized(classContract); } private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract) { int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract); LocalBuilder namespaceLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString), "ns"); if (_contractNamespacesLocal == null) { _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); } else { _ilg.LoadArrayElement(_contractNamespacesLocal, _typeIndex - 1); } _ilg.Store(namespaceLocal); int classMemberCount = classContract.Members.Count; _ilg.Call(thisObj: _contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classMemberCount); for (int i = 0; i < classMemberCount; i++, memberCount++) { DataMember member = classContract.Members[i]; Type memberType = member.MemberType; LocalBuilder memberValue = null; _ilg.Load(_contextArg); _ilg.Call(methodInfo: member.IsGetOnlyCollection ? XmlFormatGeneratorStatics.StoreIsGetOnlyCollectionMethod : XmlFormatGeneratorStatics.ResetIsGetOnlyCollectionMethod); if (!member.EmitDefaultValue) { memberValue = LoadMemberValue(member); _ilg.IfNotDefaultValue(memberValue); } bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract); if (writeXsiType || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, arrayItemIndex: null, ns: namespaceLocal, name: null, nameIndex: i + _childElementIndex)) { WriteStartElement(memberType, classContract.Namespace, namespaceLocal, nameLocal: null, nameIndex: i + _childElementIndex); if (classContract.ChildElementNamespaces[i + _childElementIndex] != null) { _ilg.Load(_xmlWriterArg); _ilg.LoadArrayElement(_childElementNamespacesLocal, i + _childElementIndex); _ilg.Call(methodInfo: XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } if (memberValue == null) memberValue = LoadMemberValue(member); WriteValue(memberValue, writeXsiType); WriteEndElement(); } if (classContract.HasExtensionData) { _ilg.Call(thisObj: _contextArg, XmlFormatGeneratorStatics.WriteExtensionDataMethod, _xmlWriterArg, extensionDataLocal, memberCount); } if (!member.EmitDefaultValue) { if (member.IsRequired) { _ilg.Else(); _ilg.Call(thisObj: null, XmlFormatGeneratorStatics.ThrowRequiredMemberMustBeEmittedMethod, member.Name, classContract.UnderlyingType); } _ilg.EndIf(); } } _typeIndex++; _childElementIndex += classMemberCount; return memberCount; } private LocalBuilder LoadMemberValue(DataMember member) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(member.MemberInfo); LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType, member.Name + "Value"); _ilg.Stloc(memberValue); return memberValue; } private void WriteCollection(CollectionDataContract collectionContract) { LocalBuilder itemNamespace = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemNamespace"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); _ilg.Store(itemNamespace); LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName"); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.CollectionItemNameProperty); _ilg.Store(itemName); if (collectionContract.ChildElementNamespace != null) { _ilg.Load(_xmlWriterArg); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespaceProperty); _ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } if (collectionContract.Kind == CollectionKind.Array) { Type itemType = collectionContract.ItemType; LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementArrayCountMethod, _xmlWriterArg, _objectLocal); if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, _objectLocal, itemName, itemNamespace)) { _ilg.For(i, 0, _objectLocal); if (!TryWritePrimitive(itemType, null /*value*/, null /*memberInfo*/, i /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/)) { WriteStartElement(itemType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/); _ilg.LoadArrayElement(_objectLocal, i); LocalBuilder memberValue = _ilg.DeclareLocal(itemType, "memberValue"); _ilg.Stloc(memberValue); WriteValue(memberValue, false /*writeXsiType*/); WriteEndElement(); } _ilg.EndFor(); } } else { MethodInfo incrementCollectionCountMethod = null; switch (collectionContract.Kind) { case CollectionKind.Collection: case CollectionKind.List: case CollectionKind.Dictionary: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod; break; case CollectionKind.GenericCollection: case CollectionKind.GenericList: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType); break; case CollectionKind.GenericDictionary: incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments())); break; } if (incrementCollectionCountMethod != null) { _ilg.Call(_contextArg, incrementCollectionCountMethod, _xmlWriterArg, _objectLocal); } bool isDictionary = false, isGenericDictionary = false; Type enumeratorType = null; Type[] keyValueTypes = null; if (collectionContract.Kind == CollectionKind.GenericDictionary) { isGenericDictionary = true; keyValueTypes = collectionContract.ItemType.GetGenericArguments(); enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes); } else if (collectionContract.Kind == CollectionKind.Dictionary) { isDictionary = true; keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject }; enumeratorType = Globals.TypeOfDictionaryEnumerator; } else { enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType; } MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); if (moveNextMethod == null || getCurrentMethod == null) { if (enumeratorType.IsInterface) { if (moveNextMethod == null) moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod; if (getCurrentMethod == null) getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod; } else { Type ienumeratorInterface = Globals.TypeOfIEnumerator; CollectionKind kind = collectionContract.Kind; if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable) { Type[] interfaceTypes = enumeratorType.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric && interfaceType.GetGenericArguments()[0] == collectionContract.ItemType) { ienumeratorInterface = interfaceType; break; } } } if (moveNextMethod == null) moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface); if (getCurrentMethod == null) getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface); } } Type elementType = getCurrentMethod.ReturnType; LocalBuilder currentValue = _ilg.DeclareLocal(elementType, "currentValue"); LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType, "enumerator"); _ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod); if (isDictionary) { _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, Globals.TypeOfIDictionaryEnumerator); _ilg.New(XmlFormatGeneratorStatics.DictionaryEnumeratorCtor); } else if (isGenericDictionary) { Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes)); ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam }); _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam); _ilg.New(dictEnumCtor); } _ilg.Stloc(enumerator); _ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod); if (incrementCollectionCountMethod == null) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); } if (!TryWritePrimitive(elementType, currentValue, null /*memberInfo*/, null /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/)) { WriteStartElement(elementType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/); if (isGenericDictionary || isDictionary) { _ilg.Call(_dataContractArg, XmlFormatGeneratorStatics.GetItemContractMethod); _ilg.Load(_xmlWriterArg); _ilg.Load(currentValue); _ilg.ConvertValue(currentValue.LocalType, Globals.TypeOfObject); _ilg.Load(_contextArg); _ilg.Call(XmlFormatGeneratorStatics.WriteXmlValueMethod); } else { WriteValue(currentValue, false /*writeXsiType*/); } WriteEndElement(); } _ilg.EndForEach(moveNextMethod); } } private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder ns, LocalBuilder name, int nameIndex) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; // load xmlwriter if (type.IsValueType) { _ilg.Load(_xmlWriterArg); } else { _ilg.Load(_contextArg); _ilg.Load(_xmlWriterArg); } // load primitive value if (value != null) { _ilg.Load(value); } else if (memberInfo != null) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(memberInfo); } else { _ilg.LoadArrayElement(_objectLocal, arrayItemIndex); } // load name if (name != null) { _ilg.Load(name); } else { _ilg.LoadArrayElement(_memberNamesLocal, nameIndex); } // load namespace _ilg.Load(ns); // call method to write primitive _ilg.Call(primitiveContract.XmlFormatWriterMethod); return true; } private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName, LocalBuilder itemNamespace) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; string writeArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: writeArrayMethod = "WriteBooleanArray"; break; case TypeCode.DateTime: writeArrayMethod = "WriteDateTimeArray"; break; case TypeCode.Decimal: writeArrayMethod = "WriteDecimalArray"; break; case TypeCode.Int32: writeArrayMethod = "WriteInt32Array"; break; case TypeCode.Int64: writeArrayMethod = "WriteInt64Array"; break; case TypeCode.Single: writeArrayMethod = "WriteSingleArray"; break; case TypeCode.Double: writeArrayMethod = "WriteDoubleArray"; break; default: break; } if (writeArrayMethod != null) { _ilg.Load(_xmlWriterArg); _ilg.Load(value); _ilg.Load(itemName); _ilg.Load(itemNamespace); _ilg.Call(typeof(XmlWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })); return true; } return false; } private void WriteValue(LocalBuilder memberValue, bool writeXsiType) { Type memberType = memberValue.LocalType; bool isNullableOfT = (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable); if (memberType.IsValueType && !isNullableOfT) { PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && !writeXsiType) _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); else InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, memberValue, memberType, writeXsiType); } else { if (isNullableOfT) { memberValue = UnwrapNullableObject(memberValue);//Leaves !HasValue on stack memberType = memberValue.LocalType; } else { _ilg.Load(memberValue); _ilg.Load(null); _ilg.Ceq(); } _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) { if (isNullableOfT) { _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); } else { _ilg.Call(_contextArg, primitiveContract.XmlFormatContentWriterMethod, _xmlWriterArg, memberValue); } } else { if (memberType == Globals.TypeOfObject ||//boxed Nullable<T> memberType == Globals.TypeOfValueType || ((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType)) { _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); memberValue = _ilg.DeclareLocal(Globals.TypeOfObject, "unwrappedMemberValue"); memberType = memberValue.LocalType; _ilg.Stloc(memberValue); _ilg.If(memberValue, Cmp.EqualTo, null); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); } InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod), memberValue, memberType, writeXsiType); if (memberType == Globals.TypeOfObject) //boxed Nullable<T> _ilg.EndIf(); } _ilg.EndIf(); } } private void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, Type memberType, bool writeXsiType) { _ilg.Load(_contextArg); _ilg.Load(_xmlWriterArg); _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); //In SL GetTypeHandle throws MethodAccessException as its internal and extern. //So as a workaround, call XmlObjectSerializerWriteContext.IsMemberTypeSameAsMemberValue that //does the actual comparison and returns the bool value we care. _ilg.Call(null, XmlFormatGeneratorStatics.IsMemberTypeSameAsMemberValue, memberValue, memberType); _ilg.Load(writeXsiType); _ilg.Load(DataContract.GetId(memberType.TypeHandle)); _ilg.Ldtoken(memberType); _ilg.Call(methodInfo); } private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !HasValue on stack { Type memberType = memberValue.LocalType; Label onNull = _ilg.DefineLabel(); Label end = _ilg.DefineLabel(); _ilg.Load(memberValue); while (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable) { Type innerType = memberType.GetGenericArguments()[0]; _ilg.Dup(); _ilg.Call(XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod(innerType)); _ilg.Brfalse(onNull); _ilg.Call(XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod(innerType)); memberType = innerType; } memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue"); _ilg.Stloc(memberValue); _ilg.Load(false); //isNull _ilg.Br(end); _ilg.MarkLabel(onNull); _ilg.Pop(); _ilg.Call(XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod(memberType)); _ilg.Stloc(memberValue); _ilg.Load(true);//isNull _ilg.MarkLabel(end); return memberValue; } private bool NeedsPrefix(Type type, XmlDictionaryString ns) { return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0); } private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder nameLocal, int nameIndex) { bool needsPrefix = NeedsPrefix(type, ns); _ilg.Load(_xmlWriterArg); // prefix if (needsPrefix) _ilg.Load(Globals.ElementPrefix); // localName if (nameLocal == null) _ilg.LoadArrayElement(_memberNamesLocal, nameIndex); else _ilg.Load(nameLocal); // namespace _ilg.Load(namespaceLocal); _ilg.Call(needsPrefix ? XmlFormatGeneratorStatics.WriteStartElementMethod3 : XmlFormatGeneratorStatics.WriteStartElementMethod2); } private void WriteEndElement() { _ilg.Call(_xmlWriterArg, XmlFormatGeneratorStatics.WriteEndElementMethod); } private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract) { // Check for conflict with base type members if (CheckIfConflictingMembersHaveDifferentTypes(member)) return true; // Check for conflict with derived type members string name = member.Name; string ns = classContract.StableName.Namespace; ClassDataContract currentContract = derivedMostClassContract; while (currentContract != null && currentContract != classContract) { if (ns == currentContract.StableName.Namespace) { List<DataMember> members = currentContract.Members; for (int j = 0; j < members.Count; j++) { if (name == members[j].Name) return CheckIfConflictingMembersHaveDifferentTypes(members[j]); } } currentContract = currentContract.BaseContract; } return false; } private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) { while (member.ConflictingMember != null) { if (member.MemberType != member.ConflictingMember.MemberType) return true; member = member.ConflictingMember; } return false; } #endif } } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using LightBlue.Standalone; using Microsoft.WindowsAzure.Storage.Blob; using Xunit; using Xunit.Extensions; namespace LightBlue.Tests.Standalone { public class ListMetadataTests : StandaloneAzureTestsBase { public ListMetadataTests() : base(DirectoryType.Container) { var flatBlob = new StandaloneAzureBlockBlob(BasePath, "flat"); flatBlob.UploadFromByteArrayAsync(Encoding.UTF8.GetBytes("flat")); flatBlob.Metadata["thing"] = "flat"; flatBlob.SetMetadata(); var withPath = new StandaloneAzureBlockBlob(BasePath, @"random\path\blob"); withPath.UploadFromByteArrayAsync(Encoding.UTF8.GetBytes("withPath")); withPath.Metadata["thing"] = "withPath"; withPath.SetMetadata(); } public static IEnumerable<object[]> DetailsWithoutMetadata { get { yield return new object[] {BlobListingDetails.None}; yield return new object[] {BlobListingDetails.Snapshots}; yield return new object[] {BlobListingDetails.UncommittedBlobs}; yield return new object[] {BlobListingDetails.Copy}; yield return new object[] {BlobListingDetails.Snapshots | BlobListingDetails.UncommittedBlobs}; yield return new object[] {BlobListingDetails.Snapshots | BlobListingDetails.Copy}; yield return new object[] {BlobListingDetails.UncommittedBlobs | BlobListingDetails.Copy}; yield return new object[] {BlobListingDetails.UncommittedBlobs | BlobListingDetails.Copy | BlobListingDetails.Snapshots}; } } public static IEnumerable<object[]> DetailsWithoutMetadataNoSnapshots { get { yield return new object[] {BlobListingDetails.None}; yield return new object[] {BlobListingDetails.UncommittedBlobs}; yield return new object[] {BlobListingDetails.Copy}; yield return new object[] {BlobListingDetails.UncommittedBlobs | BlobListingDetails.Copy}; } } public static IEnumerable<object[]> DetailsWithMetadata { get { yield return new object[] {BlobListingDetails.Metadata}; yield return new object[] {BlobListingDetails.Metadata | BlobListingDetails.Snapshots}; yield return new object[] {BlobListingDetails.Metadata | BlobListingDetails.Copy}; yield return new object[] {BlobListingDetails.Metadata | BlobListingDetails.UncommittedBlobs}; yield return new object[] {BlobListingDetails.All}; } } public static IEnumerable<object[]> DetailsWithMetadataNoSnapshots { get { yield return new object[] {BlobListingDetails.Metadata}; yield return new object[] {BlobListingDetails.Metadata | BlobListingDetails.Copy}; yield return new object[] {BlobListingDetails.Metadata | BlobListingDetails.UncommittedBlobs}; yield return new object[] {BlobListingDetails.Metadata | BlobListingDetails.UncommittedBlobs | BlobListingDetails.Copy}; } } [Theory] [PropertyData("DetailsWithoutMetadata")] public async Task ContainerWillNotLoadMetadataIfNotSpecifiedForFlatListing(BlobListingDetails blobListingDetails) { var results = await new StandaloneAzureBlobContainer(BasePath) .ListBlobsSegmentedAsync( "", BlobListing.Flat, blobListingDetails, null, null); Assert.Empty(results.Results.OfType<IAzureBlockBlob>().First(r => r.Name == "flat").Metadata); } [Theory] [PropertyData("DetailsWithMetadata")] public async Task ContainerWillLoadMetadataIfSpecifiedForFlatListing(BlobListingDetails blobListingDetails) { var results = await new StandaloneAzureBlobContainer(BasePath) .ListBlobsSegmentedAsync( "", BlobListing.Flat, blobListingDetails, null, null); var blob = results.Results.OfType<IAzureBlockBlob>().First(r => r.Name == "flat"); Assert.Equal("flat", blob.Metadata["thing"]); } [Theory] [PropertyData("DetailsWithoutMetadataNoSnapshots")] public async Task ContainerWillNotLoadMetadataIfNotSpecifiedForHierarchicalListing(BlobListingDetails blobListingDetails) { var results = await new StandaloneAzureBlobContainer(BasePath) .ListBlobsSegmentedAsync( "", BlobListing.Hierarchical, blobListingDetails, null, null); Assert.Empty(results.Results.OfType<IAzureBlockBlob>().First(r => r.Name == "flat").Metadata); } [Theory] [PropertyData("DetailsWithMetadataNoSnapshots")] public async Task ContainerWillLoadMetadataIfSpecifiedForHierarchicalListing(BlobListingDetails blobListingDetails) { var results = await new StandaloneAzureBlobContainer(BasePath) .ListBlobsSegmentedAsync( "", BlobListing.Hierarchical, blobListingDetails, null, null); var blob = results.Results.OfType<IAzureBlockBlob>().First(r => r.Name == "flat"); Assert.Equal("flat", blob.Metadata["thing"]); } [Theory] [PropertyData("DetailsWithoutMetadata")] public async Task DirectoryWillNotLoadMetadataIfNotSpecifiedForFlatListing(BlobListingDetails blobListingDetails) { var results = await new StandaloneAzureBlobDirectory(BasePath, Path.Combine(BasePath, @"random\path")) .ListBlobsSegmentedAsync( BlobListing.Flat, blobListingDetails, null, null); Assert.Empty(results.Results.OfType<IAzureBlockBlob>().First(r => r.Name == @"random\path\blob").Metadata); } [Theory] [PropertyData("DetailsWithMetadata")] public async Task DirectoryWillLoadMetadataIfSpecifiedForFlatListing(BlobListingDetails blobListingDetails) { var results = await new StandaloneAzureBlobDirectory(BasePath, Path.Combine(BasePath, @"random\path")) .ListBlobsSegmentedAsync( BlobListing.Flat, blobListingDetails, null, null); var blob = results.Results.OfType<IAzureBlockBlob>().First(r => r.Name == @"random\path\blob"); Assert.Equal("withPath", blob.Metadata["thing"]); } [Theory] [PropertyData("DetailsWithoutMetadataNoSnapshots")] public async Task DirectoryWillNotLoadMetadataIfNotSpecifiedForHierarchicalListing(BlobListingDetails blobListingDetails) { var results = await new StandaloneAzureBlobDirectory(BasePath, Path.Combine(BasePath, @"random\path")) .ListBlobsSegmentedAsync( BlobListing.Hierarchical, blobListingDetails, null, null); Assert.Empty(results.Results.OfType<IAzureBlockBlob>().First(r => r.Name == @"random\path\blob").Metadata); } [Theory] [PropertyData("DetailsWithMetadataNoSnapshots")] public async Task DirectoryWillLoadMetadataIfSpecifiedForHierarchicalListing(BlobListingDetails blobListingDetails) { var results = await new StandaloneAzureBlobDirectory(BasePath, Path.Combine(BasePath, @"random\path")) .ListBlobsSegmentedAsync( BlobListing.Hierarchical, blobListingDetails, null, null); var blob = results.Results.OfType<IAzureBlockBlob>().First(r => r.Name == @"random\path\blob"); Assert.Equal("withPath", blob.Metadata["thing"]); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using osu.Framework.Configuration; using osu.Framework.Configuration.Tracking; using osu.Framework.Extensions; using osu.Framework.Platform; using osu.Framework.Testing; using osu.Game.Input; using osu.Game.Input.Bindings; using osu.Game.Overlays; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Select; using osu.Game.Screens.Select.Filter; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class OsuConfigManager : IniConfigManager<OsuSetting> { protected override void InitialiseDefaults() { // UI/selection defaults SetDefault(OsuSetting.Ruleset, 0, 0, int.MaxValue); SetDefault(OsuSetting.Skin, 0, -1, int.MaxValue); SetDefault(OsuSetting.BeatmapDetailTab, PlayBeatmapDetailArea.TabType.Details); SetDefault(OsuSetting.BeatmapDetailModsFilter, false); SetDefault(OsuSetting.ShowConvertedBeatmaps, true); SetDefault(OsuSetting.DisplayStarsMinimum, 0.0, 0, 10, 0.1); SetDefault(OsuSetting.DisplayStarsMaximum, 10.1, 0, 10.1, 0.1); SetDefault(OsuSetting.SongSelectGroupingMode, GroupMode.All); SetDefault(OsuSetting.SongSelectSortingMode, SortMode.Title); SetDefault(OsuSetting.RandomSelectAlgorithm, RandomSelectAlgorithm.RandomPermutation); SetDefault(OsuSetting.ChatDisplayHeight, ChatOverlay.DEFAULT_HEIGHT, 0.2f, 1f); // Online settings SetDefault(OsuSetting.Username, string.Empty); SetDefault(OsuSetting.Token, string.Empty); SetDefault(OsuSetting.AutomaticallyDownloadWhenSpectating, false); SetDefault(OsuSetting.SavePassword, false).ValueChanged += enabled => { if (enabled.NewValue) SetValue(OsuSetting.SaveUsername, true); }; SetDefault(OsuSetting.SaveUsername, true).ValueChanged += enabled => { if (!enabled.NewValue) SetValue(OsuSetting.SavePassword, false); }; SetDefault(OsuSetting.ExternalLinkWarning, true); SetDefault(OsuSetting.PreferNoVideo, false); SetDefault(OsuSetting.ShowOnlineExplicitContent, false); SetDefault(OsuSetting.NotifyOnUsernameMentioned, true); SetDefault(OsuSetting.NotifyOnPrivateMessage, true); // Audio SetDefault(OsuSetting.VolumeInactive, 0.25, 0, 1, 0.01); SetDefault(OsuSetting.MenuVoice, true); SetDefault(OsuSetting.MenuMusic, true); SetDefault(OsuSetting.AudioOffset, 0, -500.0, 500.0, 1); // Input SetDefault(OsuSetting.MenuCursorSize, 1.0f, 0.5f, 2f, 0.01f); SetDefault(OsuSetting.GameplayCursorSize, 1.0f, 0.1f, 2f, 0.01f); SetDefault(OsuSetting.AutoCursorSize, false); SetDefault(OsuSetting.MouseDisableButtons, false); SetDefault(OsuSetting.MouseDisableWheel, false); SetDefault(OsuSetting.ConfineMouseMode, OsuConfineMouseMode.DuringGameplay); // Graphics SetDefault(OsuSetting.ShowFpsDisplay, false); SetDefault(OsuSetting.ShowStoryboard, true); SetDefault(OsuSetting.BeatmapSkins, true); SetDefault(OsuSetting.BeatmapColours, true); SetDefault(OsuSetting.BeatmapHitsounds, true); SetDefault(OsuSetting.CursorRotation, true); SetDefault(OsuSetting.MenuParallax, true); // Gameplay SetDefault(OsuSetting.DimLevel, 0.8, 0, 1, 0.01); SetDefault(OsuSetting.BlurLevel, 0, 0, 1, 0.01); SetDefault(OsuSetting.LightenDuringBreaks, true); SetDefault(OsuSetting.HitLighting, true); SetDefault(OsuSetting.HUDVisibilityMode, HUDVisibilityMode.Always); SetDefault(OsuSetting.ShowDifficultyGraph, true); SetDefault(OsuSetting.ShowHealthDisplayWhenCantFail, true); SetDefault(OsuSetting.FadePlayfieldWhenHealthLow, true); SetDefault(OsuSetting.KeyOverlay, false); SetDefault(OsuSetting.PositionalHitSounds, true); SetDefault(OsuSetting.AlwaysPlayFirstComboBreak, true); SetDefault(OsuSetting.FloatingComments, false); SetDefault(OsuSetting.ScoreDisplayMode, ScoringMode.Standardised); SetDefault(OsuSetting.IncreaseFirstObjectVisibility, true); SetDefault(OsuSetting.GameplayDisableWinKey, true); // Update SetDefault(OsuSetting.ReleaseStream, ReleaseStream.Lazer); SetDefault(OsuSetting.Version, string.Empty); SetDefault(OsuSetting.ScreenshotFormat, ScreenshotFormat.Jpg); SetDefault(OsuSetting.ScreenshotCaptureMenuCursor, false); SetDefault(OsuSetting.SongSelectRightMouseScroll, false); SetDefault(OsuSetting.Scaling, ScalingMode.Off); SetDefault(OsuSetting.ScalingSizeX, 0.8f, 0.2f, 1f); SetDefault(OsuSetting.ScalingSizeY, 0.8f, 0.2f, 1f); SetDefault(OsuSetting.ScalingPositionX, 0.5f, 0f, 1f); SetDefault(OsuSetting.ScalingPositionY, 0.5f, 0f, 1f); SetDefault(OsuSetting.UIScale, 1f, 0.8f, 1.6f, 0.01f); SetDefault(OsuSetting.UIHoldActivationDelay, 200f, 0f, 500f, 50f); SetDefault(OsuSetting.IntroSequence, IntroSequence.Triangles); SetDefault(OsuSetting.MenuBackgroundSource, BackgroundSource.Skin); SetDefault(OsuSetting.SeasonalBackgroundMode, SeasonalBackgroundMode.Sometimes); SetDefault(OsuSetting.DiscordRichPresence, DiscordRichPresenceMode.Full); SetDefault(OsuSetting.EditorWaveformOpacity, 0.25f); SetDefault(OsuSetting.EditorHitAnimations, false); } public OsuConfigManager(Storage storage) : base(storage) { Migrate(); } public void Migrate() { // arrives as 2020.123.0 var rawVersion = Get<string>(OsuSetting.Version); if (rawVersion.Length < 6) return; var pieces = rawVersion.Split('.'); // on a fresh install or when coming from a non-release build, execution will end here. // we don't want to run migrations in such cases. if (!int.TryParse(pieces[0], out int year)) return; if (!int.TryParse(pieces[1], out int monthDay)) return; int combined = (year * 10000) + monthDay; if (combined < 20210413) { SetValue(OsuSetting.EditorWaveformOpacity, 0.25f); } } public override TrackedSettings CreateTrackedSettings() { // these need to be assigned in normal game startup scenarios. Debug.Assert(LookupKeyBindings != null); Debug.Assert(LookupSkinName != null); return new TrackedSettings { new TrackedSetting<bool>(OsuSetting.MouseDisableButtons, v => new SettingDescription(!v, "gameplay mouse buttons", v ? "disabled" : "enabled", LookupKeyBindings(GlobalAction.ToggleGameplayMouseButtons))), new TrackedSetting<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode, m => new SettingDescription(m, "HUD Visibility", m.GetDescription(), $"cycle: {LookupKeyBindings(GlobalAction.ToggleInGameInterface)} quick view: {LookupKeyBindings(GlobalAction.HoldForHUD)}")), new TrackedSetting<ScalingMode>(OsuSetting.Scaling, m => new SettingDescription(m, "scaling", m.GetDescription())), new TrackedSetting<int>(OsuSetting.Skin, m => { string skinName = LookupSkinName(m) ?? string.Empty; return new SettingDescription(skinName, "skin", skinName, $"random: {LookupKeyBindings(GlobalAction.RandomSkin)}"); }) }; } public Func<int, string> LookupSkinName { private get; set; } public Func<GlobalAction, string> LookupKeyBindings { get; set; } } public enum OsuSetting { Ruleset, Token, MenuCursorSize, GameplayCursorSize, AutoCursorSize, DimLevel, BlurLevel, LightenDuringBreaks, ShowStoryboard, KeyOverlay, PositionalHitSounds, AlwaysPlayFirstComboBreak, FloatingComments, HUDVisibilityMode, ShowDifficultyGraph, ShowHealthDisplayWhenCantFail, FadePlayfieldWhenHealthLow, MouseDisableButtons, MouseDisableWheel, ConfineMouseMode, AudioOffset, VolumeInactive, MenuMusic, MenuVoice, CursorRotation, MenuParallax, BeatmapDetailTab, BeatmapDetailModsFilter, Username, ReleaseStream, SavePassword, SaveUsername, DisplayStarsMinimum, DisplayStarsMaximum, SongSelectGroupingMode, SongSelectSortingMode, RandomSelectAlgorithm, ShowFpsDisplay, ChatDisplayHeight, Version, ShowConvertedBeatmaps, Skin, ScreenshotFormat, ScreenshotCaptureMenuCursor, SongSelectRightMouseScroll, BeatmapSkins, BeatmapColours, BeatmapHitsounds, IncreaseFirstObjectVisibility, ScoreDisplayMode, ExternalLinkWarning, PreferNoVideo, Scaling, ScalingPositionX, ScalingPositionY, ScalingSizeX, ScalingSizeY, UIScale, IntroSequence, NotifyOnUsernameMentioned, NotifyOnPrivateMessage, UIHoldActivationDelay, HitLighting, MenuBackgroundSource, GameplayDisableWinKey, SeasonalBackgroundMode, EditorWaveformOpacity, EditorHitAnimations, DiscordRichPresence, AutomaticallyDownloadWhenSpectating, ShowOnlineExplicitContent, } }
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using Moq; using NUnit.Framework; using XenAdmin.Alerts; using XenAdmin.Core; using XenAdmin.Network; using XenAdminTests.UnitTests.UnitTestHelper; using XenAPI; namespace XenAdminTests.UnitTests.AlertTests { [TestFixture, Category(TestCategories.Unit)] public class XenServerUpdateAlertTests { private Mock<IXenConnection> connA; private Mock<IXenConnection> connB; private Mock<Host> hostA; private Mock<Host> hostB; protected Cache cacheA; protected Cache cacheB; [Test] public void TestAlertWithConnectionAndHosts() { XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, "http://url", new List<XenServerPatch>(), new DateTime(2011,4,1).ToString(), "123"); var alert = new XenServerVersionAlert(ver); alert.IncludeConnection(connA.Object); alert.IncludeConnection(connB.Object); alert.IncludeHosts(new List<Host>() { hostA.Object, hostB.Object }); IUnitTestVerifier validator = new VerifyGetters(alert); validator.Verify(new AlertClassUnitTestData { AppliesTo = "HostAName, HostBName, ConnAName, ConnBName", FixLinkText = "Go to Web Page", HelpID = "XenServerUpdateAlert", Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.", HelpLinkText = "Help", Title = "name is now available", Priority = "Priority5" }); Assert.IsFalse(alert.CanIgnore); VerifyConnExpectations(Times.Once); VerifyHostsExpectations(Times.Once); } [Test] public void TestAlertWithHostsAndNoConnection() { XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, "http://url", new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123"); var alert = new XenServerVersionAlert(ver); alert.IncludeHosts(new List<Host> { hostA.Object, hostB.Object }); IUnitTestVerifier validator = new VerifyGetters(alert); validator.Verify(new AlertClassUnitTestData { AppliesTo = "HostAName, HostBName", FixLinkText = "Go to Web Page", HelpID = "XenServerUpdateAlert", Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.", HelpLinkText = "Help", Title = "name is now available", Priority = "Priority5" }); Assert.IsFalse(alert.CanIgnore); VerifyConnExpectations(Times.Never); VerifyHostsExpectations(Times.Once); } [Test] public void TestAlertWithConnectionAndNoHosts() { XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, "http://url", new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123"); var alert = new XenServerVersionAlert(ver); alert.IncludeConnection(connA.Object); alert.IncludeConnection(connB.Object); IUnitTestVerifier validator = new VerifyGetters(alert); validator.Verify(new AlertClassUnitTestData { AppliesTo = "ConnAName, ConnBName", FixLinkText = "Go to Web Page", HelpID = "XenServerUpdateAlert", Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.", HelpLinkText = "Help", Title = "name is now available", Priority = "Priority5" }); Assert.IsFalse(alert.CanIgnore); VerifyConnExpectations(Times.Once); VerifyHostsExpectations(Times.Never); } [Test] public void TestAlertWithNoConnectionAndNoHosts() { XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, "http://url", new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123"); var alert = new XenServerVersionAlert(ver); IUnitTestVerifier validator = new VerifyGetters(alert); validator.Verify(new AlertClassUnitTestData { AppliesTo = string.Empty, FixLinkText = "Go to Web Page", HelpID = "XenServerUpdateAlert", Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.", HelpLinkText = "Help", Title = "name is now available", Priority = "Priority5" }); Assert.IsTrue(alert.CanIgnore); VerifyConnExpectations(Times.Never); VerifyHostsExpectations(Times.Never); } [Test, ExpectedException(typeof(NullReferenceException))] public void TestAlertWithNullVersion() { var alert = new XenServerVersionAlert(null); } private void VerifyConnExpectations(Func<Times> times) { connA.VerifyGet(n => n.Name, times()); connB.VerifyGet(n => n.Name, times()); } private void VerifyHostsExpectations(Func<Times> times) { hostA.VerifyGet(n => n.Name, times()); hostB.VerifyGet(n => n.Name, times()); } [SetUp] public void TestSetUp() { connA = new Mock<IXenConnection>(MockBehavior.Strict); connA.Setup(n => n.Name).Returns("ConnAName"); cacheA = new Cache(); connA.Setup(x => x.Cache).Returns(cacheA); connB = new Mock<IXenConnection>(MockBehavior.Strict); connB.Setup(n => n.Name).Returns("ConnBName"); cacheB = new Cache(); connB.Setup(x => x.Cache).Returns(cacheB); hostA = new Mock<Host>(MockBehavior.Strict); hostA.Setup(n => n.Name).Returns("HostAName"); hostA.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostA.Object)); hostB = new Mock<Host>(MockBehavior.Strict); hostB.Setup(n => n.Name).Returns("HostBName"); hostB.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostB.Object)); } [TearDown] public void TestTearDown() { cacheA = null; cacheB = null; connA = null; connB = null; hostA = null; hostB = null; } } }
// // MacSecureMimeContext.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2014 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Collections.Generic; using Org.BouncyCastle.Pkix; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.X509.Store; using MimeKit.MacInterop; namespace MimeKit.Cryptography { public class MacSecureMimeContext : SecureMimeContext { SecKeychain keychain; public MacSecureMimeContext (string path, string password) { if (path == null) throw new ArgumentNullException ("path"); if (password == null) throw new ArgumentNullException ("password"); keychain = SecKeychain.Create (path, password); } public MacSecureMimeContext () { keychain = SecKeychain.Default; } #region implemented abstract members of SecureMimeContext /// <summary> /// Gets the X.509 certificate based on the selector. /// </summary> /// <returns>The certificate on success; otherwise <c>null</c>.</returns> /// <param name="selector">The search criteria for the certificate.</param> protected override X509Certificate GetCertificate (IX509Selector selector) { foreach (var certificate in keychain.GetCertificates ((CssmKeyUse) 0)) { if (selector.Match (certificate)) return certificate; } return null; } /// <summary> /// Gets the private key based on the provided selector. /// </summary> /// <returns>The private key on success; otherwise <c>null</c>.</returns> /// <param name="selector">The search criteria for the private key.</param> protected override AsymmetricKeyParameter GetPrivateKey (IX509Selector selector) { foreach (var signer in keychain.GetAllCmsSigners ()) { if (selector.Match (signer.Certificate)) return signer.PrivateKey; } return null; } /// <summary> /// Gets the trust anchors. /// </summary> /// <returns>The trust anchors.</returns> protected override Org.BouncyCastle.Utilities.Collections.HashSet GetTrustedAnchors () { var anchors = new Org.BouncyCastle.Utilities.Collections.HashSet (); // FIXME: how do we get the trusted root certs? return anchors; } /// <summary> /// Gets the intermediate certificates. /// </summary> /// <returns>The intermediate certificates.</returns> protected override IX509Store GetIntermediateCertificates () { var store = new X509CertificateStore (); foreach (var certificate in keychain.GetCertificates ((CssmKeyUse) 0)) { store.Add (certificate); } return store; } /// <summary> /// Gets the certificate revocation lists. /// </summary> /// <returns>The certificate revocation lists.</returns> protected override IX509Store GetCertificateRevocationLists () { var crls = new List<X509Crl> (); return X509StoreFactory.Create ("Crl/Collection", new X509CollectionStoreParameters (crls)); } /// <summary> /// Gets the <see cref="CmsRecipient"/> for the specified mailbox. /// </summary> /// <returns>A <see cref="CmsRecipient"/>.</returns> /// <param name="mailbox">The mailbox.</param> /// <exception cref="CertificateNotFoundException"> /// A certificate for the specified <paramref name="mailbox"/> could not be found. /// </exception> protected override CmsRecipient GetCmsRecipient (MailboxAddress mailbox) { foreach (var certificate in keychain.GetCertificates (CssmKeyUse.Encrypt)) { if (certificate.GetSubjectEmailAddress () == mailbox.Address) return new CmsRecipient (certificate); } throw new CertificateNotFoundException (mailbox, "A valid certificate could not be found."); } /// <summary> /// Gets the <see cref="CmsSigner"/> for the specified mailbox. /// </summary> /// <returns>A <see cref="CmsSigner"/>.</returns> /// <param name="mailbox">The mailbox.</param> /// <param name="digestAlgo">The preferred digest algorithm.</param> /// <exception cref="CertificateNotFoundException"> /// A certificate for the specified <paramref name="mailbox"/> could not be found. /// </exception> protected override CmsSigner GetCmsSigner (MailboxAddress mailbox, DigestAlgorithm digestAlgo) { foreach (var signer in keychain.GetAllCmsSigners ()) { if (signer.Certificate.GetSubjectEmailAddress () == mailbox.Address) { signer.DigestAlgorithm = digestAlgo; return signer; } } throw new CertificateNotFoundException (mailbox, "A valid signing certificate could not be found."); } /// <summary> /// Updates the known S/MIME capabilities of the client used by the recipient that owns the specified certificate. /// </summary> /// <param name="certificate">The certificate.</param> /// <param name="algorithms">The encryption algorithm capabilities of the client (in preferred order).</param> /// <param name="timestamp">The timestamp.</param> protected override void UpdateSecureMimeCapabilities (X509Certificate certificate, EncryptionAlgorithm[] algorithms, DateTime timestamp) { // FIXME: implement this } /// <summary> /// Import the specified certificate. /// </summary> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public override void Import (X509Certificate certificate) { if (certificate == null) throw new ArgumentNullException ("certificate"); keychain.Add (certificate); } /// <summary> /// Import the specified certificate revocation list. /// </summary> /// <param name="crl">The certificate revocation list.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="crl"/> is <c>null</c>. /// </exception> public override void Import (X509Crl crl) { if (crl == null) throw new ArgumentNullException ("crl"); // FIXME: implement this } /// <summary> /// Imports certificates and keys from a pkcs12-encoded stream. /// </summary> /// <param name="stream">The raw certificate and key data.</param> /// <param name="password">The password to unlock the stream.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="stream"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="password"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// Importing keys is not supported by this cryptography context. /// </exception> public override void Import (Stream stream, string password) { if (stream == null) throw new ArgumentNullException ("stream"); if (password == null) throw new ArgumentNullException ("password"); var pkcs12 = new Pkcs12Store (stream, password.ToCharArray ()); foreach (string alias in pkcs12.Aliases) { if (pkcs12.IsKeyEntry (alias)) { var chain = pkcs12.GetCertificateChain (alias); var entry = pkcs12.GetKey (alias); for (int i = 0; i < chain.Length; i++) keychain.Add (chain[i].Certificate); keychain.Add (entry.Key); } else if (pkcs12.IsCertificateEntry (alias)) { var entry = pkcs12.GetCertificate (alias); keychain.Add (entry.Certificate); } } } #endregion /// <summary> /// Releases all resources used by the <see cref="MimeKit.Cryptography.MacSecureMimeContext"/> object. /// </summary> /// <param name="disposing">If <c>true</c>, this method is being called by /// <see cref="MimeKit.Cryptography.CryptographyContext.Dispose()"/>; /// otherwise it is being called by the finalizer.</param> protected override void Dispose (bool disposing) { if (disposing && keychain != SecKeychain.Default) { keychain.Dispose (); keychain = null; } base.Dispose (disposing); } } }
//----------------------------------------------------------------------- // <copyright file="CommandBase.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>This is the base class from which command </summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using Csla.Server; using Csla.Properties; using Csla.Core; using Csla.Serialization.Mobile; using Csla.DataPortalClient; using System.Linq.Expressions; using Csla.Reflection; using System.Reflection; using System.Threading.Tasks; namespace Csla { /// <summary> /// This is the base class from which command /// objects will be derived. /// </summary> /// <remarks> /// <para> /// Command objects allow the execution of arbitrary server-side /// functionality. Most often, this involves the invocation of /// a stored procedure in the database, but can involve any other /// type of stateless, atomic call to the server instead. /// </para><para> /// To implement a command object, inherit from CommandBase and /// override the DataPortal_Execute method. In this method you can /// implement any server-side code as required. /// </para><para> /// To pass data to/from the server, use instance variables within /// the command object itself. The command object is instantiated on /// the client, and is passed by value to the server where the /// DataPortal_Execute method is invoked. The command object is then /// returned to the client by value. /// </para> /// </remarks> [Serializable] public abstract class CommandBase<T> : ManagedObjectBase, ICommandObject, ICloneable, Csla.Server.IDataPortalTarget, Csla.Core.IManageProperties, ICommandBase where T : CommandBase<T> { /// <summary> /// Creates an instance of the object. /// </summary> public CommandBase() { Initialize(); } #region Initialize /// <summary> /// Override this method to set up event handlers so user /// code in a partial class can respond to events raised by /// generated code. /// </summary> protected virtual void Initialize() { /* allows subclass to initialize events before any other activity occurs */ } #endregion #region Identity int IBusinessObject.Identity { get { return 0; } } #endregion #region Data Access [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void DataPortal_Create(object criteria) { throw new NotSupportedException(Resources.CreateNotSupportedException); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void DataPortal_Fetch(object criteria) { throw new NotSupportedException(Resources.FetchNotSupportedException); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void DataPortal_Update() { throw new NotSupportedException(Resources.UpdateNotSupportedException); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void DataPortal_Delete(object criteria) { throw new NotSupportedException(Resources.DeleteNotSupportedException); } /// <summary> /// Override this method to implement any server-side code /// that is to be run when the command is executed. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] protected virtual void DataPortal_Execute() { throw new NotSupportedException(Resources.ExecuteNotSupportedException); } /// <summary> /// Called by the server-side DataPortal prior to calling the /// requested DataPortal_xyz method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal after calling the /// requested DataPortal_xyz method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal if an exception /// occurs during server-side processing. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> /// <param name="ex">The Exception thrown during processing.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } #endregion #region IDataPortalTarget Members void IDataPortalTarget.CheckRules() { } void IDataPortalTarget.MarkAsChild() { } void IDataPortalTarget.MarkNew() { } void IDataPortalTarget.MarkOld() { } void IDataPortalTarget.DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvoke(e); } void IDataPortalTarget.DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvokeComplete(e); } void IDataPortalTarget.DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { this.DataPortal_OnDataPortalException(e, ex); } void IDataPortalTarget.Child_OnDataPortalInvoke(DataPortalEventArgs e) { } void IDataPortalTarget.Child_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } void IDataPortalTarget.Child_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } #endregion #region ICloneable object ICloneable.Clone() { return GetClone(); } /// <summary> /// Creates a clone of the object. /// </summary> /// <returns> /// A new object containing the exact data of the original object. /// </returns> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual object GetClone() { return ObjectCloner.Clone(this); } /// <summary> /// Creates a clone of the object. /// </summary> /// <returns> /// A new object containing the exact data of the original object. /// </returns> public T Clone() { return (T)GetClone(); } #endregion #region Register Properties /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P"> /// Type of property. /// </typeparam> /// <param name="info"> /// PropertyInfo object for the property. /// </param> /// <returns> /// The provided IPropertyInfo object. /// </returns> protected static PropertyInfo<P> RegisterProperty<P>(PropertyInfo<P> info) { return Core.FieldManager.PropertyInfoManager.RegisterProperty<P>(typeof(T), info); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="defaultValue">Default Value for the property</param> /// <returns></returns> [Obsolete] protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, P defaultValue) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), reflectedPropertyInfo.Name, reflectedPropertyInfo.Name, defaultValue)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, RelationshipTypes relationship) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, string.Empty, relationship)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, RelationshipTypes relationship) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name, relationship); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name, friendlyName); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> [Obsolete] protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, RelationshipTypes relationship) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), reflectedPropertyInfo.Name, friendlyName, relationship)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName, P defaultValue) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName, defaultValue)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, P defaultValue) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name, friendlyName, defaultValue); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName, P defaultValue, RelationshipTypes relationship) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName, defaultValue, relationship)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, P defaultValue, RelationshipTypes relationship) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name, friendlyName, defaultValue, relationship); } #endregion #region IManageProperties Members bool IManageProperties.HasManagedProperties { get { return (FieldManager != null && FieldManager.HasFields); } } List<IPropertyInfo> IManageProperties.GetManagedProperties() { return FieldManager.GetRegisteredProperties(); } object IManageProperties.GetProperty(IPropertyInfo propertyInfo) { return ReadProperty(propertyInfo); } object IManageProperties.ReadProperty(IPropertyInfo propertyInfo) { return ReadProperty(propertyInfo); } P IManageProperties.ReadProperty<P>(PropertyInfo<P> propertyInfo) { return ReadProperty<P>(propertyInfo); } void IManageProperties.SetProperty(IPropertyInfo propertyInfo, object newValue) { FieldManager.SetFieldData(propertyInfo, newValue); } void IManageProperties.LoadProperty(IPropertyInfo propertyInfo, object newValue) { LoadProperty(propertyInfo, newValue); } void IManageProperties.LoadProperty<P>(PropertyInfo<P> propertyInfo, P newValue) { LoadProperty<P>(propertyInfo, newValue); } bool IManageProperties.LoadPropertyMarkDirty(IPropertyInfo propertyInfo, object newValue) { LoadProperty(propertyInfo, newValue); return false; } List<object> IManageProperties.GetChildren() { return FieldManager.GetChildren(); } bool IManageProperties.FieldExists(Core.IPropertyInfo property) { return FieldManager.FieldExists(property); } object IManageProperties.LazyGetProperty<P>(PropertyInfo<P> propertyInfo, Func<P> valueGenerator) { throw new NotImplementedException(); } object IManageProperties.LazyGetPropertyAsync<P>(PropertyInfo<P> propertyInfo, Task<P> factory) { throw new NotImplementedException(); } P IManageProperties.LazyReadProperty<P>(PropertyInfo<P> propertyInfo, Func<P> valueGenerator) { throw new NotImplementedException(); } P IManageProperties.LazyReadPropertyAsync<P>(PropertyInfo<P> propertyInfo, Task<P> factory) { throw new NotImplementedException(); } #endregion } }
/** * (C) Copyright IBM Corp. 2019, 2020. * * 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. * */ /** * IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-153452 */ using System.Collections.Generic; using System.Text; using IBM.Cloud.SDK; using IBM.Cloud.SDK.Authentication; using IBM.Cloud.SDK.Connection; using IBM.Cloud.SDK.Utilities; using IBM.Watson.PersonalityInsights.V3.Model; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using UnityEngine.Networking; namespace IBM.Watson.PersonalityInsights.V3 { [System.Obsolete("On 1 December 2021, Personality Insights will no longer be available." + " Consider migrating to Watson Natural Language Understanding." + "\nFor more information, see Personality Insights Deprecation " + "(https://github.com/watson-developer-cloud/unity-sdk/tree/master#personality-insights-deprecation).")] public partial class PersonalityInsightsService : BaseService { private const string defaultServiceName = "personality_insights"; private const string defaultServiceUrl = "https://api.us-south.personality-insights.watson.cloud.ibm.com"; #region Version private string version; /// <summary> /// Gets and sets the version of the service. /// Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current /// version is `2017-10-13`. /// </summary> public string Version { get { return version; } set { version = value; } } #endregion #region DisableSslVerification private bool disableSslVerification = false; /// <summary> /// Gets and sets the option to disable ssl verification /// </summary> public bool DisableSslVerification { get { return disableSslVerification; } set { disableSslVerification = value; } } #endregion /// <summary> /// PersonalityInsightsService constructor. /// </summary> /// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD /// format. The current version is `2017-10-13`.</param> public PersonalityInsightsService(string version) : this(version, defaultServiceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(defaultServiceName)) {} /// <summary> /// PersonalityInsightsService constructor. /// </summary> /// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD /// format. The current version is `2017-10-13`.</param> /// <param name="authenticator">The service authenticator.</param> public PersonalityInsightsService(string version, Authenticator authenticator) : this(version, defaultServiceName, authenticator) {} /// <summary> /// PersonalityInsightsService constructor. /// </summary> /// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD /// format. The current version is `2017-10-13`.</param> /// <param name="serviceName">The service name to be used when configuring the client instance</param> public PersonalityInsightsService(string version, string serviceName) : this(version, serviceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceName)) {} /// <summary> /// PersonalityInsightsService constructor. /// </summary> /// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD /// format. The current version is `2017-10-13`.</param> /// <param name="serviceName">The service name to be used when configuring the client instance</param> /// <param name="authenticator">The service authenticator.</param> public PersonalityInsightsService(string version, string serviceName, Authenticator authenticator) : base(authenticator, serviceName) { Authenticator = authenticator; if (string.IsNullOrEmpty(version)) { throw new ArgumentNullException("`version` is required"); } else { Version = version; } if (string.IsNullOrEmpty(GetServiceUrl())) { SetServiceUrl(defaultServiceUrl); } } /// <summary> /// Get profile. /// /// Generates a personality profile for the author of the input text. The service accepts a maximum of 20 MB of /// input content, but it requires much less text to produce an accurate profile. The service can analyze text /// in Arabic, English, Japanese, Korean, or Spanish. It can return its results in a variety of languages. /// /// **See also:** /// * [Requesting a /// profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#input) /// * [Providing sufficient /// input](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#sufficient) /// /// ### Content types /// /// You can provide input content as plain text (`text/plain`), HTML (`text/html`), or JSON /// (`application/json`) by specifying the **Content-Type** parameter. The default is `text/plain`. /// * Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8. /// * Per the HTTP specification, the default encoding for plain text and HTML is ISO-8859-1 (effectively, the /// ASCII character set). /// /// When specifying a content type of plain text or HTML, include the `charset` parameter to indicate the /// character encoding of the input text; for example, `Content-Type: text/plain;charset=utf-8`. /// /// **See also:** [Specifying request and response /// formats](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#formats) /// /// ### Accept types /// /// You must request a response as JSON (`application/json`) or comma-separated values (`text/csv`) by /// specifying the **Accept** parameter. CSV output includes a fixed number of columns. Set the **csv_headers** /// parameter to `true` to request optional column headers for CSV output. /// /// **See also:** /// * [Understanding a JSON /// profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-output#output) /// * [Understanding a CSV /// profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-outputCSV#outputCSV). /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="content">A maximum of 20 MB of content to analyze, though the service requires much less text; /// for more information, see [Providing sufficient /// input](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#sufficient). For /// JSON input, provide an object of type `Content`.</param> /// <param name="contentType">The type of the input. For more information, see **Content types** in the method /// description. (optional, default to text/plain)</param> /// <param name="contentLanguage">The language of the input text for the request: Arabic, English, Japanese, /// Korean, or Spanish. Regional variants are treated as their parent language; for example, `en-US` is /// interpreted as `en`. /// /// The effect of the **Content-Language** parameter depends on the **Content-Type** parameter. When /// **Content-Type** is `text/plain` or `text/html`, **Content-Language** is the only way to specify the /// language. When **Content-Type** is `application/json`, **Content-Language** overrides a language specified /// with the `language` parameter of a `ContentItem` object, and content items that specify a different language /// are ignored; omit this parameter to base the language on the specification of the content items. You can /// specify any combination of languages for **Content-Language** and **Accept-Language**. (optional, default to /// en)</param> /// <param name="acceptLanguage">The desired language of the response. For two-character arguments, regional /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can specify /// any combination of languages for the input and response content. (optional, default to en)</param> /// <param name="rawScores">Indicates whether a raw score in addition to a normalized percentile is returned for /// each characteristic; raw scores are not compared with a sample population. By default, only normalized /// percentiles are returned. (optional, default to false)</param> /// <param name="csvHeaders">Indicates whether column labels are returned with a CSV response. By default, no /// column labels are returned. Applies only when the response type is CSV (`text/csv`). (optional, default to /// false)</param> /// <param name="consumptionPreferences">Indicates whether consumption preferences are returned with the /// results. By default, no consumption preferences are returned. (optional, default to false)</param> /// <returns><see cref="Profile" />Profile</returns> public bool Profile(Callback<Profile> callback, System.IO.MemoryStream content, string contentType = null, string contentLanguage = null, string acceptLanguage = null, bool? rawScores = null, bool? csvHeaders = null, bool? consumptionPreferences = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `Profile`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); if (content == null) throw new ArgumentNullException("`content` is required for `Profile`"); RequestObject<Profile> req = new RequestObject<Profile> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbPOST, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("personality_insights", "V3", "Profile")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } if (rawScores != null) { req.Parameters["raw_scores"] = (bool)rawScores ? "true" : "false"; } if (csvHeaders != null) { req.Parameters["csv_headers"] = (bool)csvHeaders ? "true" : "false"; } if (consumptionPreferences != null) { req.Parameters["consumption_preferences"] = (bool)consumptionPreferences ? "true" : "false"; } req.Headers["Accept"] = "application/json"; if (!string.IsNullOrEmpty(contentType)) { req.Headers["Content-Type"] = contentType; } if (!string.IsNullOrEmpty(contentLanguage)) { req.Headers["Content-Language"] = contentLanguage; } if (!string.IsNullOrEmpty(acceptLanguage)) { req.Headers["Accept-Language"] = acceptLanguage; } req.Send = content.ToArray(); req.OnResponse = OnProfileResponse; Connector.URL = GetServiceUrl() + "/v3/profile"; Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnProfileResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<Profile> response = new DetailedResponse<Profile>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; try { string json = Encoding.UTF8.GetString(resp.Data); response.Result = JsonConvert.DeserializeObject<Profile>(json); response.Response = json; } catch (Exception e) { Log.Error("PersonalityInsightsService.OnProfileResponse()", "Exception: {0}", e.ToString()); resp.Success = false; } if (((RequestObject<Profile>)req).Callback != null) ((RequestObject<Profile>)req).Callback(response, resp.Error); } /// <summary> /// Get profile as csv. /// /// Generates a personality profile for the author of the input text. The service accepts a maximum of 20 MB of /// input content, but it requires much less text to produce an accurate profile. The service can analyze text /// in Arabic, English, Japanese, Korean, or Spanish. It can return its results in a variety of languages. /// /// **See also:** /// * [Requesting a /// profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#input) /// * [Providing sufficient /// input](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#sufficient) /// /// ### Content types /// /// You can provide input content as plain text (`text/plain`), HTML (`text/html`), or JSON /// (`application/json`) by specifying the **Content-Type** parameter. The default is `text/plain`. /// * Per the JSON specification, the default character encoding for JSON content is effectively always UTF-8. /// * Per the HTTP specification, the default encoding for plain text and HTML is ISO-8859-1 (effectively, the /// ASCII character set). /// /// When specifying a content type of plain text or HTML, include the `charset` parameter to indicate the /// character encoding of the input text; for example, `Content-Type: text/plain;charset=utf-8`. /// /// **See also:** [Specifying request and response /// formats](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#formats) /// /// ### Accept types /// /// You must request a response as JSON (`application/json`) or comma-separated values (`text/csv`) by /// specifying the **Accept** parameter. CSV output includes a fixed number of columns. Set the **csv_headers** /// parameter to `true` to request optional column headers for CSV output. /// /// **See also:** /// * [Understanding a JSON /// profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-output#output) /// * [Understanding a CSV /// profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-outputCSV#outputCSV). /// </summary> /// <param name="callback">The callback function that is invoked when the operation completes.</param> /// <param name="content">A maximum of 20 MB of content to analyze, though the service requires much less text; /// for more information, see [Providing sufficient /// input](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#sufficient). For /// JSON input, provide an object of type `Content`.</param> /// <param name="contentType">The type of the input. For more information, see **Content types** in the method /// description. (optional, default to text/plain)</param> /// <param name="contentLanguage">The language of the input text for the request: Arabic, English, Japanese, /// Korean, or Spanish. Regional variants are treated as their parent language; for example, `en-US` is /// interpreted as `en`. /// /// The effect of the **Content-Language** parameter depends on the **Content-Type** parameter. When /// **Content-Type** is `text/plain` or `text/html`, **Content-Language** is the only way to specify the /// language. When **Content-Type** is `application/json`, **Content-Language** overrides a language specified /// with the `language` parameter of a `ContentItem` object, and content items that specify a different language /// are ignored; omit this parameter to base the language on the specification of the content items. You can /// specify any combination of languages for **Content-Language** and **Accept-Language**. (optional, default to /// en)</param> /// <param name="acceptLanguage">The desired language of the response. For two-character arguments, regional /// variants are treated as their parent language; for example, `en-US` is interpreted as `en`. You can specify /// any combination of languages for the input and response content. (optional, default to en)</param> /// <param name="rawScores">Indicates whether a raw score in addition to a normalized percentile is returned for /// each characteristic; raw scores are not compared with a sample population. By default, only normalized /// percentiles are returned. (optional, default to false)</param> /// <param name="csvHeaders">Indicates whether column labels are returned with a CSV response. By default, no /// column labels are returned. Applies only when the response type is CSV (`text/csv`). (optional, default to /// false)</param> /// <param name="consumptionPreferences">Indicates whether consumption preferences are returned with the /// results. By default, no consumption preferences are returned. (optional, default to false)</param> /// <returns><see cref="System.IO.MemoryStream" />System.IO.MemoryStream</returns> public bool ProfileAsCsv(Callback<System.IO.MemoryStream> callback, System.IO.MemoryStream content, string contentType = null, string contentLanguage = null, string acceptLanguage = null, bool? rawScores = null, bool? csvHeaders = null, bool? consumptionPreferences = null) { if (callback == null) throw new ArgumentNullException("`callback` is required for `ProfileAsCsv`"); if (string.IsNullOrEmpty(Version)) throw new ArgumentNullException("`Version` is required"); if (content == null) throw new ArgumentNullException("`content` is required for `ProfileAsCsv`"); RequestObject<System.IO.MemoryStream> req = new RequestObject<System.IO.MemoryStream> { Callback = callback, HttpMethod = UnityWebRequest.kHttpVerbPOST, DisableSslVerification = DisableSslVerification }; foreach (KeyValuePair<string, string> kvp in customRequestHeaders) { req.Headers.Add(kvp.Key, kvp.Value); } ClearCustomRequestHeaders(); foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("personality_insights", "V3", "ProfileAsCsv")) { req.Headers.Add(kvp.Key, kvp.Value); } if (!string.IsNullOrEmpty(Version)) { req.Parameters["version"] = Version; } if (rawScores != null) { req.Parameters["raw_scores"] = (bool)rawScores ? "true" : "false"; } if (csvHeaders != null) { req.Parameters["csv_headers"] = (bool)csvHeaders ? "true" : "false"; } if (consumptionPreferences != null) { req.Parameters["consumption_preferences"] = (bool)consumptionPreferences ? "true" : "false"; } req.Headers["Accept"] = "text/csv"; if (!string.IsNullOrEmpty(contentType)) { req.Headers["Content-Type"] = contentType; } if (!string.IsNullOrEmpty(contentLanguage)) { req.Headers["Content-Language"] = contentLanguage; } if (!string.IsNullOrEmpty(acceptLanguage)) { req.Headers["Accept-Language"] = acceptLanguage; } req.Send = content.ToArray(); req.OnResponse = OnProfileAsCsvResponse; Connector.URL = GetServiceUrl() + "/v3/profile"; Authenticator.Authenticate(Connector); return Connector.Send(req); } private void OnProfileAsCsvResponse(RESTConnector.Request req, RESTConnector.Response resp) { DetailedResponse<System.IO.MemoryStream> response = new DetailedResponse<System.IO.MemoryStream>(); foreach (KeyValuePair<string, string> kvp in resp.Headers) { response.Headers.Add(kvp.Key, kvp.Value); } response.StatusCode = resp.HttpResponseCode; response.Result = new System.IO.MemoryStream(resp.Data); if (((RequestObject<System.IO.MemoryStream>)req).Callback != null) ((RequestObject<System.IO.MemoryStream>)req).Callback(response, resp.Error); } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// gRPC server. A single server can server arbitrary number of services and can listen on more than one ports. /// </summary> public class Server { const int DefaultRequestCallTokensPerCq = 2000; static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Server>(); readonly AtomicCounter activeCallCounter = new AtomicCounter(); readonly ServiceDefinitionCollection serviceDefinitions; readonly ServerPortCollection ports; readonly GrpcEnvironment environment; readonly List<ChannelOption> options; readonly ServerSafeHandle handle; readonly object myLock = new object(); readonly List<ServerServiceDefinition> serviceDefinitionsList = new List<ServerServiceDefinition>(); readonly List<ServerPort> serverPortList = new List<ServerPort>(); readonly Dictionary<string, IServerCallHandler> callHandlers = new Dictionary<string, IServerCallHandler>(); readonly TaskCompletionSource<object> shutdownTcs = new TaskCompletionSource<object>(); bool startRequested; volatile bool shutdownRequested; int requestCallTokensPerCq = DefaultRequestCallTokensPerCq; /// <summary> /// Creates a new server. /// </summary> public Server() : this(null) { } /// <summary> /// Creates a new server. /// </summary> /// <param name="options">Channel options.</param> public Server(IEnumerable<ChannelOption> options) { this.serviceDefinitions = new ServiceDefinitionCollection(this); this.ports = new ServerPortCollection(this); this.environment = GrpcEnvironment.AddRef(); this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>(); using (var channelArgs = ChannelOptions.CreateChannelArgs(this.options)) { this.handle = ServerSafeHandle.NewServer(channelArgs); } foreach (var cq in environment.CompletionQueues) { this.handle.RegisterCompletionQueue(cq); } GrpcEnvironment.RegisterServer(this); } /// <summary> /// Services that will be exported by the server once started. Register a service with this /// server by adding its definition to this collection. /// </summary> public ServiceDefinitionCollection Services { get { return serviceDefinitions; } } /// <summary> /// Ports on which the server will listen once started. Register a port with this /// server by adding its definition to this collection. /// </summary> public ServerPortCollection Ports { get { return ports; } } /// <summary> /// To allow awaiting termination of the server. /// </summary> public Task ShutdownTask { get { return shutdownTcs.Task; } } /// <summary> /// Experimental API. Might anytime change without prior notice. /// Number or calls requested via grpc_server_request_call at any given time for each completion queue. /// </summary> public int RequestCallTokensPerCompletionQueue { get { return requestCallTokensPerCq; } set { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); GrpcPreconditions.CheckArgument(value > 0); requestCallTokensPerCq = value; } } } /// <summary> /// Starts the server. /// Throws <c>IOException</c> if not successful. /// </summary> public void Start() { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); GrpcPreconditions.CheckState(!shutdownRequested); startRequested = true; CheckPortsBoundSuccessfully(); handle.Start(); for (int i = 0; i < requestCallTokensPerCq; i++) { foreach (var cq in environment.CompletionQueues) { AllowOneRpc(cq); } } } } /// <summary> /// Requests server shutdown and when there are no more calls being serviced, /// cleans up used resources. The returned task finishes when shutdown procedure /// is complete. /// </summary> /// <remarks> /// It is strongly recommended to shutdown all previously created servers before exiting from the process. /// </remarks> public Task ShutdownAsync() { return ShutdownInternalAsync(false); } /// <summary> /// Requests server shutdown while cancelling all the in-progress calls. /// The returned task finishes when shutdown procedure is complete. /// </summary> /// <remarks> /// It is strongly recommended to shutdown all previously created servers before exiting from the process. /// </remarks> public Task KillAsync() { return ShutdownInternalAsync(true); } internal void AddCallReference(object call) { activeCallCounter.Increment(); bool success = false; handle.DangerousAddRef(ref success); GrpcPreconditions.CheckState(success); } internal void RemoveCallReference(object call) { handle.DangerousRelease(); activeCallCounter.Decrement(); } /// <summary> /// Shuts down the server. /// </summary> private async Task ShutdownInternalAsync(bool kill) { lock (myLock) { GrpcPreconditions.CheckState(!shutdownRequested); shutdownRequested = true; } GrpcEnvironment.UnregisterServer(this); var cq = environment.CompletionQueues.First(); // any cq will do handle.ShutdownAndNotify(HandleServerShutdown, cq); if (kill) { handle.CancelAllCalls(); } await ShutdownCompleteOrEnvironmentDeadAsync().ConfigureAwait(false); DisposeHandle(); await GrpcEnvironment.ReleaseAsync().ConfigureAwait(false); } /// <summary> /// In case the environment's threadpool becomes dead, the shutdown completion will /// never be delivered, but we need to release the environment's handle anyway. /// </summary> private async Task ShutdownCompleteOrEnvironmentDeadAsync() { while (true) { var task = await Task.WhenAny(shutdownTcs.Task, Task.Delay(20)).ConfigureAwait(false); if (shutdownTcs.Task == task) { return; } if (!environment.IsAlive) { return; } } } /// <summary> /// Adds a service definition. /// </summary> private void AddServiceDefinitionInternal(ServerServiceDefinition serviceDefinition) { lock (myLock) { GrpcPreconditions.CheckState(!startRequested); foreach (var entry in serviceDefinition.CallHandlers) { callHandlers.Add(entry.Key, entry.Value); } serviceDefinitionsList.Add(serviceDefinition); } } /// <summary> /// Adds a listening port. /// </summary> private int AddPortInternal(ServerPort serverPort) { lock (myLock) { GrpcPreconditions.CheckNotNull(serverPort.Credentials, "serverPort"); GrpcPreconditions.CheckState(!startRequested); var address = string.Format("{0}:{1}", serverPort.Host, serverPort.Port); int boundPort; using (var nativeCredentials = serverPort.Credentials.ToNativeCredentials()) { if (nativeCredentials != null) { boundPort = handle.AddSecurePort(address, nativeCredentials); } else { boundPort = handle.AddInsecurePort(address); } } var newServerPort = new ServerPort(serverPort, boundPort); this.serverPortList.Add(newServerPort); return boundPort; } } /// <summary> /// Allows one new RPC call to be received by server. /// </summary> private void AllowOneRpc(CompletionQueueSafeHandle cq) { if (!shutdownRequested) { handle.RequestCall((success, ctx) => HandleNewServerRpc(success, ctx, cq), cq); } } /// <summary> /// Checks that all ports have been bound successfully. /// </summary> private void CheckPortsBoundSuccessfully() { lock (myLock) { var unboundPort = ports.FirstOrDefault(port => port.BoundPort == 0); if (unboundPort != null) { throw new IOException( string.Format("Failed to bind port \"{0}:{1}\"", unboundPort.Host, unboundPort.Port)); } } } private void DisposeHandle() { var activeCallCount = activeCallCounter.Count; if (activeCallCount > 0) { Logger.Warning("Server shutdown has finished but there are still {0} active calls for that server.", activeCallCount); } handle.Dispose(); } /// <summary> /// Selects corresponding handler for given call and handles the call. /// </summary> private async Task HandleCallAsync(ServerRpcNew newRpc, CompletionQueueSafeHandle cq, Action continuation) { try { IServerCallHandler callHandler; if (!callHandlers.TryGetValue(newRpc.Method, out callHandler)) { callHandler = UnimplementedMethodCallHandler.Instance; } await callHandler.HandleCall(newRpc, cq).ConfigureAwait(false); } catch (Exception e) { Logger.Warning(e, "Exception while handling RPC."); } finally { continuation(); } } /// <summary> /// Handles the native callback. /// </summary> private void HandleNewServerRpc(bool success, RequestCallContextSafeHandle ctx, CompletionQueueSafeHandle cq) { bool nextRpcRequested = false; if (success) { var newRpc = ctx.GetServerRpcNew(this); // after server shutdown, the callback returns with null call if (!newRpc.Call.IsInvalid) { nextRpcRequested = true; // Start asynchronous handler for the call. // Don't await, the continuations will run on gRPC thread pool once triggered // by cq.Next(). #pragma warning disable 4014 HandleCallAsync(newRpc, cq, () => AllowOneRpc(cq)); #pragma warning restore 4014 } } if (!nextRpcRequested) { AllowOneRpc(cq); } } /// <summary> /// Handles native callback. /// </summary> private void HandleServerShutdown(bool success, BatchContextSafeHandle ctx, object state) { shutdownTcs.SetResult(null); } /// <summary> /// Collection of service definitions. /// </summary> public class ServiceDefinitionCollection : IEnumerable<ServerServiceDefinition> { readonly Server server; internal ServiceDefinitionCollection(Server server) { this.server = server; } /// <summary> /// Adds a service definition to the server. This is how you register /// handlers for a service with the server. Only call this before Start(). /// </summary> public void Add(ServerServiceDefinition serviceDefinition) { server.AddServiceDefinitionInternal(serviceDefinition); } /// <summary> /// Gets enumerator for this collection. /// </summary> public IEnumerator<ServerServiceDefinition> GetEnumerator() { return server.serviceDefinitionsList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return server.serviceDefinitionsList.GetEnumerator(); } } /// <summary> /// Collection of server ports. /// </summary> public class ServerPortCollection : IEnumerable<ServerPort> { readonly Server server; internal ServerPortCollection(Server server) { this.server = server; } /// <summary> /// Adds a new port on which server should listen. /// Only call this before Start(). /// <returns>The port on which server will be listening.</returns> /// </summary> public int Add(ServerPort serverPort) { return server.AddPortInternal(serverPort); } /// <summary> /// Adds a new port on which server should listen. /// <returns>The port on which server will be listening.</returns> /// </summary> /// <param name="host">the host</param> /// <param name="port">the port. If zero, an unused port is chosen automatically.</param> /// <param name="credentials">credentials to use to secure this port.</param> public int Add(string host, int port, ServerCredentials credentials) { return Add(new ServerPort(host, port, credentials)); } /// <summary> /// Gets enumerator for this collection. /// </summary> public IEnumerator<ServerPort> GetEnumerator() { return server.serverPortList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return server.serverPortList.GetEnumerator(); } } } }
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using System; namespace Fungus { /// <summary> /// Standard comparison operators. /// </summary> public enum CompareOperator { /// <summary> == mathematical operator.</summary> Equals, /// <summary> != mathematical operator.</summary> NotEquals, /// <summary> < mathematical operator.</summary> LessThan, /// <summary> > mathematical operator.</summary> GreaterThan, /// <summary> <= mathematical operator.</summary> LessThanOrEquals, /// <summary> >= mathematical operator.</summary> GreaterThanOrEquals } /// <summary> /// Mathematical operations that can be performed on variables. /// </summary> public enum SetOperator { /// <summary> = operator. </summary> Assign, /// <summary> =! operator. </summary> Negate, /// <summary> += operator. </summary> Add, /// <summary> -= operator. </summary> Subtract, /// <summary> *= operator. </summary> Multiply, /// <summary> /= operator. </summary> Divide } /// <summary> /// Scope types for Variables. /// </summary> public enum VariableScope { /// <summary> Can only be accessed by commands in the same Flowchart. </summary> Private, /// <summary> Can be accessed from any command in any Flowchart. </summary> Public, /// <summary> Creates and/or references a global variable of that name, all variables of this name and scope share the same underlying fungus variable and exist for the duration of the instance of Unity.</summary> Global, } /// <summary> /// Attribute class for variables. /// </summary> public class VariableInfoAttribute : Attribute { public VariableInfoAttribute(string category, string variableType, int order = 0) { this.Category = category; this.VariableType = variableType; this.Order = order; } public string Category { get; set; } public string VariableType { get; set; } public int Order { get; set; } } /// <summary> /// Attribute class for variable properties. /// </summary> public class VariablePropertyAttribute : PropertyAttribute { public VariablePropertyAttribute (params System.Type[] variableTypes) { this.VariableTypes = variableTypes; } public VariablePropertyAttribute (string defaultText, params System.Type[] variableTypes) { this.defaultText = defaultText; this.VariableTypes = variableTypes; } public String defaultText = "<None>"; public Type[] VariableTypes { get; set; } } /// <summary> /// Abstract base class for variables. /// </summary> [RequireComponent(typeof(Flowchart))] public abstract class Variable : MonoBehaviour { [SerializeField] protected VariableScope scope; [SerializeField] protected string key = ""; #region Public members /// <summary> /// Visibility scope for the variable. /// </summary> public virtual VariableScope Scope { get { return scope; } set { scope = value; } } /// <summary> /// String identifier for the variable. /// </summary> public virtual string Key { get { return key; } set { key = value; } } /// <summary> /// Callback to reset the variable if the Flowchart is reset. /// </summary> public abstract void OnReset(); #endregion } /// <summary> /// Generic concrete base class for variables. /// </summary> public abstract class VariableBase<T> : Variable { //caching mechanism for global static variables private VariableBase<T> _globalStaicRef; private VariableBase<T> globalStaicRef { get { if (_globalStaicRef != null) { return _globalStaicRef; } else if(Application.isPlaying) { return _globalStaicRef = FungusManager.Instance.GlobalVariables.GetOrAddVariable(Key, value, this.GetType()); } else { return null; } } } [SerializeField] protected T value; public virtual T Value { get { if (scope != VariableScope.Global || !Application.isPlaying) { return this.value; } else { return globalStaicRef.value; } } set { if (scope != VariableScope.Global || !Application.isPlaying) { this.value = value; } else { globalStaicRef.Value = value; } } } protected T startValue; public override void OnReset() { Value = startValue; } public override string ToString() { return Value.ToString(); } protected virtual void Start() { // Remember the initial value so we can reset later on startValue = Value; } public virtual void Apply(SetOperator setOperator, T value) { Debug.LogError("Variable doesn't have any operators."); } } }
// // CanvasHost.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright 2009 Aaron Bockover // // 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 Gtk; using Gdk; using Hyena.Gui.Theming; namespace Hyena.Gui.Canvas { public class CanvasHost : Widget, ICanvasHost { private Gdk.Window event_window; private CanvasItem canvas_child; private Theme theme; private CanvasManager manager; private bool debug = false; private FpsCalculator fps = new FpsCalculator (); private Hyena.Data.Gui.CellContext context = new Hyena.Data.Gui.CellContext (); public CanvasHost () { HasWindow = false; manager = new CanvasManager (this); } protected CanvasHost (IntPtr native) : base (native) { } protected override void OnRealized () { base.OnRealized (); WindowAttr attributes = new WindowAttr (); attributes.WindowType = Gdk.WindowType.Child; attributes.X = Allocation.X; attributes.Y = Allocation.Y; attributes.Width = Allocation.Width; attributes.Height = Allocation.Height; attributes.Wclass = WindowWindowClass.InputOnly; attributes.EventMask = (int)( EventMask.PointerMotionMask | EventMask.ButtonPressMask | EventMask.ButtonReleaseMask | EventMask.EnterNotifyMask | EventMask.LeaveNotifyMask | EventMask.ExposureMask); WindowAttributesType attributes_mask = WindowAttributesType.X | WindowAttributesType.Y | WindowAttributesType.Wmclass; event_window = new Gdk.Window (Window, attributes, attributes_mask); event_window.UserData = Handle; AllocateChild (); QueueResize (); } protected override void OnUnrealized () { IsRealized = false; event_window.UserData = IntPtr.Zero; event_window.Destroy (); event_window = null; base.OnUnrealized (); } protected override void OnMapped () { event_window.Show (); base.OnMapped (); } protected override void OnUnmapped () { event_window.Hide (); base.OnUnmapped (); } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { base.OnSizeAllocated (allocation); if (IsRealized) { event_window.MoveResize (allocation); AllocateChild (); } } protected override void OnGetPreferredHeight (out int minimum_height, out int natural_height) { base.OnGetPreferredHeight (out minimum_height, out natural_height); var requisition = SizeRequested (); minimum_height = natural_height = requisition.Height; } protected override void OnGetPreferredWidth (out int minimum_width, out int natural_width) { base.OnGetPreferredWidth (out minimum_width, out natural_width); var requisition = SizeRequested (); minimum_width = natural_width = requisition.Width; } protected Requisition SizeRequested () { var requisition = new Requisition (); if (canvas_child != null) { Size size = canvas_child.Measure (Size.Empty); if (size.Width > 0) { requisition.Width = (int)Math.Ceiling (size.Width); } if (size.Height > 0) { requisition.Height = (int)Math.Ceiling (size.Height); } } return requisition; } private Random rand; protected override bool OnDamageEvent (Gdk.EventExpose evnt) { if (canvas_child == null || !canvas_child.Visible || !Visible || !IsMapped) { return true; } Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window); context.Context = cr; for (int i = 0; i < evnt.Region.NumRectangles; i++) { var damage = evnt.Region.GetRectangle (i); cr.Rectangle (damage.X, damage.Y, damage.Width, damage.Height); cr.Clip (); cr.Translate (Allocation.X, Allocation.Y); canvas_child.Render (context); cr.Translate (-Allocation.X, -Allocation.Y); if (Debug) { cr.LineWidth = 1.0; cr.SetSourceColor (CairoExtensions.RgbToColor ( (uint)(rand = rand ?? new Random ()).Next (0, 0xffffff))); cr.Rectangle (damage.X + 0.5, damage.Y + 0.5, damage.Width - 1, damage.Height - 1); cr.Stroke (); } cr.ResetClip (); } CairoExtensions.DisposeContext (cr); if (fps.Update ()) { // Console.WriteLine ("FPS: {0}", fps.FramesPerSecond); } return true; } private void AllocateChild () { if (canvas_child != null) { canvas_child.Allocation = new Rect (0, 0, Allocation.Width, Allocation.Height); canvas_child.Measure (new Size (Allocation.Width, Allocation.Height)); canvas_child.Arrange (); } } public void QueueRender (CanvasItem item, Rect rect) { double x = Allocation.X; double y = Allocation.Y; double w, h; if (rect.IsEmpty) { w = item.Allocation.Width; h = item.Allocation.Height; } else { x += rect.X; y += rect.Y; w = rect.Width; h = rect.Height; } while (item != null) { x += item.ContentAllocation.X; y += item.ContentAllocation.Y; item = item.Parent; } QueueDrawArea ( (int)Math.Floor (x), (int)Math.Floor (y), (int)Math.Ceiling (w), (int)Math.Ceiling (h) ); } private bool changing_style = false; protected override void OnStyleUpdated () { if (changing_style) { return; } changing_style = true; theme = new GtkTheme (this); context.Theme = theme; if (canvas_child != null) { canvas_child.Theme = theme; } changing_style = false; base.OnStyleUpdated (); } protected override bool OnButtonPressEvent (Gdk.EventButton press) { if (canvas_child != null) { canvas_child.ButtonEvent (new Point (press.X, press.Y), true, press.Button); } return true; } protected override bool OnButtonReleaseEvent (Gdk.EventButton press) { if (canvas_child != null) { canvas_child.ButtonEvent (new Point (press.X, press.Y), false, press.Button); } return true; } protected override bool OnMotionNotifyEvent (EventMotion evnt) { if (canvas_child != null) { canvas_child.CursorMotionEvent (new Point (evnt.X, evnt.Y)); } return true; } public void Add (CanvasItem child) { if (Child != null) { throw new InvalidOperationException ("Child is already set, remove it first"); } Child = child; } public void Remove (CanvasItem child) { if (Child != child) { throw new InvalidOperationException ("child does not already belong to host"); } Child = null; } private void OnCanvasChildLayoutUpdated (object o, EventArgs args) { QueueDraw (); } private void OnCanvasChildSizeChanged (object o, EventArgs args) { QueueResize (); } public CanvasItem Child { get { return canvas_child; } set { if (canvas_child == value) { return; } else if (canvas_child != null) { canvas_child.Theme = null; canvas_child.Manager = null; canvas_child.LayoutUpdated -= OnCanvasChildLayoutUpdated; canvas_child.SizeChanged -= OnCanvasChildSizeChanged; } canvas_child = value; if (canvas_child != null) { canvas_child.Theme = theme; canvas_child.Manager = manager; canvas_child.LayoutUpdated += OnCanvasChildLayoutUpdated; canvas_child.SizeChanged += OnCanvasChildSizeChanged; } AllocateChild (); } } Pango.Layout layout; public Pango.Layout PangoLayout { get { if (layout == null) { if (Window == null || !IsRealized) { return null; } using (var cr = Gdk.CairoHelper.Create (Window)) { layout = CairoExtensions.CreateLayout (this, cr); FontDescription = layout.FontDescription; } } return layout; } } public Pango.FontDescription FontDescription { get; private set; } public bool Debug { get { return debug; } set { debug = value; } } } }
// 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 OLEDB.Test.ModuleCore; using System.IO; using System.Text; using XmlCoreTest.Common; namespace System.Xml.Tests { [InheritRequired()] public abstract partial class TCReadContentAsBinHex : TCXMLReaderBaseGeneral { public const string ST_ELEM_NAME1 = "ElemAll"; public const string ST_ELEM_NAME2 = "ElemEmpty"; public const string ST_ELEM_NAME3 = "ElemNum"; public const string ST_ELEM_NAME4 = "ElemText"; public const string ST_ELEM_NAME5 = "ElemNumText"; public const string ST_ELEM_NAME6 = "ElemLong"; public static string BinHexXml = "BinHex.xml"; public const string strTextBinHex = "ABCDEF"; public const string strNumBinHex = "0123456789"; public override int Init(object objParam) { int ret = base.Init(objParam); CreateTestFile(EREADER_TYPE.BINHEX_TEST); return ret; } public override int Terminate(object objParam) { if (DataReader.Internal != null) { while (DataReader.Read()) ; DataReader.Close(); } return base.Terminate(objParam); } private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType) { bool bPassed = false; byte[] buffer = new byte[iBufferSize]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); DataReader.Read(); if (CheckCanReadBinaryContent()) return true; try { DataReader.ReadContentAsBinHex(buffer, iIndex, iCount); } catch (Exception e) { CError.WriteLine("Actual exception:{0}", e.GetType().ToString()); CError.WriteLine("Expected exception:{0}", exceptionType.ToString()); bPassed = (e.GetType().ToString() == exceptionType.ToString()); } return bPassed; } protected void TestInvalidNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); string name = DataReader.Name; string value = DataReader.Value; byte[] buffer = new byte[1]; if (CheckCanReadBinaryContent()) return; try { int nBytes = DataReader.ReadContentAsBinHex(buffer, 0, 1); } catch (InvalidOperationException) { return; } CError.Compare(false, "Invalid OP exception not thrown on wrong nodetype"); } [Variation("ReadBinHex Element with all valid value")] public int TestReadBinHex_1() { int binhexlen = 0; byte[] binhex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; binhexlen = DataReader.ReadContentAsBinHex(binhex, 0, binhex.Length); string strActbinhex = ""; for (int i = 0; i < binhexlen; i = i + 2) { strActbinhex += System.BitConverter.ToChar(binhex, i); } CError.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Num value", Pri = 0)] public int TestReadBinHex_2() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME3); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Text value")] public int TestReadBinHex_3() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex"); return TEST_PASS; } public void Dump(byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { CError.WriteLineIgnore("Byte" + i + ": " + bytes[i]); } } [Variation("ReadBinHex Element on CDATA", Pri = 0)] public int TestReadBinHex_4() { int BinHexlen = 0; byte[] BinHex = new byte[3]; string xmlStr = "<root><![CDATA[ABCDEF]]></root>"; ReloadSource(new StringReader(xmlStr)); DataReader.PositionOnElement("root"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); CError.Compare(BinHexlen, 3, "BinHex"); BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); CError.Compare(BinHexlen, 0, "BinHex"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.None, "Not on none"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid value (from concatenation), Pri=0")] public int TestReadBinHex_5() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME5); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all long valid value (from concatenation)")] public int TestReadBinHex_6() { int BinHexlen = 0; byte[] BinHex = new byte[2000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME6); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } string strExpBinHex = ""; for (int i = 0; i < 10; i++) strExpBinHex += (strNumBinHex + strTextBinHex); CError.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex with count > buffer size")] public int TestReadBinHex_7() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with count < 0")] public int TestReadBinHex_8() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index > buffer size")] public int vReadBinHex_9() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index < 0")] public int TestReadBinHex_10() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index + count exceeds buffer")] public int TestReadBinHex_11() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex index & count =0")] public int TestReadBinHex_12() { byte[] buffer = new byte[5]; int iCount = 0; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; try { iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0); } catch (Exception e) { CError.WriteLine(e.ToString()); return TEST_FAIL; } CError.Compare(iCount, 0, "has to be zero"); return TEST_PASS; } [Variation("ReadBinHex Element multiple into same buffer (using offset), Pri=0")] public int TestReadBinHex_13() { int BinHexlen = 10; byte[] BinHex = new byte[BinHexlen]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; string strActbinhex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { DataReader.ReadContentAsBinHex(BinHex, i, 2); strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString(); CError.WriteLine("Actual: " + strActbinhex + " Exp: " + strTextBinHex); CError.Compare(string.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64"); } return TEST_PASS; } [Variation("ReadBinHex with buffer == null")] public int TestReadBinHex_14() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadContentAsBinHex(null, 0, 0); } catch (ArgumentNullException) { return TEST_PASS; } return TEST_FAIL; } [Variation("Read after partial ReadBinHex")] public int TestReadBinHex_16() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement("ElemNum"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[10]; int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 8); CError.Compare(nRead, 8, "0"); DataReader.Read(); CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, "ElemText", string.Empty), "1vn"); return TEST_PASS; } [Variation("Current node on multiple calls")] public int TestReadBinHex_17() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement("ElemNum"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[30]; int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 2); CError.Compare(nRead, 2, "0"); nRead = DataReader.ReadContentAsBinHex(buffer, 0, 19); CError.Compare(nRead, 18, "1"); CError.Compare(DataReader.VerifyNode(XmlNodeType.EndElement, "ElemNum", string.Empty), "1vn"); return TEST_PASS; } [Variation("ReadBinHex with whitespace")] public int TestTextReadBinHex_21() { byte[] buffer = new byte[1]; string strxml = "<abc> 1 1 B </abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex with odd number of chars")] public int TestTextReadBinHex_22() { byte[] buffer = new byte[1]; string strxml = "<abc>11B</abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex when end tag doesn't exist")] public int TestTextReadBinHex_23() { if (IsRoundTrippedReader()) return TEST_SKIPPED; byte[] buffer = new byte[5000]; string strxml = "<B>" + new string('A', 5000); ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("B"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadContentAsBinHex(buffer, 0, 5000); CError.WriteLine("Accepted incomplete element"); return TEST_FAIL; } catch (XmlException e) { CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004); } return TEST_PASS; } [Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes")] public int TestTextReadBinHex_24() { string filename = Path.Combine(TestData, "Common", "Bug99148.xml"); ReloadSource(filename); DataReader.MoveToContent(); int bytes = -1; DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; StringBuilder output = new StringBuilder(); while (bytes != 0) { byte[] bbb = new byte[1024]; bytes = DataReader.ReadContentAsBinHex(bbb, 0, bbb.Length); for (int i = 0; i < bytes; i++) { CError.Write(bbb[i].ToString()); output.AppendFormat(bbb[i].ToString()); } } CError.WriteLine(); CError.WriteLine("Length of the output : " + output.ToString().Length); return (CError.Compare(output.ToString().Length, 1735, "Expected Length : 1735")) ? TEST_PASS : TEST_FAIL; } } [InheritRequired()] public abstract partial class TCReadElementContentAsBinHex : TCXMLReaderBaseGeneral { public const string ST_ELEM_NAME1 = "ElemAll"; public const string ST_ELEM_NAME2 = "ElemEmpty"; public const string ST_ELEM_NAME3 = "ElemNum"; public const string ST_ELEM_NAME4 = "ElemText"; public const string ST_ELEM_NAME5 = "ElemNumText"; public const string ST_ELEM_NAME6 = "ElemLong"; public static string BinHexXml = "BinHex.xml"; public const string strTextBinHex = "ABCDEF"; public const string strNumBinHex = "0123456789"; public override int Init(object objParam) { int ret = base.Init(objParam); CreateTestFile(EREADER_TYPE.BINHEX_TEST); return ret; } public override int Terminate(object objParam) { DataReader.Close(); return base.Terminate(objParam); } private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType) { bool bPassed = false; byte[] buffer = new byte[iBufferSize]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); if (CheckCanReadBinaryContent()) return true; try { DataReader.ReadElementContentAsBinHex(buffer, iIndex, iCount); } catch (Exception e) { CError.WriteLine("Actual exception:{0}", e.GetType().ToString()); CError.WriteLine("Expected exception:{0}", exceptionType.ToString()); bPassed = (e.GetType().ToString() == exceptionType.ToString()); } return bPassed; } protected void TestInvalidNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); string name = DataReader.Name; string value = DataReader.Value; byte[] buffer = new byte[1]; if (CheckCanReadBinaryContent()) return; try { int nBytes = DataReader.ReadElementContentAsBinHex(buffer, 0, 1); } catch (InvalidOperationException) { return; } CError.Compare(false, "Invalid OP exception not thrown on wrong nodetype"); } [Variation("ReadBinHex Element with all valid value")] public int TestReadBinHex_1() { int binhexlen = 0; byte[] binhex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); if (CheckCanReadBinaryContent()) return TEST_PASS; binhexlen = DataReader.ReadElementContentAsBinHex(binhex, 0, binhex.Length); string strActbinhex = ""; for (int i = 0; i < binhexlen; i = i + 2) { strActbinhex += System.BitConverter.ToChar(binhex, i); } CError.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Num value", Pri = 0)] public int TestReadBinHex_2() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME3); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Text value")] public int TestReadBinHex_3() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with Comments and PIs", Pri = 0)] public int TestReadBinHex_4() { int BinHexlen = 0; byte[] BinHex = new byte[3]; ReloadSource(new StringReader("<root>AB<!--Comment-->CD<?pi target?>EF</root>")); DataReader.PositionOnElement("root"); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); CError.Compare(BinHexlen, 3, "BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid value (from concatenation), Pri=0")] public int TestReadBinHex_5() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME5); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all long valid value (from concatenation)")] public int TestReadBinHex_6() { int BinHexlen = 0; byte[] BinHex = new byte[2000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME6); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } string strExpBinHex = ""; for (int i = 0; i < 10; i++) strExpBinHex += (strNumBinHex + strTextBinHex); CError.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex with count > buffer size")] public int TestReadBinHex_7() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with count < 0")] public int TestReadBinHex_8() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index > buffer size")] public int vReadBinHex_9() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index < 0")] public int TestReadBinHex_10() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index + count exceeds buffer")] public int TestReadBinHex_11() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex index & count =0")] public int TestReadBinHex_12() { byte[] buffer = new byte[5]; int iCount = 0; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); if (CheckCanReadBinaryContent()) return TEST_PASS; try { iCount = DataReader.ReadElementContentAsBinHex(buffer, 0, 0); } catch (Exception e) { CError.WriteLine(e.ToString()); return TEST_FAIL; } CError.Compare(iCount, 0, "has to be zero"); return TEST_PASS; } [Variation("ReadBinHex Element multiple into same buffer (using offset), Pri=0")] public int TestReadBinHex_13() { int BinHexlen = 10; byte[] BinHex = new byte[BinHexlen]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); if (CheckCanReadBinaryContent()) return TEST_PASS; string strActbinhex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { DataReader.ReadElementContentAsBinHex(BinHex, i, 2); strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString(); CError.WriteLine("Actual: " + strActbinhex + " Exp: " + strTextBinHex); CError.Compare(string.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64"); } return TEST_PASS; } [Variation("ReadBinHex with buffer == null")] public int TestReadBinHex_14() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadElementContentAsBinHex(null, 0, 0); } catch (ArgumentNullException) { return TEST_PASS; } return TEST_FAIL; } [Variation("Read after partial ReadBinHex")] public int TestReadBinHex_16() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement("ElemNum"); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[10]; int nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 8); CError.Compare(nRead, 8, "0"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on text node"); return TEST_PASS; } [Variation("No op node types")] public int TestReadBinHex_18() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; TestInvalidNodeType(XmlNodeType.Text); TestInvalidNodeType(XmlNodeType.Attribute); TestInvalidNodeType(XmlNodeType.Whitespace); TestInvalidNodeType(XmlNodeType.ProcessingInstruction); TestInvalidNodeType(XmlNodeType.CDATA); if (!(IsCoreReader() || IsRoundTrippedReader())) { TestInvalidNodeType(XmlNodeType.EndEntity); TestInvalidNodeType(XmlNodeType.EntityReference); } return TEST_PASS; } [Variation("ReadBinHex with whitespace")] public int TestTextReadBinHex_21() { byte[] buffer = new byte[1]; string strxml = "<abc> 1 1 B </abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex with odd number of chars")] public int TestTextReadBinHex_22() { byte[] buffer = new byte[1]; string strxml = "<abc>11B</abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex when end tag doesn't exist")] public int TestTextReadBinHex_23() { if (IsRoundTrippedReader()) return TEST_SKIPPED; byte[] buffer = new byte[5000]; string strxml = "<B>" + new string('A', 5000); ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("B"); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadElementContentAsBinHex(buffer, 0, 5000); CError.WriteLine("Accepted incomplete element"); return TEST_FAIL; } catch (XmlException e) { CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004); } return TEST_PASS; } [Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes")] public int TestTextReadBinHex_24() { string filename = Path.Combine(TestData, "Common", "Bug99148.xml"); ReloadSource(filename); DataReader.MoveToContent(); if (CheckCanReadBinaryContent()) return TEST_PASS; int bytes = -1; StringBuilder output = new StringBuilder(); while (bytes != 0) { byte[] bbb = new byte[1024]; bytes = DataReader.ReadElementContentAsBinHex(bbb, 0, bbb.Length); for (int i = 0; i < bytes; i++) { CError.Write(bbb[i].ToString()); output.AppendFormat(bbb[i].ToString()); } } CError.WriteLine(); CError.WriteLine("Length of the output : " + output.ToString().Length); return (CError.Compare(output.ToString().Length, 1735, "Expected Length : 1735")) ? TEST_PASS : TEST_FAIL; } [Variation("430329: SubtreeReader inserted attributes don't work with ReadContentAsBinHex")] public int TestReadBinHex_430329() { if (IsCustomReader() || IsXsltReader() || IsBinaryReader()) return TEST_SKIPPED; string strxml = "<root xmlns='0102030405060708090a0B0c'><bar/></root>"; ReloadSource(new StringReader(strxml)); DataReader.Read(); DataReader.Read(); using (XmlReader sr = DataReader.ReadSubtree()) { sr.Read(); sr.MoveToFirstAttribute(); sr.MoveToFirstAttribute(); byte[] bytes = new byte[4]; while ((sr.ReadContentAsBinHex(bytes, 0, bytes.Length)) > 0) { if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } } DataReader.Close(); return TEST_PASS; } [Variation("ReadBinHex with = in the middle")] public int TestReadBinHex_27() { byte[] buffer = new byte[1]; string strxml = "<abc>1=2</abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadElementContentAsBinHex(buffer, 0, 1); CError.Compare(false, "ReadBinHex with = in the middle succeeded"); } catch (XmlException) { return TEST_PASS; } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation("ReadBinHex runs into an Overflow", Params = new object[] { "1000000" })] //[Variation("ReadBinHex runs into an Overflow", Params = new object[] { "10000000" })] public int TestReadBinHex_105376() { int totalfilesize = Convert.ToInt32(CurVariation.Params[0].ToString()); CError.WriteLine(" totalfilesize = " + totalfilesize); string ascii = new string('c', totalfilesize); byte[] bits = Encoding.Unicode.GetBytes(ascii); CError.WriteLineIgnore("Count = " + bits.Length); string base64str = Convert.ToBase64String(bits); string fileName = "bug105376c_" + CurVariation.Params[0].ToString() + ".xml"; MemoryStream mems = new MemoryStream(); StreamWriter sw = new StreamWriter(mems); sw.Write("<root><base64>"); sw.Write(base64str); sw.Write("</base64></root>"); sw.Flush();//sw.Close(); FilePathUtil.addStream(fileName, mems); ReloadSource(fileName); int SIZE = (totalfilesize - 30); int SIZE64 = SIZE * 3 / 4; DataReader.PositionOnElement("base64"); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] base64 = new byte[SIZE64]; try { DataReader.ReadElementContentAsBinHex(base64, 0, 4096); return TEST_FAIL; } catch (XmlException) { DataReader.Close(); return TEST_PASS; } finally { DataReader.Close(); } } [Variation("call ReadContentAsBinHex on two or more nodes")] public int TestReadBinHex_28() { string xml = "<elem0> 11B <elem1> 11B <elem2> 11B </elem2> 11B </elem1> 11B </elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; int startPos = 0; int readSize = 3; int currentSize = 0; DataReader.Read(); while (DataReader.Read()) { currentSize = DataReader.ReadContentAsBinHex(buffer, startPos, readSize); CError.Equals(currentSize, 1, "size"); CError.Equals(buffer[0], (byte)17, "buffer"); if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } DataReader.Close(); return TEST_PASS; } [Variation("read BinHex over invalid text node")] public int TestReadBinHex_29() { string xml = "<elem0>12%45<elem1>12%45<elem2>12%45</elem2>12%45</elem1>12%45</elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[5]; int currentSize = 0; while (DataReader.Read()) { DataReader.Read(); try { currentSize = DataReader.ReadContentAsBinHex(buffer, 0, 5); if (!(IsCharCheckingReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsXPathNavigatorReader())) return TEST_FAIL; } catch (XmlException) { CError.Compare(currentSize, 0, "size"); } } DataReader.Close(); return TEST_PASS; } [Variation("goto to text node, ask got.Value, readcontentasBinHex")] public int TestReadBinHex_30() { string xml = "<elem0>123</elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; DataReader.Read(); DataReader.Read(); CError.Compare(DataReader.Value, "123", "value"); CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 1), 1, "size"); DataReader.Close(); return TEST_PASS; } [Variation("goto to text node, readcontentasBinHex, ask got.Value")] public int TestReadBinHex_31() { string xml = "<elem0>123</elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; DataReader.Read(); DataReader.Read(); CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 1), 1, "size"); CError.Compare(DataReader.Value, (IsCharCheckingReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsXPathNavigatorReader()) ? "123" : "3", "value"); DataReader.Close(); return TEST_PASS; } [Variation("goto to huge text node, read several chars with ReadContentAsBinHex and Move forward with .Read()")] public int TestReadBinHex_32() { string xml = "<elem0>1234567 89 1234 123345 5676788 5567712 34567 89 1234 123345 5676788 55677</elem0>"; ReloadSource(new StringReader(xml)); byte[] buffer = new byte[5]; DataReader.Read(); DataReader.Read(); try { CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 5), 5, "size"); } catch (NotSupportedException) { return TEST_PASS; } DataReader.Read(); DataReader.Close(); return TEST_PASS; } [Variation("goto to huge text node with invalid chars, read several chars with ReadContentAsBinHex and Move forward with .Read()")] public int TestReadBinHex_33() { string xml = "<elem0>123 $^ 56789 abcdefg hij klmn opqrst 12345 uvw xy ^ z</elem0>"; ReloadSource(new StringReader(xml)); byte[] buffer = new byte[5]; DataReader.Read(); DataReader.Read(); try { CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 5), 5, "size"); DataReader.Read(); } catch (XmlException) { return TEST_PASS; } catch (NotSupportedException) { return TEST_PASS; } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation("ReadContentAsBinHex on an xmlns attribute", Param = "<foo xmlns='default'> <bar > id='1'/> </foo>")] //[Variation("ReadContentAsBinHex on an xmlns:k attribute", Param = "<k:foo xmlns:k='default'> <k:bar id='1'/> </k:foo>")] //[Variation("ReadContentAsBinHex on an xml:space attribute", Param = "<foo xml:space='default'> <bar > id='1'/> </foo>")] //[Variation("ReadContentAsBinHex on an xml:lang attribute", Param = "<foo xml:lang='default'> <bar > id='1'/> </foo>")] public int TestBinHex_34() { string xml = (string)CurVariation.Param; byte[] buffer = new byte[8]; try { ReloadSource(new StringReader(xml)); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); DataReader.MoveToAttribute(0); CError.Compare(DataReader.Value, "default", "value"); CError.Equals(DataReader.ReadContentAsBinHex(buffer, 0, 8), 5, "size"); CError.Equals(false, "No exception"); } catch (XmlException) { return TEST_PASS; } catch (NotSupportedException) { return TEST_PASS; } finally { DataReader.Close(); } return TEST_FAIL; } [Variation("call ReadContentAsBinHex on two or more nodes and whitespace")] public int TestReadBinHex_35() { string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123 <elem2> 123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; int startPos = 0; int readSize = 3; int currentSize = 0; DataReader.Read(); while (DataReader.Read()) { currentSize = DataReader.ReadContentAsBinHex(buffer, startPos, readSize); CError.Equals(currentSize, 1, "size"); CError.Equals(buffer[0], (byte)18, "buffer"); if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } DataReader.Close(); return TEST_PASS; } [Variation("call ReadContentAsBinHex on two or more nodes and whitespace after call Value")] public int TestReadBinHex_36() { string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123 <elem2> 123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; int startPos = 0; int readSize = 3; int currentSize = 0; DataReader.Read(); while (DataReader.Read()) { CError.Equals(DataReader.Value.Contains("123"), "Value"); currentSize = DataReader.ReadContentAsBinHex(buffer, startPos, readSize); CError.Equals(currentSize, 1, "size"); CError.Equals(buffer[0], (byte)18, "buffer"); if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } DataReader.Close(); return TEST_PASS; } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.DB.Structure; using Autodesk.Revit; using System.Drawing; using Point = System.Drawing.Point; namespace Revit.SDK.Samples.NewPathReinforcement.CS { /// <summary> /// base class of ProfileFloor and ProfileWall /// contains the profile information and can make matrix to transform point to 2D plane /// </summary> public abstract class Profile { #region class member variables /// <summary> /// store all the points on the needed face /// </summary> protected List<List<XYZ>> m_points; /// <summary> /// object which contains reference to Revit Application /// </summary> protected Autodesk.Revit.UI.ExternalCommandData m_commandData; /// <summary> /// used to create new instances of utility objects. /// </summary> protected Autodesk.Revit.Creation.Application m_appCreator; /// <summary> /// used to create new instances of elements /// </summary> protected Autodesk.Revit.Creation.Document m_docCreator; /// <summary> /// store the Matrix used to transform 3D points to 2D /// </summary> protected Matrix4 m_to2DMatrix = null; #endregion /// <summary> /// CommandData property get object which contains reference to Revit Application /// </summary> public Autodesk.Revit.UI.ExternalCommandData CommandData { get { return m_commandData; } } /// <summary> /// To2DMatrix property to get Matrix used to transform 3D points to 2D /// </summary> public Matrix4 To2DMatrix { get { return m_to2DMatrix; } } /// <summary> /// constructor /// </summary> /// <param name="commandData">object which contains reference to Revit Application</param> protected Profile(ExternalCommandData commandData) { m_commandData = commandData; m_appCreator = m_commandData.Application.Application.Create; m_docCreator = m_commandData.Application.ActiveUIDocument.Document.Create; } /// <summary> /// abstract method to create PathReinforcement /// </summary> /// <returns>new created PathReinforcement</returns> /// <param name="points">points used to create PathReinforcement</param> /// <param name="flip">used to specify whether new PathReinforcement is Filp</param> public abstract PathReinforcement CreatePathReinforcement(List<Vector4> points, bool flip); /// <summary> /// Get points in first face /// </summary> /// <param name="faces">edges in all faces</param> /// <returns>points in first face</returns> public abstract List<List<XYZ>> GetNeedPoints(List<List<Edge>> faces); /// <summary> /// Get a matrix which can transform points to 2D /// </summary> public abstract Matrix4 GetTo2DMatrix(); /// <summary> /// draw profile of wall or floor in 2D /// </summary> /// <param name="graphics">form graphic</param> /// <param name="pen">pen used to draw line in pictureBox</param> /// <param name="matrix4">Matrix used to transform 3d to 2d /// and make picture in right scale </param> public void Draw2D(Graphics graphics, Pen pen, Matrix4 matrix4) { for (int i = 0; i < m_points.Count; i++) { List<XYZ> points = m_points[i]; for (int j = 0; j < points.Count - 1; j++) { Autodesk.Revit.DB.XYZ point1 = points[j]; Autodesk.Revit.DB.XYZ point2 = points[j + 1]; Vector4 v1 = new Vector4(point1); Vector4 v2 = new Vector4(point2); v1 = matrix4.Transform(v1); v2 = matrix4.Transform(v2); graphics.DrawLine(pen, new Point((int)v1.X, (int)v1.Y), new Point((int)v2.X, (int)v2.Y)); } } } /// <summary> /// Get edges of element's profile /// </summary> /// <param name="elem">selected element</param> /// <returns>all the faces in the selected Element</returns> public List<List<Edge>> GetFaces(Autodesk.Revit.DB.Element elem) { List<List<Edge>> faceEdges = new List<List<Edge>>(); Options options = m_appCreator.NewGeometryOptions(); options.DetailLevel = DetailLevels.Medium; options.ComputeReferences = true; //make sure references to geometric objects are computed. Autodesk.Revit.DB.GeometryElement geoElem = elem.get_Geometry(options); GeometryObjectArray gObjects = geoElem.Objects; //get all the edges in the Geometry object foreach (GeometryObject geo in gObjects) { Solid solid = geo as Solid; if (solid != null) { FaceArray faces = solid.Faces; foreach (Face face in faces) { EdgeArrayArray edgeArrarr = face.EdgeLoops; foreach (EdgeArray edgeArr in edgeArrarr) { List<Edge> edgesList = new List<Edge>(); foreach (Edge edge in edgeArr) { edgesList.Add(edge); } faceEdges.Add(edgesList); } } } } return faceEdges; } /// <summary> /// Get normal of face /// </summary> /// <param name="face">edges in a face</param> /// <returns>vector stands for normal of the face</returns> public Vector4 GetFaceNormal(List<Edge> face) { Edge eg0 = face[0]; Edge eg1 = face[1]; //get two lines from the face List<XYZ> points = eg0.Tessellate() as List<XYZ>; Autodesk.Revit.DB.XYZ start = points[0]; Autodesk.Revit.DB.XYZ end = points[1]; Vector4 vStart = new Vector4((float)start.X, (float)start.Y, (float)start.Z); Vector4 vEnd = new Vector4((float)end.X, (float)end.Y, (float)end.Z); Vector4 vSub = vEnd - vStart; points = eg1.Tessellate() as List<XYZ>; start = points[0]; end = points[1]; vStart = new Vector4((float)start.X, (float)start.Y, (float)start.Z); vEnd = new Vector4((float)end.X, (float)end.Y, (float)end.Z); Vector4 vSub2 = vEnd - vStart; //get the normal with two lines got from face Vector4 result = vSub.CrossProduct(vSub2); result.Normalize(); return result; } /// <summary> /// Get a matrix which can move points to center /// </summary> /// <returns>matrix used to move point to center of graphics</returns> public Matrix4 ToCenterMatrix() { //translate the origin to bound center PointF[] bounds = GetFaceBounds(); PointF min = bounds[0]; PointF max = bounds[1]; PointF center = new PointF((min.X + max.X) / 2, (min.Y + max.Y) / 2); return new Matrix4(new Vector4(center.X, center.Y, 0)); } /// <summary> /// Get the bound of a face /// </summary> /// <returns>points array store the bound of the face</returns> public PointF[] GetFaceBounds() { Matrix4 matrix = m_to2DMatrix; Matrix4 inverseMatrix = matrix.Inverse(); float minX = 0, maxX = 0, minY = 0, maxY = 0; bool bFirstPoint = true; //get the max and min point on the face for (int i = 0; i < m_points.Count; i++) { List<XYZ> points = m_points[i]; foreach (Autodesk.Revit.DB.XYZ point in points) { Vector4 v = new Vector4(point); Vector4 v1 = inverseMatrix.Transform(v); if (bFirstPoint) { minX = maxX = v1.X; minY = maxY = v1.Y; bFirstPoint = false; } else { if (v1.X < minX) { minX = v1.X; } else if (v1.X > maxX) { maxX = v1.X; } if (v1.Y < minY) { minY = v1.Y; } else if (v1.Y > maxY) { maxY = v1.Y; } } } } //return an array with max and min value of face PointF[] resultPoints = new PointF[2] { new PointF(minX, minY), new PointF(maxX, maxY) }; return resultPoints; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Extensions.ObjectExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Online.Multiplayer; using osu.Game.Online.Multiplayer.MatchTypes.TeamVersus; using osu.Game.Rulesets.UI; using osu.Game.Screens.OnlinePlay.Multiplayer.Spectate; using osu.Game.Screens.Play; using osu.Game.Screens.Play.HUD; using osu.Game.Screens.Play.PlayerSettings; using osu.Game.Tests.Beatmaps.IO; using osu.Game.Users; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneMultiSpectatorScreen : MultiplayerTestScene { [Resolved] private OsuGameBase game { get; set; } [Resolved] private OsuConfigManager config { get; set; } [Resolved] private BeatmapManager beatmapManager { get; set; } private MultiSpectatorScreen spectatorScreen; private readonly List<MultiplayerRoomUser> playingUsers = new List<MultiplayerRoomUser>(); private BeatmapSetInfo importedSet; private BeatmapInfo importedBeatmap; private int importedBeatmapId; [BackgroundDependencyLoader] private void load() { importedSet = ImportBeatmapTest.LoadOszIntoOsu(game, virtualTrack: true).Result; importedBeatmap = importedSet.Beatmaps.First(b => b.RulesetID == 0); importedBeatmapId = importedBeatmap.OnlineBeatmapID ?? -1; } [SetUp] public new void Setup() => Schedule(() => playingUsers.Clear()); [Test] public void TestDelayedStart() { AddStep("start players silently", () => { OnlinePlayDependencies.Client.AddUser(new User { Id = PLAYER_1_ID }, true); OnlinePlayDependencies.Client.AddUser(new User { Id = PLAYER_2_ID }, true); playingUsers.Add(new MultiplayerRoomUser(PLAYER_1_ID)); playingUsers.Add(new MultiplayerRoomUser(PLAYER_2_ID)); }); loadSpectateScreen(false); AddWaitStep("wait a bit", 10); AddStep("load player first_player_id", () => SpectatorClient.StartPlay(PLAYER_1_ID, importedBeatmapId)); AddUntilStep("one player added", () => spectatorScreen.ChildrenOfType<Player>().Count() == 1); AddWaitStep("wait a bit", 10); AddStep("load player second_player_id", () => SpectatorClient.StartPlay(PLAYER_2_ID, importedBeatmapId)); AddUntilStep("two players added", () => spectatorScreen.ChildrenOfType<Player>().Count() == 2); } [Test] public void TestGeneral() { int[] userIds = getPlayerIds(4); start(userIds); loadSpectateScreen(); sendFrames(userIds, 1000); AddWaitStep("wait a bit", 20); } [Test] public void TestSpectatorPlayerInteractiveElementsHidden() { HUDVisibilityMode originalConfigValue = default; AddStep("get original config hud visibility", () => originalConfigValue = config.Get<HUDVisibilityMode>(OsuSetting.HUDVisibilityMode)); AddStep("set config hud visibility to always", () => config.SetValue(OsuSetting.HUDVisibilityMode, HUDVisibilityMode.Always)); start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(false); AddUntilStep("wait for player loaders", () => this.ChildrenOfType<PlayerLoader>().Count() == 2); AddAssert("all player loader settings hidden", () => this.ChildrenOfType<PlayerLoader>().All(l => !l.ChildrenOfType<FillFlowContainer<PlayerSettingsGroup>>().Any())); AddUntilStep("wait for players to load", () => spectatorScreen.AllPlayersLoaded); // components wrapped in skinnable target containers load asynchronously, potentially taking more than one frame to load. // therefore use until step rather than direct assert to account for that. AddUntilStep("all interactive elements removed", () => this.ChildrenOfType<Player>().All(p => !p.ChildrenOfType<PlayerSettingsOverlay>().Any() && !p.ChildrenOfType<HoldForMenuButton>().Any() && p.ChildrenOfType<SongProgressBar>().SingleOrDefault()?.ShowHandle == false)); AddStep("restore config hud visibility", () => config.SetValue(OsuSetting.HUDVisibilityMode, originalConfigValue)); } [Test] public void TestTeamDisplay() { AddStep("start players", () => { var player1 = OnlinePlayDependencies.Client.AddUser(new User { Id = PLAYER_1_ID }, true); player1.MatchState = new TeamVersusUserState { TeamID = 0, }; var player2 = OnlinePlayDependencies.Client.AddUser(new User { Id = PLAYER_2_ID }, true); player2.MatchState = new TeamVersusUserState { TeamID = 1, }; SpectatorClient.StartPlay(player1.UserID, importedBeatmapId); SpectatorClient.StartPlay(player2.UserID, importedBeatmapId); playingUsers.Add(player1); playingUsers.Add(player2); }); loadSpectateScreen(); sendFrames(PLAYER_1_ID, 1000); sendFrames(PLAYER_2_ID, 1000); AddWaitStep("wait a bit", 20); } [Test] public void TestTimeDoesNotProgressWhileAllPlayersPaused() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); sendFrames(PLAYER_1_ID, 40); sendFrames(PLAYER_2_ID, 20); checkPaused(PLAYER_2_ID, true); checkPausedInstant(PLAYER_1_ID, false); AddAssert("master clock still running", () => this.ChildrenOfType<MasterGameplayClockContainer>().Single().IsRunning); checkPaused(PLAYER_1_ID, true); AddUntilStep("master clock paused", () => !this.ChildrenOfType<MasterGameplayClockContainer>().Single().IsRunning); } [Test] public void TestPlayersMustStartSimultaneously() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); // Send frames for one player only, both should remain paused. sendFrames(PLAYER_1_ID, 20); checkPausedInstant(PLAYER_1_ID, true); checkPausedInstant(PLAYER_2_ID, true); // Send frames for the other player, both should now start playing. sendFrames(PLAYER_2_ID, 20); checkPausedInstant(PLAYER_1_ID, false); checkPausedInstant(PLAYER_2_ID, false); } [Test] public void TestPlayersDoNotStartSimultaneouslyIfBufferingForMaximumStartDelay() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); // Send frames for one player only, both should remain paused. sendFrames(PLAYER_1_ID, 1000); checkPausedInstant(PLAYER_1_ID, true); checkPausedInstant(PLAYER_2_ID, true); // Wait for the start delay seconds... AddWaitStep("wait maximum start delay seconds", (int)(CatchUpSyncManager.MAXIMUM_START_DELAY / TimePerAction)); // Player 1 should start playing by itself, player 2 should remain paused. checkPausedInstant(PLAYER_1_ID, false); checkPausedInstant(PLAYER_2_ID, true); } [Test] public void TestPlayersContinueWhileOthersBuffer() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); // Send initial frames for both players. A few more for player 1. sendFrames(PLAYER_1_ID, 20); sendFrames(PLAYER_2_ID); checkPausedInstant(PLAYER_1_ID, false); checkPausedInstant(PLAYER_2_ID, false); // Eventually player 2 will pause, player 1 must remain running. checkPaused(PLAYER_2_ID, true); checkPausedInstant(PLAYER_1_ID, false); // Eventually both players will run out of frames and should pause. checkPaused(PLAYER_1_ID, true); checkPausedInstant(PLAYER_2_ID, true); // Send more frames for the first player only. Player 1 should start playing with player 2 remaining paused. sendFrames(PLAYER_1_ID, 20); checkPausedInstant(PLAYER_2_ID, true); checkPausedInstant(PLAYER_1_ID, false); // Send more frames for the second player. Both should be playing sendFrames(PLAYER_2_ID, 20); checkPausedInstant(PLAYER_2_ID, false); checkPausedInstant(PLAYER_1_ID, false); } [Test] public void TestPlayersCatchUpAfterFallingBehind() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); // Send initial frames for both players. A few more for player 1. sendFrames(PLAYER_1_ID, 1000); sendFrames(PLAYER_2_ID, 30); checkPausedInstant(PLAYER_1_ID, false); checkPausedInstant(PLAYER_2_ID, false); // Eventually player 2 will run out of frames and should pause. checkPaused(PLAYER_2_ID, true); AddWaitStep("wait a few more frames", 10); // Send more frames for player 2. It should unpause. sendFrames(PLAYER_2_ID, 1000); checkPausedInstant(PLAYER_2_ID, false); // Player 2 should catch up to player 1 after unpausing. waitForCatchup(PLAYER_2_ID); AddWaitStep("wait a bit", 10); } [Test] public void TestMostInSyncUserIsAudioSource() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); loadSpectateScreen(); assertMuted(PLAYER_1_ID, true); assertMuted(PLAYER_2_ID, true); sendFrames(PLAYER_1_ID); sendFrames(PLAYER_2_ID, 20); checkPaused(PLAYER_1_ID, false); assertOneNotMuted(); checkPaused(PLAYER_1_ID, true); assertMuted(PLAYER_1_ID, true); assertMuted(PLAYER_2_ID, false); sendFrames(PLAYER_1_ID, 100); waitForCatchup(PLAYER_1_ID); checkPaused(PLAYER_2_ID, true); assertMuted(PLAYER_1_ID, false); assertMuted(PLAYER_2_ID, true); sendFrames(PLAYER_2_ID, 100); waitForCatchup(PLAYER_2_ID); assertMuted(PLAYER_1_ID, false); assertMuted(PLAYER_2_ID, true); } [Test] public void TestSpectatingDuringGameplay() { var players = new[] { PLAYER_1_ID, PLAYER_2_ID }; start(players); sendFrames(players, 300); loadSpectateScreen(); sendFrames(players, 300); AddUntilStep("playing from correct point in time", () => this.ChildrenOfType<DrawableRuleset>().All(r => r.FrameStableClock.CurrentTime > 30000)); } [Test] public void TestSpectatingDuringGameplayWithLateFrames() { start(new[] { PLAYER_1_ID, PLAYER_2_ID }); sendFrames(new[] { PLAYER_1_ID, PLAYER_2_ID }, 300); loadSpectateScreen(); sendFrames(PLAYER_1_ID, 300); AddWaitStep("wait maximum start delay seconds", (int)(CatchUpSyncManager.MAXIMUM_START_DELAY / TimePerAction)); checkPaused(PLAYER_1_ID, false); sendFrames(PLAYER_2_ID, 300); AddUntilStep("player 2 playing from correct point in time", () => getPlayer(PLAYER_2_ID).ChildrenOfType<DrawableRuleset>().Single().FrameStableClock.CurrentTime > 30000); } [Test] public void TestPlayersLeaveWhileSpectating() { start(getPlayerIds(4)); sendFrames(getPlayerIds(4), 300); loadSpectateScreen(); for (int count = 3; count >= 0; count--) { var id = PLAYER_1_ID + count; end(id); AddUntilStep($"{id} area grayed", () => getInstance(id).Colour != Color4.White); AddUntilStep($"{id} score quit set", () => getLeaderboardScore(id).HasQuit.Value); sendFrames(getPlayerIds(count), 300); } Player player = null; AddStep($"get {PLAYER_1_ID} player instance", () => player = getInstance(PLAYER_1_ID).ChildrenOfType<Player>().Single()); start(new[] { PLAYER_1_ID }); sendFrames(PLAYER_1_ID, 300); AddAssert($"{PLAYER_1_ID} player instance still same", () => getInstance(PLAYER_1_ID).ChildrenOfType<Player>().Single() == player); AddAssert($"{PLAYER_1_ID} area still grayed", () => getInstance(PLAYER_1_ID).Colour != Color4.White); AddAssert($"{PLAYER_1_ID} score quit still set", () => getLeaderboardScore(PLAYER_1_ID).HasQuit.Value); } private void loadSpectateScreen(bool waitForPlayerLoad = true) { AddStep("load screen", () => { Beatmap.Value = beatmapManager.GetWorkingBeatmap(importedBeatmap); Ruleset.Value = importedBeatmap.Ruleset; LoadScreen(spectatorScreen = new MultiSpectatorScreen(playingUsers.ToArray())); }); AddUntilStep("wait for screen load", () => spectatorScreen.LoadState == LoadState.Loaded && (!waitForPlayerLoad || spectatorScreen.AllPlayersLoaded)); } private void start(int[] userIds, int? beatmapId = null) { AddStep("start play", () => { foreach (int id in userIds) { var user = new MultiplayerRoomUser(id) { User = new User { Id = id }, }; OnlinePlayDependencies.Client.AddUser(user.User, true); SpectatorClient.StartPlay(id, beatmapId ?? importedBeatmapId); playingUsers.Add(user); } }); } private void end(int userId) { AddStep($"end play for {userId}", () => { var user = playingUsers.Single(u => u.UserID == userId); OnlinePlayDependencies.Client.RemoveUser(user.User.AsNonNull()); SpectatorClient.EndPlay(userId); playingUsers.Remove(user); }); } private void sendFrames(int userId, int count = 10) => sendFrames(new[] { userId }, count); private void sendFrames(int[] userIds, int count = 10) { AddStep("send frames", () => { foreach (int id in userIds) SpectatorClient.SendFrames(id, count); }); } private void checkPaused(int userId, bool state) => AddUntilStep($"{userId} is {(state ? "paused" : "playing")}", () => getPlayer(userId).ChildrenOfType<GameplayClockContainer>().First().GameplayClock.IsRunning != state); private void checkPausedInstant(int userId, bool state) { checkPaused(userId, state); // Todo: The following should work, but is broken because SpectatorScreen retrieves the WorkingBeatmap via the BeatmapManager, bypassing the test scene clock and running real-time. // AddAssert($"{userId} is {(state ? "paused" : "playing")}", () => getPlayer(userId).ChildrenOfType<GameplayClockContainer>().First().GameplayClock.IsRunning != state); } private void assertOneNotMuted() => AddAssert("one player not muted", () => spectatorScreen.ChildrenOfType<PlayerArea>().Count(p => !p.Mute) == 1); private void assertMuted(int userId, bool muted) => AddAssert($"{userId} {(muted ? "is" : "is not")} muted", () => getInstance(userId).Mute == muted); private void waitForCatchup(int userId) => AddUntilStep($"{userId} not catching up", () => !getInstance(userId).GameplayClock.IsCatchingUp); private Player getPlayer(int userId) => getInstance(userId).ChildrenOfType<Player>().Single(); private PlayerArea getInstance(int userId) => spectatorScreen.ChildrenOfType<PlayerArea>().Single(p => p.UserId == userId); private GameplayLeaderboardScore getLeaderboardScore(int userId) => spectatorScreen.ChildrenOfType<GameplayLeaderboardScore>().Single(s => s.User?.Id == userId); private int[] getPlayerIds(int count) => Enumerable.Range(PLAYER_1_ID, count).ToArray(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Transport.Channels { using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; /// <summary> /// A list of {@link ChannelHandler}s which handles or intercepts inbound events and outbound operations of a /// {@link Channel}. {@link ChannelPipeline} implements an advanced form of the /// <a href="http://www.oracle.com/technetwork/java/interceptingfilter-142169.html">Intercepting Filter</a> pattern /// to give a user full control over how an event is handled and how the {@link ChannelHandler}s in a pipeline /// interact with each other. /// /// <h3>Creation of a pipeline</h3> /// /// Each channel has its own pipeline and it is created automatically when a new channel is created. /// /// <h3>How an event flows in a pipeline</h3> /// /// The following diagram describes how I/O events are processed by {@link ChannelHandler}s in a {@link ChannelPipeline} /// typically. An I/O event is handled by a {@link ChannelHandler} and is forwarded by the {@link ChannelHandler} which /// handled the event to the {@link ChannelHandler} which is placed right next to it. A {@link ChannelHandler} can also /// trigger an arbitrary I/O event if necessary. To forward or trigger an event, a {@link ChannelHandler} calls the /// event propagation methods defined in {@link ChannelHandlerContext}, such as /// {@link ChannelHandlerContext#fireChannelRead(Object)} and {@link ChannelHandlerContext#write(Object)}. /// <pre> /// I/O Request /// via {@link Channel} or /// {@link ChannelHandlerContext} /// | /// +---------------------------------------------------+---------------+ /// | ChannelPipeline | | /// | \|/ | /// | +----------------------------------------------+----------+ | /// | | ChannelHandler N | | /// | +----------+-----------------------------------+----------+ | /// | /|\ | | /// | | \|/ | /// | +----------+-----------------------------------+----------+ | /// | | ChannelHandler N-1 | | /// | +----------+-----------------------------------+----------+ | /// | /|\ . | /// | . . | /// | ChannelHandlerContext.fireIN_EVT() ChannelHandlerContext.OUT_EVT()| /// | [method call] [method call] | /// | . . | /// | . \|/ | /// | +----------+-----------------------------------+----------+ | /// | | ChannelHandler 2 | | /// | +----------+-----------------------------------+----------+ | /// | /|\ | | /// | | \|/ | /// | +----------+-----------------------------------+----------+ | /// | | ChannelHandler 1 | | /// | +----------+-----------------------------------+----------+ | /// | /|\ | | /// +---------------+-----------------------------------+---------------+ /// | \|/ /// +---------------+-----------------------------------+---------------+ /// | | | | /// | [ Socket.read() ] [ Socket.write() ] | /// | | /// | Netty Internal I/O Threads (Transport Implementation) | /// +-------------------------------------------------------------------+ /// </pre> /// An inbound event is handled by the {@link ChannelHandler}s in the bottom-up direction as shown on the left side of /// the diagram. An inbound event is usually triggered by the I/O thread on the bottom of the diagram so that the /// {@link ChannelHandler}s are notified when the state of a {@link Channel} changes (e.g. newly established connections /// and closed connections) or the inbound data was read from a remote peer. If an inbound event goes beyond the /// {@link ChannelHandler} at the top of the diagram, it is discarded and logged, depending on your loglevel. /// /// <p> /// An outbound event is handled by the {@link ChannelHandler}s in the top-down direction as shown on the right side of /// the diagram. An outbound event is usually triggered by your code that requests an outbound I/O operation, such as /// a write request and a connection attempt. If an outbound event goes beyond the {@link ChannelHandler} at the /// bottom of the diagram, it is handled by an I/O thread associated with the {@link Channel}. The I/O thread often /// performs the actual output operation such as {@link SocketChannel#write(ByteBuffer)}. /// <p> /// /// <h3>Forwarding an event to the next handler</h3> /// /// As explained briefly above, a {@link ChannelHandler} has to invoke the event propagation methods in /// {@link ChannelHandlerContext} to forward an event to its next handler. Those methods include: /// <ul> /// <li>Inbound event propagation methods: /// <ul> /// <li>{@link ChannelHandlerContext#fireChannelRegistered()}</li> /// <li>{@link ChannelHandlerContext#fireChannelActive()}</li> /// <li>{@link ChannelHandlerContext#fireChannelRead(Object)}</li> /// <li>{@link ChannelHandlerContext#fireChannelReadComplete()}</li> /// <li>{@link ChannelHandlerContext#fireExceptionCaught(Throwable)}</li> /// <li>{@link ChannelHandlerContext#fireUserEventTriggered(Object)}</li> /// <li>{@link ChannelHandlerContext#fireChannelWritabilityChanged()}</li> /// <li>{@link ChannelHandlerContext#fireChannelInactive()}</li> /// </ul> /// </li> /// <li>Outbound event propagation methods: /// <ul> /// <li>{@link ChannelHandlerContext#bind(SocketAddress, ChannelPromise)}</li> /// <li>{@link ChannelHandlerContext#connect(SocketAddress, SocketAddress, ChannelPromise)}</li> /// <li>{@link ChannelHandlerContext#write(Object, ChannelPromise)}</li> /// <li>{@link ChannelHandlerContext#flush()}</li> /// <li>{@link ChannelHandlerContext#read()}</li> /// <li>{@link ChannelHandlerContext#disconnect(ChannelPromise)}</li> /// <li>{@link ChannelHandlerContext#close(ChannelPromise)}</li> /// </ul> /// </li> /// </ul> /// /// and the following example shows how the event propagation is usually done: /// /// <pre> /// public class MyInboundHandler extends {@link ChannelHandlerAdapter} { /// {@code } /// public void channelActive({@link ChannelHandlerContext} ctx) { /// System.out.println("Connected!"); /// ctx.fireChannelActive(); /// } /// } /// /// public clas MyOutboundHandler extends {@link ChannelHandlerAdapter} { /// {@code } /// public void close({@link ChannelHandlerContext} ctx, {@link ChannelPromise} promise) { /// System.out.println("Closing .."); /// ctx.close(promise); /// } /// } /// </pre> /// /// <h3>Building a pipeline</h3> /// <p> /// A user is supposed to have one or more {@link ChannelHandler}s in a pipeline to receive I/O events (e.g. read) and /// to request I/O operations (e.g. write and close). For example, a typical server will have the following handlers /// in each channel's pipeline, but your mileage may vary depending on the complexity and characteristics of the /// protocol and business logic: /// /// <ol> /// <li>Protocol Decoder - translates binary data (e.g. {@link ByteBuf}) into a Java object.</li> /// <li>Protocol Encoder - translates a Java object into binary data.</li> /// <li>Business Logic Handler - performs the actual business logic (e.g. database access).</li> /// </ol> /// /// and it could be represented as shown in the following example: /// /// <pre> /// static final {@link EventExecutorGroup} group = new {@link DefaultEventExecutorGroup}(16); /// ... /// /// {@link ChannelPipeline} pipeline = ch.pipeline(); /// /// pipeline.addLast("decoder", new MyProtocolDecoder()); /// pipeline.addLast("encoder", new MyProtocolEncoder()); /// /// // Tell the pipeline to run MyBusinessLogicHandler's event handler methods /// // in a different thread than an I/O thread so that the I/O thread is not blocked by /// // a time-consuming task. /// // If your business logic is fully asynchronous or finished very quickly, you don't /// // need to specify a group. /// pipeline.addLast(group, "handler", new MyBusinessLogicHandler()); /// </pre> /// /// <h3>Thread safety</h3> /// <p> /// A {@link ChannelHandler} can be added or removed at any time because a {@link ChannelPipeline} is thread safe. /// For example, you can insert an encryption handler when sensitive information is about to be exchanged, and remove it /// after the exchange. /// </summary> public interface IChannelPipeline : IEnumerable<IChannelHandler> { /// <summary> /// Inserts a {@link ChannelHandler} at the first position of this pipeline. /// </summary> /// /// @param name the name of the handler to insert first. {@code null} to let the name auto-generated. /// @param handler the handler to insert first /// /// @throws IllegalArgumentException /// if there's an entry with the same name already in the pipeline /// @throws NullPointerException /// if the specified handler is {@code null} IChannelPipeline AddFirst(string name, IChannelHandler handler); /// <summary> /// Inserts a {@link ChannelHandler} at the first position of this pipeline. /// </summary> /// <param name="invoker">the {@link ChannelHandlerInvoker} which invokes the {@code handler}s event handler methods</param> /// <param name="name">the name of the handler to insert first. <code>null</code> to let the name auto-generated.</param> /// <param name="handler">the handler to insert first</param> /// <exception cref="ArgumentException">if there's an entry with the same name already in the pipeline</exception> /// <exception cref="ArgumentNullException">if the specified handler is <code>null</code></exception> IChannelPipeline AddFirst(IChannelHandlerInvoker invoker, string name, IChannelHandler handler); /// <summary> /// Appends a {@link ChannelHandler} at the last position of this pipeline. /// /// @param name the name of the handler to append. {@code null} to let the name auto-generated. /// @param handler the handler to append /// /// @throws IllegalArgumentException /// if there's an entry with the same name already in the pipeline /// @throws NullPointerException /// if the specified handler is {@code null} /// </summary> IChannelPipeline AddLast(string name, IChannelHandler handler); /// <summary> /// Appends a {@link ChannelHandler} at the last position of this pipeline. /// </summary> /// <param name="invoker">the {@link ChannelHandlerInvoker} which invokes the {@code handler}s event handler methods</param> /// <param name="name">the name of the handler to append. {@code null} to let the name auto-generated.</param> /// <param name="handler">the handler to append</param> /// <exception cref="ArgumentException">if there's an entry with the same name already in the pipeline</exception> /// <exception cref="ArgumentNullException">if the specified handler is <code>null</code></exception> IChannelPipeline AddLast(IChannelHandlerInvoker invoker, string name, IChannelHandler handler); /// <summary> /// Inserts a {@link ChannelHandler} before an existing handler of this pipeline. /// </summary> /// <param name="baseName">the name of the existing handler</param> /// <param name="name">the name of the handler to insert before. {@code null} to let the name auto-generated.</param> /// <param name="handler">the handler to insert before</param> /// @throws NoSuchElementException /// if there's no such entry with the specified {@code baseName} /// @throws IllegalArgumentException /// if there's an entry with the same name already in the pipeline /// @throws NullPointerException /// if the specified baseName or handler is {@code null} IChannelPipeline AddBefore(string baseName, string name, IChannelHandler handler); /// <summary> /// Inserts a {@link ChannelHandler} before an existing handler of this pipeline. /// </summary> /// <param name="invoker">the {@link ChannelHandlerInvoker} which invokes the {@code handler}s event handler methods</param> /// <param name="baseName">the name of the existing handler</param> /// <param name="name">the name of the handler to insert before. {@code null} to let the name auto-generated.</param> /// <param name="handler">the handler to insert before</param> /// @throws NoSuchElementException /// if there's no such entry with the specified {@code baseName} /// @throws IllegalArgumentException /// if there's an entry with the same name already in the pipeline /// @throws NullPointerException /// if the specified baseName or handler is {@code null} IChannelPipeline AddBefore(IChannelHandlerInvoker invoker, string baseName, string name, IChannelHandler handler); /// <summary> /// Inserts a {@link ChannelHandler} after an existing handler of this pipeline. /// </summary> /// <param name="baseName">the name of the existing handler</param> /// <param name="name">the name of the handler to insert after. {@code null} to let the name auto-generated.</param> /// <param name="handler">the handler to insert after</param> /// @throws NoSuchElementException /// if there's no such entry with the specified {@code baseName} /// @throws IllegalArgumentException /// if there's an entry with the same name already in the pipeline /// @throws NullPointerException /// if the specified baseName or handler is {@code null} IChannelPipeline AddAfter(string baseName, string name, IChannelHandler handler); /// <summary> /// Inserts a {@link ChannelHandler} after an existing handler of this pipeline. /// </summary> /// <param name="invoker">the {@link ChannelHandlerInvoker} which invokes the {@code handler}s event handler methods</param> /// <param name="baseName">the name of the existing handler</param> /// <param name="name">the name of the handler to insert after. {@code null} to let the name auto-generated.</param> /// <param name="handler">the handler to insert after</param> /// @throws NoSuchElementException /// if there's no such entry with the specified {@code baseName} /// @throws IllegalArgumentException /// if there's an entry with the same name already in the pipeline /// @throws NullPointerException /// if the specified baseName or handler is {@code null} IChannelPipeline AddAfter(IChannelHandlerInvoker invoker, string baseName, string name, IChannelHandler handler); /// <summary> /// Inserts a {@link ChannelHandler}s at the first position of this pipeline. /// /// @param handlers the handlers to insert first /// /// </summary> IChannelPipeline AddFirst(params IChannelHandler[] handlers); /// <summary> /// Inserts a {@link ChannelHandler}s at the first position of this pipeline. /// /// @param invoker the {@link ChannelHandlerInvoker} which invokes the {@code handler}s event handler methods /// @param handlers the handlers to insert first /// /// </summary> IChannelPipeline AddFirst(IChannelHandlerInvoker invoker, params IChannelHandler[] handlers); /// <summary> /// Inserts a {@link ChannelHandler}s at the last position of this pipeline. /// /// @param handlers the handlers to insert last /// /// </summary> IChannelPipeline AddLast(params IChannelHandler[] handlers); /// <summary> /// Inserts a {@link ChannelHandler}s at the last position of this pipeline. /// /// @param invoker the {@link ChannelHandlerInvoker} which invokes the {@code handler}s event handler methods /// @param handlers the handlers to insert last /// /// </summary> IChannelPipeline AddLast(IChannelHandlerInvoker invoker, params IChannelHandler[] handlers); /// <summary> /// Removes the specified {@link ChannelHandler} from this pipeline. /// /// @param handler the {@link ChannelHandler} to remove /// /// @throws NoSuchElementException /// if there's no such handler in this pipeline /// @throws NullPointerException /// if the specified handler is {@code null} /// </summary> IChannelPipeline Remove(IChannelHandler handler); /// <summary> /// Removes the {@link ChannelHandler} with the specified name from this pipeline. /// </summary> /// <param name="name">the name under which the {@link ChannelHandler} was stored.</param> /// <returns>the removed handler</returns> /// /// <exception cref="ArgumentException">if there's no such handler with the specified name in this pipeline</exception> /// <exception cref="ArgumentNullException">if the specified name is {@code null}</exception> IChannelHandler Remove(string name); /// <summary> /// Removes the {@link ChannelHandler} of the specified type from this pipeline. /// /// @param <T> the type of the handler /// @param handlerType the type of the handler /// /// @return the removed handler /// /// @throws NoSuchElementException /// if there's no such handler of the specified type in this pipeline /// @throws NullPointerException /// if the specified handler type is {@code null} /// </summary> T Remove<T>() where T : class, IChannelHandler; /// <summary> /// Removes the first {@link ChannelHandler} in this pipeline. /// /// @return the removed handler /// /// @throws NoSuchElementException /// if this pipeline is empty /// </summary> IChannelHandler RemoveFirst(); /// <summary> /// Removes the last {@link ChannelHandler} in this pipeline. /// /// @return the removed handler /// /// @throws NoSuchElementException /// if this pipeline is empty /// </summary> IChannelHandler RemoveLast(); /// <summary> /// Replaces the specified {@link ChannelHandler} with a new handler in this pipeline. /// /// @param oldHandler the {@link ChannelHandler} to be replaced /// @param newName the name under which the replacement should be added. /// {@code null} to use the same name with the handler being replaced. /// @param newHandler the {@link ChannelHandler} which is used as replacement /// /// @return itself /// @throws NoSuchElementException /// if the specified old handler does not exist in this pipeline /// @throws IllegalArgumentException /// if a handler with the specified new name already exists in this /// pipeline, except for the handler to be replaced /// @throws NullPointerException /// if the specified old handler or new handler is {@code null} /// </summary> IChannelPipeline Replace(IChannelHandler oldHandler, string newName, IChannelHandler newHandler); /// Replaces the {@link ChannelHandler} of the specified name with a new handler in this pipeline. /// @param oldName the name of the {@link ChannelHandler} to be replaced /// @param newName the name under which the replacement should be added. /// {@code null} to use the same name with the handler being replaced. /// @param newHandler the {@link ChannelHandler} which is used as replacement /// @return the removed handler /// @throws NoSuchElementException /// if the handler with the specified old name does not exist in this pipeline /// @throws IllegalArgumentException /// if a handler with the specified new name already exists in this /// pipeline, except for the handler to be replaced /// @throws NullPointerException /// if the specified old handler or new handler is {@code null} IChannelHandler Replace(string oldName, string newName, IChannelHandler newHandler); /// <summary> /// Replaces the {@link ChannelHandler} of the specified type with a new handler in this pipeline. /// /// @param oldHandlerType the type of the handler to be removed /// @param newName the name under which the replacement should be added. /// {@code null} to use the same name with the handler being replaced. /// @param newHandler the {@link ChannelHandler} which is used as replacement /// /// @return the removed handler /// /// @throws NoSuchElementException /// if the handler of the specified old handler type does not exist /// in this pipeline /// @throws IllegalArgumentException /// if a handler with the specified new name already exists in this /// pipeline, except for the handler to be replaced /// @throws NullPointerException /// if the specified old handler or new handler is {@code null} /// </summary> T Replace<T>(string newName, IChannelHandler newHandler) where T : class, IChannelHandler; /// <summary> /// Returns the first {@link ChannelHandler} in this pipeline. /// /// @return the first handler. {@code null} if this pipeline is empty. /// </summary> IChannelHandler First(); /// <summary> /// Returns the context of the first {@link ChannelHandler} in this pipeline. /// /// @return the context of the first handler. {@code null} if this pipeline is empty. /// </summary> IChannelHandlerContext FirstContext(); /// <summary> /// Returns the last {@link ChannelHandler} in this pipeline. /// /// @return the last handler. {@code null} if this pipeline is empty. /// </summary> IChannelHandler Last(); /// <summary> /// Returns the context of the last {@link ChannelHandler} in this pipeline. /// /// @return the context of the last handler. {@code null} if this pipeline is empty. /// </summary> IChannelHandlerContext LastContext(); /// <summary>Returns the {@link ChannelHandler} with the specified name in this pipeline.</summary> /// <returns>the handler with the specified name. {@code null} if there's no such handler in this pipeline.</returns> IChannelHandler Get(string name); /// <summary> /// Returns the {@link ChannelHandler} of the specified type in this /// pipeline. /// /// @return the handler of the specified handler type. /// {@code null} if there's no such handler in this pipeline. /// </summary> T Get<T>() where T : class, IChannelHandler; /// <summary> /// Returns the context object of the specified {@link ChannelHandler} in /// this pipeline. /// /// @return the context object of the specified handler. /// {@code null} if there's no such handler in this pipeline. /// </summary> IChannelHandlerContext Context(IChannelHandler handler); /// <summary>Returns the context object of the {@link ChannelHandler} with the specified name in this pipeline.</summary> /// <returns>the context object of the handler with the specified name. {@code null} if there's no such handler in this pipeline.</returns> IChannelHandlerContext Context(string name); /// <summary> /// Returns the context object of the {@link ChannelHandler} of the /// specified type in this pipeline. /// /// @return the context object of the handler of the specified type. /// {@code null} if there's no such handler in this pipeline. /// </summary> IChannelHandlerContext Context<T>() where T : class, IChannelHandler; /// <summary> /// Returns the {@link Channel} that this pipeline is attached to. /// /// @return the channel. {@code null} if this pipeline is not attached yet. /// </summary> IChannel Channel(); /// <summary> /// A {@link Channel} is active now, which means it is connected. /// /// This will result in having the {@link ChannelHandler#channelActive(ChannelHandlerContext)} method /// called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> /// <summary> /// A {@link Channel} was registered to its {@link EventLoop}. /// /// This will result in having the {@link ChannelHandler#channelRegistered(ChannelHandlerContext)} method /// called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> IChannelPipeline FireChannelRegistered(); /// <summary> /// A {@link Channel} was unregistered from its {@link EventLoop}. /// /// This will result in having the {@link ChannelHandler#channelUnregistered(ChannelHandlerContext)} method /// called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> IChannelPipeline FireChannelUnregistered(); /// <summary> /// A {@link Channel} is active now, which means it is connected. /// /// This will result in having the {@link ChannelHandler#channelActive(ChannelHandlerContext)} method /// called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> IChannelPipeline FireChannelActive(); /// <summary> /// A {@link Channel} is inactive now, which means it is closed. /// /// This will result in having the {@link ChannelHandler#channelInactive(ChannelHandlerContext)} method /// called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> IChannelPipeline FireChannelInactive(); /// <summary> /// A {@link Channel} received an {@link Throwable} in one of its inbound operations. /// /// This will result in having the {@link ChannelHandler#exceptionCaught(ChannelHandlerContext, Throwable)} /// method called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> IChannelPipeline FireExceptionCaught(Exception cause); /// <summary> /// A {@link Channel} received an user defined event. /// /// This will result in having the {@link ChannelHandler#userEventTriggered(ChannelHandlerContext, Object)} /// method called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> IChannelPipeline FireUserEventTriggered(object evt); /// <summary> /// A {@link Channel} received a message. /// /// This will result in having the {@link ChannelHandler#channelRead(ChannelHandlerContext, Object)} /// method called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> IChannelPipeline FireChannelRead(object msg); IChannelPipeline FireChannelReadComplete(); /// <summary> /// Triggers an {@link ChannelHandler#channelWritabilityChanged(ChannelHandlerContext)} /// event to the next {@link ChannelHandler} in the {@link ChannelPipeline}. /// </summary> IChannelPipeline FireChannelWritabilityChanged(); /// <summary> /// Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation /// completes, either because the operation was successful or because of an error. /// /// The given {@link ChannelPromise} will be notified. /// <p> /// This will result in having the /// {@link ChannelHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method /// called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> Task BindAsync(EndPoint localAddress); /// <summary> /// Request to connect to the given {@link EndPoint} and notify the {@link Task} once the operation /// completes, either because the operation was successful or because of an error. /// /// The given {@link Task} will be notified. /// /// <p> /// If the connection fails because of a connection timeout, the {@link Task} will get failed with /// a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} /// will be used. /// <p> /// This will result in having the /// {@link ChannelHandler#connect(ChannelHandlerContext, EndPoint, EndPoint, ChannelPromise)} /// method called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> Task ConnectAsync(EndPoint remoteAddress); /// <summary> /// Request to connect to the given {@link EndPoint} while bind to the localAddress and notify the /// {@link Task} once the operation completes, either because the operation was successful or because of /// an error. /// /// The given {@link ChannelPromise} will be notified and also returned. /// <p> /// This will result in having the /// {@link ChannelHandler#connect(ChannelHandlerContext, EndPoint, EndPoint, ChannelPromise)} /// method called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> Task ConnectAsync(EndPoint remoteAddress, EndPoint localAddress); /// <summary> /// Request to disconnect from the remote peer and notify the {@link Task} once the operation completes, /// either because the operation was successful or because of an error. /// /// The given {@link ChannelPromise} will be notified. /// <p> /// This will result in having the /// {@link ChannelHandler#disconnect(ChannelHandlerContext, ChannelPromise)} /// method called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> Task DisconnectAsync(); /// <summary> /// Request to close the {@link Channel} and notify the {@link ChannelFuture} once the operation completes, /// either because the operation was successful or because of /// an error. /// /// After it is closed it is not possible to reuse it again. /// <p> /// This will result in having the /// {@link ChannelHandler#close(ChannelHandlerContext, ChannelPromise)} /// method called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> Task CloseAsync(); /// <summary> /// Request to deregister the {@link Channel} bound this {@link ChannelPipeline} from the previous assigned /// {@link EventExecutor} and notify the {@link ChannelFuture} once the operation completes, either because the /// operation was successful or because of an error. /// /// The given {@link ChannelPromise} will be notified. /// <p>ChannelOutboundHandler /// This will result in having the /// {@link ChannelHandler#deregister(ChannelHandlerContext, ChannelPromise)} /// method called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> Task DeregisterAsync(); /// <summary> /// Request to Read data from the {@link Channel} into the first inbound buffer, triggers an /// {@link ChannelHandler#channelRead(ChannelHandlerContext, Object)} event if data was /// read, and triggers a /// {@link ChannelHandler#channelReadComplete(ChannelHandlerContext) channelReadComplete} event so the /// handler can decide to continue reading. If there's a pending read operation already, this method does nothing. /// <p> /// This will result in having the /// {@link ChannelHandler#read(ChannelHandlerContext)} /// method called of the next {@link ChannelHandler} contained in the {@link ChannelPipeline} of the /// {@link Channel}. /// </summary> IChannelPipeline Read(); /// <summary> /// Request to write a message via this {@link ChannelPipeline}. /// This method will not request to actual flush, so be sure to call {@link #flush()} /// once you want to request to flush all pending data to the actual transport. /// </summary> Task WriteAsync(object msg); /// <summary> /// Request to flush all pending messages. /// </summary> IChannelPipeline Flush(); /// <summary> /// Shortcut for call {@link #write(Object)} and {@link #flush()}. /// </summary> Task WriteAndFlushAsync(object msg); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using Xunit; namespace System.IO.Tests { public class Directory_CreateDirectory : FileSystemTest { public static TheoryData ReservedDeviceNames = IOInputs.GetReservedDeviceNames().ToTheoryData(); #region Utilities public virtual DirectoryInfo Create(string path) { return Directory.CreateDirectory(path); } #endregion #region UniversalTests [Fact] public void NullAsPath_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => Create(null)); } [Fact] public void EmptyAsPath_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Create(string.Empty)); } [Theory, MemberData(nameof(PathsWithInvalidCharacters))] public void PathWithInvalidCharactersAsPath_ThrowsArgumentException(string invalidPath) { if (invalidPath.Equals(@"\\?\") && !PathFeatures.IsUsingLegacyPathNormalization()) AssertExtensions.ThrowsAny<IOException, UnauthorizedAccessException>(() => Create(invalidPath)); else if (invalidPath.Contains(@"\\?\") && !PathFeatures.IsUsingLegacyPathNormalization()) Assert.Throws<DirectoryNotFoundException>(() => Create(invalidPath)); else Assert.Throws<ArgumentException>(() => Create(invalidPath)); } [Fact] public void PathAlreadyExistsAsFile() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.Throws<IOException>(() => Create(path)); Assert.Throws<IOException>(() => Create(IOServices.AddTrailingSlashIfNeeded(path))); Assert.Throws<IOException>(() => Create(IOServices.RemoveTrailingSlash(path))); } [Theory] [InlineData(FileAttributes.Hidden)] [InlineData(FileAttributes.ReadOnly)] [InlineData(FileAttributes.Normal)] public void PathAlreadyExistsAsDirectory(FileAttributes attributes) { DirectoryInfo testDir = Create(GetTestFilePath()); FileAttributes original = testDir.Attributes; try { testDir.Attributes = attributes; Assert.Equal(testDir.FullName, Create(testDir.FullName).FullName); } finally { testDir.Attributes = original; } } [Fact] public void RootPath() { string dirName = Path.GetPathRoot(Directory.GetCurrentDirectory()); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void DotIsCurrentDirectory() { string path = GetTestFilePath(); DirectoryInfo result = Create(Path.Combine(path, ".")); Assert.Equal(IOServices.RemoveTrailingSlash(path), result.FullName); result = Create(Path.Combine(path, ".") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(path), result.FullName); } [Fact] public void CreateCurrentDirectory() { DirectoryInfo result = Create(Directory.GetCurrentDirectory()); Assert.Equal(Directory.GetCurrentDirectory(), result.FullName); } [Fact] public void DotDotIsParentDirectory() { DirectoryInfo result = Create(Path.Combine(GetTestFilePath(), "..")); Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName); result = Create(Path.Combine(GetTestFilePath(), "..") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName); } [Theory, MemberData(nameof(ValidPathComponentNames))] public void ValidPathWithTrailingSlash(string component) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string path = IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component)); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(result.Exists); } [ConditionalTheory(nameof(UsingNewNormalization)), MemberData(nameof(ValidPathComponentNames))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // trailing slash public void ValidExtendedPathWithTrailingSlash(string component) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string path = IOInputs.ExtendedPrefix + IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component)); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(result.Exists); } [Theory, MemberData(nameof(ValidPathComponentNames))] public void ValidPathWithoutTrailingSlash(string component) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); string path = testDir.FullName + Path.DirectorySeparatorChar + component; DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Fact] public void ValidPathWithMultipleSubdirectories() { string dirName = Path.Combine(GetTestFilePath(), "Test", "Test", "Test"); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void AllowedSymbols() { string dirName = Path.Combine(TestDirectory, Path.GetRandomFileName() + "!@#$%^&"); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void DirectoryEqualToMaxDirectory_CanBeCreatedAllAtOnce() { DirectoryInfo testDir = Create(GetTestFilePath()); string path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Theory, MemberData(nameof(PathsWithComponentLongerThanMaxComponent))] [ActiveIssue("https://github.com/dotnet/corefx/issues/8655")] public void DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsException(string path) { // While paths themselves can be up to 260 characters including trailing null, file systems // limit each components of the path to a total of 255 characters on Desktop. if (PlatformDetection.IsFullFramework) { Assert.Throws<PathTooLongException>(() => Create(path)); } else { AssertExtensions.ThrowsAny<IOException, DirectoryNotFoundException>(() => Create(path)); } } #endregion #region PlatformSpecific [Theory, MemberData(nameof(PathsWithInvalidColons))] [PlatformSpecific(TestPlatforms.Windows)] // invalid colons throws ArgumentException [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Versions of netfx older than 4.6.2 throw an ArgumentException instead of NotSupportedException. Until all of our machines run netfx against the actual latest version, these will fail.")] public void PathWithInvalidColons_ThrowsNotSupportedException(string invalidPath) { Assert.Throws<NotSupportedException>(() => Create(invalidPath)); } [ConditionalFact(nameof(AreAllLongPathsAvailable))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // long directory path succeeds public void DirectoryLongerThanMaxPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath()); Assert.All(paths, (path) => { DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // long directory path throws PathTooLongException public void DirectoryLongerThanMaxLongPath_ThrowsPathTooLongException() { var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath()); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } [ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] public void DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsException() { var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath(), useExtendedSyntax: true); // Long directory path with extended syntax throws PathTooLongException on Desktop. // Everywhere else, it may be either PathTooLongException or DirectoryNotFoundException if (PlatformDetection.IsFullFramework) { Assert.All(paths, path => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } else { Assert.All(paths, path => { AssertExtensions .ThrowsAny<PathTooLongException, DirectoryNotFoundException>( () => Create(path)); }); } } [ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // long directory path with extended syntax succeeds public void ExtendedDirectoryLongerThanLegacyMaxPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath(), useExtendedSyntax: true); Assert.All(paths, (path) => { Assert.True(Create(path).Exists); }); } [ConditionalFact(nameof(AreAllLongPathsAvailable))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // long directory path succeeds public void DirectoryLongerThanMaxDirectoryAsPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath()); Assert.All(paths, (path) => { var result = Create(path); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // long directory path allowed public void UnixPathLongerThan256_Allowed() { DirectoryInfo testDir = Create(GetTestFilePath()); string path = IOServices.GetPath(testDir.FullName, 257); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // deeply nested directories allowed public void UnixPathWithDeeplyNestedDirectories() { DirectoryInfo parent = Create(GetTestFilePath()); for (int i = 1; i <= 100; i++) // 100 == arbitrarily large number of directories { parent = Create(Path.Combine(parent.FullName, "dir" + i)); Assert.True(Directory.Exists(parent.FullName)); } } [Theory, MemberData(nameof(WhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] // whitespace as path throws ArgumentException on Windows public void WindowsWhiteSpaceAsPath_ThrowsArgumentException(string path) { Assert.Throws<ArgumentException>(() => Create(path)); } [Theory, MemberData(nameof(WhiteSpace))] [PlatformSpecific(TestPlatforms.AnyUnix)] // whitespace as path allowed public void UnixWhiteSpaceAsPath_Allowed(string path) { Create(Path.Combine(TestDirectory, path)); Assert.True(Directory.Exists(Path.Combine(TestDirectory, path))); } [Theory, MemberData(nameof(ControlWhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] // trailing whitespace in path is removed on Windows [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] // e.g. NetFX only public void TrailingWhiteSpace_Trimmed(string component) { // On desktop, we trim a number of whitespace characters DirectoryInfo testDir = Create(GetTestFilePath()); string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component; DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); } [Theory, MemberData(nameof(NonControlWhiteSpace))] [PlatformSpecific(TestPlatforms.Windows)] // trailing whitespace in path is removed on Windows [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // Not NetFX public void TrailingWhiteSpace_NotTrimmed(string component) { // In CoreFX we don't trim anything other than space (' ') DirectoryInfo testDir = Create(GetTestFilePath() + component); string path = IOServices.RemoveTrailingSlash(testDir.FullName); DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); } [Theory, MemberData(nameof(SimpleWhiteSpace))] //*Just Spaces* [PlatformSpecific(TestPlatforms.Windows)] // trailing whitespace in path is removed on Windows [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // Not NetFX public void TrailingSpace_NotTrimmed(string component) { DirectoryInfo testDir = Create(GetTestFilePath()); string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component; DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); } [ConditionalTheory(nameof(UsingNewNormalization)), MemberData(nameof(SimpleWhiteSpace))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // extended syntax with whitespace public void WindowsExtendedSyntaxWhiteSpace(string path) { string extendedPath = Path.Combine(IOInputs.ExtendedPrefix + TestDirectory, path); Directory.CreateDirectory(extendedPath); Assert.True(Directory.Exists(extendedPath), extendedPath); } [Theory, MemberData(nameof(WhiteSpace))] [PlatformSpecific(TestPlatforms.AnyUnix)] // trailing whitespace in path treated as significant on Unix public void UnixNonSignificantTrailingWhiteSpace(string component) { // Unix treats trailing/prename whitespace as significant and a part of the name. DirectoryInfo testDir = Create(GetTestFilePath()); string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component; DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); } [Theory, MemberData(nameof(PathsWithAlternativeDataStreams))] [PlatformSpecific(TestPlatforms.Windows)] // alternate data streams public void PathWithAlternateDataStreams_ThrowsNotSupportedException(string path) { Assert.Throws<NotSupportedException>(() => Create(path)); } [Theory, MemberData(nameof(PathsWithReservedDeviceNames))] [PlatformSpecific(TestPlatforms.Windows)] // device name prefixes public void PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException(string path) { // Throws DirectoryNotFoundException, when the behavior really should be an invalid path Assert.Throws<DirectoryNotFoundException>(() => Create(path)); } [ConditionalTheory(nameof(UsingNewNormalization)), MemberData(nameof(ReservedDeviceNames))] [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] [PlatformSpecific(TestPlatforms.Windows)] // device name prefixes public void PathWithReservedDeviceNameAsExtendedPath(string path) { Assert.True(Create(IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, path)).Exists, path); } [Theory, MemberData(nameof(UncPathsWithoutShareName))] [PlatformSpecific(TestPlatforms.Windows)] // UNC shares public void UncPathWithoutShareNameAsPath_ThrowsArgumentException(string path) { Assert.Throws<ArgumentException>(() => Create(path)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // UNC shares public void UNCPathWithOnlySlashes() { Assert.Throws<ArgumentException>(() => Create("//")); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // drive labels [ActiveIssue(20117, TargetFrameworkMonikers.Uap)] public void CDriveCase() { DirectoryInfo dir = Create("c:\\"); DirectoryInfo dir2 = Create("C:\\"); Assert.NotEqual(dir.FullName, dir2.FullName); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // drive letters public void DriveLetter_Windows() { // On Windows, DirectoryInfo will replace "<DriveLetter>:" with "." var driveLetter = Create(Directory.GetCurrentDirectory()[0] + ":"); var current = Create("."); Assert.Equal(current.Name, driveLetter.Name); Assert.Equal(current.FullName, driveLetter.FullName); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // drive letters casing public void DriveLetter_Unix() { // On Unix, there's no special casing for drive letters. These may or may not be valid names, depending // on the file system underlying the current directory. Unix file systems typically allow these, but, // for example, these names are not allowed if running on a file system mounted from a Windows machine. DirectoryInfo driveLetter; try { driveLetter = Create("C:"); } catch (IOException) { return; } var current = Create("."); Assert.Equal("C:", driveLetter.Name); Assert.Equal(Path.Combine(current.FullName, "C:"), driveLetter.FullName); try { // If this test is inherited then it's possible this call will fail due to the "C:" directory // being deleted in that other test before this call. What we care about testing (proper path // handling) is unaffected by this race condition. Directory.Delete("C:"); } catch (DirectoryNotFoundException) { } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // testing drive labels public void NonExistentDriveAsPath_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => { Create(IOServices.GetNonExistentDrive()); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // testing drive labels public void SubdirectoryOnNonExistentDriveAsPath_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => { Create(Path.Combine(IOServices.GetNonExistentDrive(), "Subdirectory")); }); } [Fact] [ActiveIssue(1221)] [PlatformSpecific(TestPlatforms.Windows)] // testing drive labels public void NotReadyDriveAsPath_ThrowsDirectoryNotFoundException() { // Behavior is suspect, should really have thrown IOException similar to the SubDirectory case var drive = IOServices.GetNotReadyDrive(); if (drive == null) { Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted."); return; } Assert.Throws<DirectoryNotFoundException>(() => { Create(drive); }); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // testing drive labels [ActiveIssue(1221)] public void SubdirectoryOnNotReadyDriveAsPath_ThrowsIOException() { var drive = IOServices.GetNotReadyDrive(); if (drive == null) { Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted."); return; } // 'Device is not ready' Assert.Throws<IOException>(() => { Create(Path.Combine(drive, "Subdirectory")); }); } #if !TEST_WINRT // Cannot set current directory to root from appcontainer with it's default ACL /* [Fact] public void DotDotAsPath_WhenCurrentDirectoryIsRoot_DoesNotThrow() { string root = Path.GetPathRoot(Directory.GetCurrentDirectory()); using (CurrentDirectoryContext context = new CurrentDirectoryContext(root)) { DirectoryInfo result = Create(".."); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(root, result.FullName); } } */ #endif #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// MemberResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.IpMessaging.V2.Service.Channel { public class MemberResource : Resource { public sealed class WebhookEnabledTypeEnum : StringEnum { private WebhookEnabledTypeEnum(string value) : base(value) {} public WebhookEnabledTypeEnum() {} public static implicit operator WebhookEnabledTypeEnum(string value) { return new WebhookEnabledTypeEnum(value); } public static readonly WebhookEnabledTypeEnum True = new WebhookEnabledTypeEnum("true"); public static readonly WebhookEnabledTypeEnum False = new WebhookEnabledTypeEnum("false"); } private static Request BuildFetchRequest(FetchMemberOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.IpMessaging, "/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Fetch(FetchMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> FetchAsync(FetchMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Fetch(string pathServiceSid, string pathChannelSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchMemberOptions(pathServiceSid, pathChannelSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> FetchAsync(string pathServiceSid, string pathChannelSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchMemberOptions(pathServiceSid, pathChannelSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildCreateRequest(CreateMemberOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.IpMessaging, "/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members", postParams: options.GetParams(), headerParams: options.GetHeaderParams() ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Create(CreateMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> CreateAsync(CreateMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="identity"> The identity </param> /// <param name="roleSid"> The role_sid </param> /// <param name="lastConsumedMessageIndex"> The last_consumed_message_index </param> /// <param name="lastConsumptionTimestamp"> The last_consumption_timestamp </param> /// <param name="dateCreated"> The date_created </param> /// <param name="dateUpdated"> The date_updated </param> /// <param name="attributes"> The attributes </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Create(string pathServiceSid, string pathChannelSid, string identity, string roleSid = null, int? lastConsumedMessageIndex = null, DateTime? lastConsumptionTimestamp = null, DateTime? dateCreated = null, DateTime? dateUpdated = null, string attributes = null, MemberResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new CreateMemberOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid, LastConsumedMessageIndex = lastConsumedMessageIndex, LastConsumptionTimestamp = lastConsumptionTimestamp, DateCreated = dateCreated, DateUpdated = dateUpdated, Attributes = attributes, XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="identity"> The identity </param> /// <param name="roleSid"> The role_sid </param> /// <param name="lastConsumedMessageIndex"> The last_consumed_message_index </param> /// <param name="lastConsumptionTimestamp"> The last_consumption_timestamp </param> /// <param name="dateCreated"> The date_created </param> /// <param name="dateUpdated"> The date_updated </param> /// <param name="attributes"> The attributes </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> CreateAsync(string pathServiceSid, string pathChannelSid, string identity, string roleSid = null, int? lastConsumedMessageIndex = null, DateTime? lastConsumptionTimestamp = null, DateTime? dateCreated = null, DateTime? dateUpdated = null, string attributes = null, MemberResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new CreateMemberOptions(pathServiceSid, pathChannelSid, identity){RoleSid = roleSid, LastConsumedMessageIndex = lastConsumedMessageIndex, LastConsumptionTimestamp = lastConsumptionTimestamp, DateCreated = dateCreated, DateUpdated = dateUpdated, Attributes = attributes, XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadMemberOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.IpMessaging, "/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static ResourceSet<MemberResource> Read(ReadMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<MemberResource>.FromJson("members", response.Content); return new ResourceSet<MemberResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<ResourceSet<MemberResource>> ReadAsync(ReadMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<MemberResource>.FromJson("members", response.Content); return new ResourceSet<MemberResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="identity"> The identity </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static ResourceSet<MemberResource> Read(string pathServiceSid, string pathChannelSid, List<string> identity = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadMemberOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="identity"> The identity </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<ResourceSet<MemberResource>> ReadAsync(string pathServiceSid, string pathChannelSid, List<string> identity = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadMemberOptions(pathServiceSid, pathChannelSid){Identity = identity, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<MemberResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<MemberResource>.FromJson("members", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<MemberResource> NextPage(Page<MemberResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.IpMessaging) ); var response = client.Request(request); return Page<MemberResource>.FromJson("members", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<MemberResource> PreviousPage(Page<MemberResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.IpMessaging) ); var response = client.Request(request); return Page<MemberResource>.FromJson("members", response.Content); } private static Request BuildDeleteRequest(DeleteMemberOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.IpMessaging, "/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: options.GetHeaderParams() ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static bool Delete(DeleteMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static bool Delete(string pathServiceSid, string pathChannelSid, string pathSid, MemberResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new DeleteMemberOptions(pathServiceSid, pathChannelSid, pathSid){XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathChannelSid, string pathSid, MemberResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new DeleteMemberOptions(pathServiceSid, pathChannelSid, pathSid){XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return await DeleteAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateMemberOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.IpMessaging, "/v2/Services/" + options.PathServiceSid + "/Channels/" + options.PathChannelSid + "/Members/" + options.PathSid + "", postParams: options.GetParams(), headerParams: options.GetHeaderParams() ); } /// <summary> /// update /// </summary> /// <param name="options"> Update Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Update(UpdateMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update Member parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> UpdateAsync(UpdateMemberOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="roleSid"> The role_sid </param> /// <param name="lastConsumedMessageIndex"> The last_consumed_message_index </param> /// <param name="lastConsumptionTimestamp"> The last_consumption_timestamp </param> /// <param name="dateCreated"> The date_created </param> /// <param name="dateUpdated"> The date_updated </param> /// <param name="attributes"> The attributes </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Member </returns> public static MemberResource Update(string pathServiceSid, string pathChannelSid, string pathSid, string roleSid = null, int? lastConsumedMessageIndex = null, DateTime? lastConsumptionTimestamp = null, DateTime? dateCreated = null, DateTime? dateUpdated = null, string attributes = null, MemberResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new UpdateMemberOptions(pathServiceSid, pathChannelSid, pathSid){RoleSid = roleSid, LastConsumedMessageIndex = lastConsumedMessageIndex, LastConsumptionTimestamp = lastConsumptionTimestamp, DateCreated = dateCreated, DateUpdated = dateUpdated, Attributes = attributes, XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathChannelSid"> The channel_sid </param> /// <param name="pathSid"> The sid </param> /// <param name="roleSid"> The role_sid </param> /// <param name="lastConsumedMessageIndex"> The last_consumed_message_index </param> /// <param name="lastConsumptionTimestamp"> The last_consumption_timestamp </param> /// <param name="dateCreated"> The date_created </param> /// <param name="dateUpdated"> The date_updated </param> /// <param name="attributes"> The attributes </param> /// <param name="xTwilioWebhookEnabled"> The X-Twilio-Webhook-Enabled HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Member </returns> public static async System.Threading.Tasks.Task<MemberResource> UpdateAsync(string pathServiceSid, string pathChannelSid, string pathSid, string roleSid = null, int? lastConsumedMessageIndex = null, DateTime? lastConsumptionTimestamp = null, DateTime? dateCreated = null, DateTime? dateUpdated = null, string attributes = null, MemberResource.WebhookEnabledTypeEnum xTwilioWebhookEnabled = null, ITwilioRestClient client = null) { var options = new UpdateMemberOptions(pathServiceSid, pathChannelSid, pathSid){RoleSid = roleSid, LastConsumedMessageIndex = lastConsumedMessageIndex, LastConsumptionTimestamp = lastConsumptionTimestamp, DateCreated = dateCreated, DateUpdated = dateUpdated, Attributes = attributes, XTwilioWebhookEnabled = xTwilioWebhookEnabled}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a MemberResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> MemberResource object represented by the provided JSON </returns> public static MemberResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<MemberResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The sid /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The account_sid /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The channel_sid /// </summary> [JsonProperty("channel_sid")] public string ChannelSid { get; private set; } /// <summary> /// The service_sid /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The identity /// </summary> [JsonProperty("identity")] public string Identity { get; private set; } /// <summary> /// The date_created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The date_updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The role_sid /// </summary> [JsonProperty("role_sid")] public string RoleSid { get; private set; } /// <summary> /// The last_consumed_message_index /// </summary> [JsonProperty("last_consumed_message_index")] public int? LastConsumedMessageIndex { get; private set; } /// <summary> /// The last_consumption_timestamp /// </summary> [JsonProperty("last_consumption_timestamp")] public DateTime? LastConsumptionTimestamp { get; private set; } /// <summary> /// The url /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The attributes /// </summary> [JsonProperty("attributes")] public string Attributes { get; private set; } private MemberResource() { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Build.Utilities { public partial class AssemblyFoldersFromConfigInfo { public AssemblyFoldersFromConfigInfo(string directoryPath, System.Version targetFrameworkVersion) { } public string DirectoryPath { get { throw null; } } public System.Version TargetFrameworkVersion { get { throw null; } } } public partial class CommandLineBuilder { public CommandLineBuilder() { } public CommandLineBuilder(bool quoteHyphensOnCommandLine) { } public CommandLineBuilder(bool quoteHyphensOnCommandLine, bool useNewLineSeparator) { } protected System.Text.StringBuilder CommandLine { get { throw null; } } public int Length { get { throw null; } } public void AppendFileNameIfNotNull(Microsoft.Build.Framework.ITaskItem fileItem) { } public void AppendFileNameIfNotNull(string fileName) { } public void AppendFileNamesIfNotNull(Microsoft.Build.Framework.ITaskItem[] fileItems, string delimiter) { } public void AppendFileNamesIfNotNull(string[] fileNames, string delimiter) { } protected void AppendFileNameWithQuoting(string fileName) { } protected void AppendQuotedTextToBuffer(System.Text.StringBuilder buffer, string unquotedTextToAppend) { } protected void AppendSpaceIfNotEmpty() { } public void AppendSwitch(string switchName) { } public void AppendSwitchIfNotNull(string switchName, Microsoft.Build.Framework.ITaskItem parameter) { } public void AppendSwitchIfNotNull(string switchName, Microsoft.Build.Framework.ITaskItem[] parameters, string delimiter) { } public void AppendSwitchIfNotNull(string switchName, string parameter) { } public void AppendSwitchIfNotNull(string switchName, string[] parameters, string delimiter) { } public void AppendSwitchUnquotedIfNotNull(string switchName, Microsoft.Build.Framework.ITaskItem parameter) { } public void AppendSwitchUnquotedIfNotNull(string switchName, Microsoft.Build.Framework.ITaskItem[] parameters, string delimiter) { } public void AppendSwitchUnquotedIfNotNull(string switchName, string parameter) { } public void AppendSwitchUnquotedIfNotNull(string switchName, string[] parameters, string delimiter) { } public void AppendTextUnquoted(string textToAppend) { } protected void AppendTextWithQuoting(string textToAppend) { } protected virtual bool IsQuotingRequired(string parameter) { throw null; } public override string ToString() { throw null; } protected virtual void VerifyThrowNoEmbeddedDoubleQuotes(string switchName, string parameter) { } } public enum DotNetFrameworkArchitecture { Bitness32 = 1, Bitness64 = 2, Current = 0, } public enum HostObjectInitializationStatus { NoActionReturnFailure = 3, NoActionReturnSuccess = 2, UseAlternateToolToExecute = 1, UseHostObjectToExecute = 0, } public abstract partial class Logger : Microsoft.Build.Framework.ILogger { protected Logger() { } public virtual string Parameters { get { throw null; } set { } } public virtual Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } set { } } public virtual string FormatErrorEvent(Microsoft.Build.Framework.BuildErrorEventArgs args) { throw null; } public virtual string FormatWarningEvent(Microsoft.Build.Framework.BuildWarningEventArgs args) { throw null; } public abstract void Initialize(Microsoft.Build.Framework.IEventSource eventSource); public bool IsVerbosityAtLeast(Microsoft.Build.Framework.LoggerVerbosity checkVerbosity) { throw null; } public virtual void Shutdown() { } } public enum MultipleVersionSupport { Allow = 0, Error = 2, Warning = 1, } public partial class MuxLogger : Microsoft.Build.Framework.ILogger, Microsoft.Build.Framework.INodeLogger { public MuxLogger() { } public bool IncludeEvaluationMetaprojects { get { throw null; } set { } } public bool IncludeEvaluationProfiles { get { throw null; } set { } } public bool IncludeTaskInputs { get { throw null; } set { } } public string Parameters { get { throw null; } set { } } public Microsoft.Build.Framework.LoggerVerbosity Verbosity { get { throw null; } set { } } public void Initialize(Microsoft.Build.Framework.IEventSource eventSource) { } public void Initialize(Microsoft.Build.Framework.IEventSource eventSource, int maxNodeCount) { } public void RegisterLogger(int submissionId, Microsoft.Build.Framework.ILogger logger) { } public void Shutdown() { } public bool UnregisterLoggers(int submissionId) { throw null; } } public static partial class ProcessorArchitecture { public const string AMD64 = "AMD64"; public const string ARM = "ARM"; public const string ARM64 = "ARM64"; public const string IA64 = "IA64"; public const string MSIL = "MSIL"; public const string X86 = "x86"; public static string CurrentProcessArchitecture { get { throw null; } } } public partial class SDKManifest { public SDKManifest(string pathToSdk) { } public System.Collections.Generic.IDictionary<string, string> AppxLocations { get { throw null; } } public string CopyRedistToSubDirectory { get { throw null; } } public string DependsOnSDK { get { throw null; } } public string DisplayName { get { throw null; } } public System.Collections.Generic.IDictionary<string, string> FrameworkIdentities { get { throw null; } } public string FrameworkIdentity { get { throw null; } } public string MaxOSVersionTested { get { throw null; } } public string MaxPlatformVersion { get { throw null; } } public string MinOSVersion { get { throw null; } } public string MinVSVersion { get { throw null; } } public string MoreInfo { get { throw null; } } public string PlatformIdentity { get { throw null; } } public string ProductFamilyName { get { throw null; } } public bool ReadError { get { throw null; } } public string ReadErrorMessage { get { throw null; } } public Microsoft.Build.Utilities.SDKType SDKType { get { throw null; } } public string SupportedArchitectures { get { throw null; } } public string SupportPrefer32Bit { get { throw null; } } public Microsoft.Build.Utilities.MultipleVersionSupport SupportsMultipleVersions { get { throw null; } } public string TargetPlatform { get { throw null; } } public string TargetPlatformMinVersion { get { throw null; } } public string TargetPlatformVersion { get { throw null; } } public static partial class Attributes { public const string APPX = "APPX"; public const string AppxLocation = "AppxLocation"; public const string CopyLocalExpandedReferenceAssemblies = "CopyLocalExpandedReferenceAssemblies"; public const string CopyRedist = "CopyRedist"; public const string CopyRedistToSubDirectory = "CopyRedistToSubDirectory"; public const string DependsOnSDK = "DependsOn"; public const string DisplayName = "DisplayName"; public const string ExpandReferenceAssemblies = "ExpandReferenceAssemblies"; public const string FrameworkIdentity = "FrameworkIdentity"; public const string MaxOSVersionTested = "MaxOSVersionTested"; public const string MaxPlatformVersion = "MaxPlatformVersion"; public const string MinOSVersion = "MinOSVersion"; public const string MinVSVersion = "MinVSVersion"; public const string MoreInfo = "MoreInfo"; public const string PlatformIdentity = "PlatformIdentity"; public const string ProductFamilyName = "ProductFamilyName"; public const string SDKType = "SDKType"; public const string SupportedArchitectures = "SupportedArchitectures"; public const string SupportPrefer32Bit = "SupportPrefer32Bit"; public const string SupportsMultipleVersions = "SupportsMultipleVersions"; public const string TargetedSDK = "TargetedSDKArchitecture"; public const string TargetedSDKConfiguration = "TargetedSDKConfiguration"; public const string TargetPlatform = "TargetPlatform"; public const string TargetPlatformMinVersion = "TargetPlatformMinVersion"; public const string TargetPlatformVersion = "TargetPlatformVersion"; } } public enum SDKType { External = 1, Framework = 3, Platform = 2, Unspecified = 0, } public enum TargetDotNetFrameworkVersion { Latest = 9999, Version11 = 0, Version20 = 1, Version30 = 2, Version35 = 3, Version40 = 4, Version45 = 5, Version451 = 6, Version452 = 9, Version46 = 7, Version461 = 8, Version462 = 10, Version47 = 11, Version471 = 12, Version472 = 13, Version48 = 14, VersionLatest = 10, } public partial class TargetPlatformSDK : System.IEquatable<Microsoft.Build.Utilities.TargetPlatformSDK> { public TargetPlatformSDK(string targetPlatformIdentifier, System.Version targetPlatformVersion, string path) { } public string DisplayName { get { throw null; } } public System.Version MinOSVersion { get { throw null; } } public System.Version MinVSVersion { get { throw null; } } public string Path { get { throw null; } set { } } public string TargetPlatformIdentifier { get { throw null; } } public System.Version TargetPlatformVersion { get { throw null; } } public bool ContainsPlatform(string targetPlatformIdentifier, string targetPlatformVersion) { throw null; } public bool Equals(Microsoft.Build.Utilities.TargetPlatformSDK other) { throw null; } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } } public abstract partial class Task : Microsoft.Build.Framework.ITask { protected Task() { } protected Task(System.Resources.ResourceManager taskResources) { } protected Task(System.Resources.ResourceManager taskResources, string helpKeywordPrefix) { } public Microsoft.Build.Framework.IBuildEngine BuildEngine { get { throw null; } set { } } public Microsoft.Build.Framework.IBuildEngine2 BuildEngine2 { get { throw null; } } public Microsoft.Build.Framework.IBuildEngine3 BuildEngine3 { get { throw null; } } public Microsoft.Build.Framework.IBuildEngine4 BuildEngine4 { get { throw null; } } public Microsoft.Build.Framework.IBuildEngine5 BuildEngine5 { get { throw null; } } public Microsoft.Build.Framework.IBuildEngine6 BuildEngine6 { get { throw null; } } protected string HelpKeywordPrefix { get { throw null; } set { } } public Microsoft.Build.Framework.ITaskHost HostObject { get { throw null; } set { } } public Microsoft.Build.Utilities.TaskLoggingHelper Log { get { throw null; } } protected System.Resources.ResourceManager TaskResources { get { throw null; } set { } } public abstract bool Execute(); } public sealed partial class TaskItem : Microsoft.Build.Framework.ITaskItem, Microsoft.Build.Framework.ITaskItem2 { public TaskItem() { } public TaskItem(Microsoft.Build.Framework.ITaskItem sourceItem) { } public TaskItem(string itemSpec) { } public TaskItem(string itemSpec, System.Collections.IDictionary itemMetadata) { } public string ItemSpec { get { throw null; } set { } } public int MetadataCount { get { throw null; } } public System.Collections.ICollection MetadataNames { get { throw null; } } string Microsoft.Build.Framework.ITaskItem2.EvaluatedIncludeEscaped { get { throw null; } set { } } public System.Collections.IDictionary CloneCustomMetadata() { throw null; } public void CopyMetadataTo(Microsoft.Build.Framework.ITaskItem destinationItem) { } public string GetMetadata(string metadataName) { throw null; } System.Collections.IDictionary Microsoft.Build.Framework.ITaskItem2.CloneCustomMetadataEscaped() { throw null; } string Microsoft.Build.Framework.ITaskItem2.GetMetadataValueEscaped(string metadataName) { throw null; } void Microsoft.Build.Framework.ITaskItem2.SetMetadataValueLiteral(string metadataName, string metadataValue) { } public static explicit operator string (Microsoft.Build.Utilities.TaskItem taskItemToCast) { throw null; } public void RemoveMetadata(string metadataName) { } public void SetMetadata(string metadataName, string metadataValue) { } public override string ToString() { throw null; } } public partial class TaskLoggingHelper { public TaskLoggingHelper(Microsoft.Build.Framework.IBuildEngine buildEngine, string taskName) { } public TaskLoggingHelper(Microsoft.Build.Framework.ITask taskInstance) { } protected Microsoft.Build.Framework.IBuildEngine BuildEngine { get { throw null; } } public bool HasLoggedErrors { get { throw null; } } public string HelpKeywordPrefix { get { throw null; } set { } } protected string TaskName { get { throw null; } } public System.Resources.ResourceManager TaskResources { get { throw null; } set { } } public string ExtractMessageCode(string message, out string messageWithoutCodePrefix) { messageWithoutCodePrefix = default(string); throw null; } public virtual string FormatResourceString(string resourceName, params object[] args) { throw null; } public virtual string FormatString(string unformatted, params object[] args) { throw null; } public virtual string GetResourceMessage(string resourceName) { throw null; } public void LogCommandLine(Microsoft.Build.Framework.MessageImportance importance, string commandLine) { } public void LogCommandLine(string commandLine) { } public void LogCriticalMessage(string subcategory, string code, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, params object[] messageArgs) { } public void LogError(string message, params object[] messageArgs) { } public void LogError(string subcategory, string errorCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, params object[] messageArgs) { } public void LogErrorFromException(System.Exception exception) { } public void LogErrorFromException(System.Exception exception, bool showStackTrace) { } public void LogErrorFromException(System.Exception exception, bool showStackTrace, bool showDetail, string file) { } public void LogErrorFromResources(string messageResourceName, params object[] messageArgs) { } public void LogErrorFromResources(string subcategoryResourceName, string errorCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { } public void LogErrorWithCodeFromResources(string messageResourceName, params object[] messageArgs) { } public void LogErrorWithCodeFromResources(string subcategoryResourceName, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { } public void LogExternalProjectFinished(string message, string helpKeyword, string projectFile, bool succeeded) { } public void LogExternalProjectStarted(string message, string helpKeyword, string projectFile, string targetNames) { } public void LogMessage(Microsoft.Build.Framework.MessageImportance importance, string message, params object[] messageArgs) { } public void LogMessage(string message, params object[] messageArgs) { } public void LogMessage(string subcategory, string code, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, Microsoft.Build.Framework.MessageImportance importance, string message, params object[] messageArgs) { } public void LogMessageFromResources(Microsoft.Build.Framework.MessageImportance importance, string messageResourceName, params object[] messageArgs) { } public void LogMessageFromResources(string messageResourceName, params object[] messageArgs) { } public bool LogMessageFromText(string lineOfText, Microsoft.Build.Framework.MessageImportance messageImportance) { throw null; } public bool LogMessagesFromFile(string fileName) { throw null; } public bool LogMessagesFromFile(string fileName, Microsoft.Build.Framework.MessageImportance messageImportance) { throw null; } public bool LogMessagesFromStream(System.IO.TextReader stream, Microsoft.Build.Framework.MessageImportance messageImportance) { throw null; } public void LogTelemetry(string eventName, System.Collections.Generic.IDictionary<string, string> properties) { } public void LogWarning(string message, params object[] messageArgs) { } public void LogWarning(string subcategory, string warningCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string message, params object[] messageArgs) { } public void LogWarningFromException(System.Exception exception) { } public void LogWarningFromException(System.Exception exception, bool showStackTrace) { } public void LogWarningFromResources(string messageResourceName, params object[] messageArgs) { } public void LogWarningFromResources(string subcategoryResourceName, string warningCode, string helpKeyword, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { } public void LogWarningWithCodeFromResources(string messageResourceName, params object[] messageArgs) { } public void LogWarningWithCodeFromResources(string subcategoryResourceName, string file, int lineNumber, int columnNumber, int endLineNumber, int endColumnNumber, string messageResourceName, params object[] messageArgs) { } } public static partial class ToolLocationHelper { public static string CurrentToolsVersion { get { throw null; } } public static string PathToSystem { get { throw null; } } public static void ClearSDKStaticCache() { } public static System.Collections.Generic.IDictionary<string, string> FilterPlatformExtensionSDKs(System.Version targetPlatformVersion, System.Collections.Generic.IDictionary<string, string> extensionSdks) { throw null; } public static System.Collections.Generic.IList<Microsoft.Build.Utilities.TargetPlatformSDK> FilterTargetPlatformSdks(System.Collections.Generic.IList<Microsoft.Build.Utilities.TargetPlatformSDK> targetPlatformSdkList, System.Version osVersion, System.Version vsVersion) { throw null; } public static string FindRootFolderWhereAllFilesExist(string possibleRoots, string relativeFilePaths) { throw null; } public static System.Collections.Generic.IList<Microsoft.Build.Utilities.AssemblyFoldersFromConfigInfo> GetAssemblyFoldersFromConfigInfo(string configFile, string targetFrameworkVersion, System.Reflection.ProcessorArchitecture targetProcessorArchitecture) { throw null; } public static string GetDisplayNameForTargetFrameworkDirectory(string targetFrameworkDirectory, System.Runtime.Versioning.FrameworkName frameworkName) { throw null; } public static string GetDotNetFrameworkRootRegistryKey(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; } public static string GetDotNetFrameworkSdkInstallKeyValue(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; } public static string GetDotNetFrameworkSdkInstallKeyValue(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; } public static string GetDotNetFrameworkSdkRootRegistryKey(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; } public static string GetDotNetFrameworkSdkRootRegistryKey(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; } public static string GetDotNetFrameworkVersionFolderPrefix(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; } public static System.Collections.Generic.IEnumerable<string> GetFoldersInVSInstalls(System.Version minVersion=null, System.Version maxVersion=null, string subFolder=null) { throw null; } public static string GetFoldersInVSInstallsAsString(string minVersionString=null, string maxVersionString=null, string subFolder=null) { throw null; } public static string GetLatestSDKTargetPlatformVersion(string sdkIdentifier, string sdkVersion) { throw null; } public static string GetLatestSDKTargetPlatformVersion(string sdkIdentifier, string sdkVersion, string[] sdkRoots) { throw null; } public static string GetPathToBuildTools(string toolsVersion) { throw null; } public static string GetPathToBuildTools(string toolsVersion, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; } public static string GetPathToBuildToolsFile(string fileName, string toolsVersion) { throw null; } public static string GetPathToBuildToolsFile(string fileName, string toolsVersion, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; } public static string GetPathToDotNetFramework(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; } public static string GetPathToDotNetFramework(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; } public static string GetPathToDotNetFrameworkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; } public static string GetPathToDotNetFrameworkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; } public static string GetPathToDotNetFrameworkReferenceAssemblies(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; } public static string GetPathToDotNetFrameworkSdk() { throw null; } public static string GetPathToDotNetFrameworkSdk(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; } public static string GetPathToDotNetFrameworkSdk(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; } public static string GetPathToDotNetFrameworkSdkFile(string fileName) { throw null; } public static string GetPathToDotNetFrameworkSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version) { throw null; } public static string GetPathToDotNetFrameworkSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; } public static string GetPathToDotNetFrameworkSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; } public static string GetPathToDotNetFrameworkSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; } public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(System.Runtime.Versioning.FrameworkName frameworkName) { throw null; } public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(string targetFrameworkRootPath, System.Runtime.Versioning.FrameworkName frameworkName) { throw null; } public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(string targetFrameworkRootPath, string targetFrameworkFallbackSearchPaths, System.Runtime.Versioning.FrameworkName frameworkName) { throw null; } public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile) { throw null; } public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string targetFrameworkRootPath) { throw null; } public static System.Collections.Generic.IList<string> GetPathToReferenceAssemblies(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string targetFrameworkRootPath, string targetFrameworkFallbackSearchPaths) { throw null; } public static string GetPathToStandardLibraries(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile) { throw null; } public static string GetPathToStandardLibraries(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string platformTarget) { throw null; } public static string GetPathToStandardLibraries(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string platformTarget, string targetFrameworkRootPath) { throw null; } public static string GetPathToStandardLibraries(string targetFrameworkIdentifier, string targetFrameworkVersion, string targetFrameworkProfile, string platformTarget, string targetFrameworkRootPath, string targetFrameworkFallbackSearchPaths) { throw null; } public static string GetPathToSystemFile(string fileName) { throw null; } [System.ObsoleteAttribute("Consider using GetPlatformSDKLocation instead")] public static string GetPathToWindowsSdk(Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; } [System.ObsoleteAttribute("Consider using GetPlatformSDKLocationFile instead")] public static string GetPathToWindowsSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion) { throw null; } [System.ObsoleteAttribute("Consider using GetPlatformSDKLocationFile instead")] public static string GetPathToWindowsSdkFile(string fileName, Microsoft.Build.Utilities.TargetDotNetFrameworkVersion version, Microsoft.Build.Utilities.VisualStudioVersion visualStudioVersion, Microsoft.Build.Utilities.DotNetFrameworkArchitecture architecture) { throw null; } public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, string targetPlatformVersion) { throw null; } public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, string targetPlatformVersion, string diskRoots, string registryRoot) { throw null; } public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, string targetPlatformVersion, string diskRoots, string extensionDiskRoots, string registryRoot) { throw null; } public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; } public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, System.Version targetPlatformVersion, string[] diskRoots, string registryRoot) { throw null; } public static string GetPlatformExtensionSDKLocation(string sdkMoniker, string targetPlatformIdentifier, System.Version targetPlatformVersion, string[] diskRoots, string[] extensionDiskRoots, string registryRoot) { throw null; } public static System.Collections.Generic.IDictionary<string, string> GetPlatformExtensionSDKLocations(string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; } public static System.Collections.Generic.IDictionary<string, string> GetPlatformExtensionSDKLocations(string[] diskRoots, string registryRoot, string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; } public static System.Collections.Generic.IDictionary<string, string> GetPlatformExtensionSDKLocations(string[] diskRoots, string[] extensionDiskRoots, string registryRoot, string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; } public static System.Collections.Generic.IDictionary<string, System.Tuple<string, string>> GetPlatformExtensionSDKLocationsAndVersions(string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; } public static System.Collections.Generic.IDictionary<string, System.Tuple<string, string>> GetPlatformExtensionSDKLocationsAndVersions(string[] diskRoots, string registryRoot, string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; } public static System.Collections.Generic.IDictionary<string, System.Tuple<string, string>> GetPlatformExtensionSDKLocationsAndVersions(string[] diskRoots, string[] multiPlatformDiskRoots, string registryRoot, string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; } public static string[] GetPlatformOrFrameworkExtensionSdkReferences(string extensionSdkMoniker, string targetSdkIdentifier, string targetSdkVersion, string diskRoots, string extensionDiskRoots, string registryRoot) { throw null; } public static string[] GetPlatformOrFrameworkExtensionSdkReferences(string extensionSdkMoniker, string targetSdkIdentifier, string targetSdkVersion, string diskRoots, string extensionDiskRoots, string registryRoot, string targetPlatformIdentifier, string targetPlatformVersion) { throw null; } public static string GetPlatformSDKDisplayName(string targetPlatformIdentifier, string targetPlatformVersion) { throw null; } public static string GetPlatformSDKDisplayName(string targetPlatformIdentifier, string targetPlatformVersion, string diskRoots, string registryRoot) { throw null; } public static string GetPlatformSDKLocation(string targetPlatformIdentifier, string targetPlatformVersion) { throw null; } public static string GetPlatformSDKLocation(string targetPlatformIdentifier, string targetPlatformVersion, string diskRoots, string registryRoot) { throw null; } public static string GetPlatformSDKLocation(string targetPlatformIdentifier, System.Version targetPlatformVersion) { throw null; } public static string GetPlatformSDKLocation(string targetPlatformIdentifier, System.Version targetPlatformVersion, string[] diskRoots, string registryRoot) { throw null; } public static string GetPlatformSDKPropsFileLocation(string sdkIdentifier, string sdkVersion, string targetPlatformIdentifier, string targetPlatformMinVersion, string targetPlatformVersion) { throw null; } public static string GetPlatformSDKPropsFileLocation(string sdkIdentifier, string sdkVersion, string targetPlatformIdentifier, string targetPlatformMinVersion, string targetPlatformVersion, string diskRoots, string registryRoot) { throw null; } public static System.Collections.Generic.IEnumerable<string> GetPlatformsForSDK(string sdkIdentifier, System.Version sdkVersion) { throw null; } public static System.Collections.Generic.IEnumerable<string> GetPlatformsForSDK(string sdkIdentifier, System.Version sdkVersion, string[] diskRoots, string registryRoot) { throw null; } public static string GetProgramFilesReferenceAssemblyRoot() { throw null; } public static string GetSDKContentFolderPath(string sdkIdentifier, string sdkVersion, string targetPlatformIdentifier, string targetPlatformMinVersion, string targetPlatformVersion, string folderName, string diskRoot=null) { throw null; } public static System.Collections.Generic.IList<string> GetSDKDesignTimeFolders(string sdkRoot) { throw null; } public static System.Collections.Generic.IList<string> GetSDKDesignTimeFolders(string sdkRoot, string targetConfiguration, string targetArchitecture) { throw null; } public static System.Collections.Generic.IList<string> GetSDKRedistFolders(string sdkRoot) { throw null; } public static System.Collections.Generic.IList<string> GetSDKRedistFolders(string sdkRoot, string targetConfiguration, string targetArchitecture) { throw null; } public static System.Collections.Generic.IList<string> GetSDKReferenceFolders(string sdkRoot) { throw null; } public static System.Collections.Generic.IList<string> GetSDKReferenceFolders(string sdkRoot, string targetConfiguration, string targetArchitecture) { throw null; } public static System.Collections.Generic.IList<string> GetSupportedTargetFrameworks() { throw null; } public static string[] GetTargetPlatformReferences(string sdkIdentifier, string sdkVersion, string targetPlatformIdentifier, string targetPlatformMinVersion, string targetPlatformVersion) { throw null; } public static string[] GetTargetPlatformReferences(string sdkIdentifier, string sdkVersion, string targetPlatformIdentifier, string targetPlatformMinVersion, string targetPlatformVersion, string diskRoots, string registryRoot) { throw null; } public static System.Collections.Generic.IList<Microsoft.Build.Utilities.TargetPlatformSDK> GetTargetPlatformSdks() { throw null; } public static System.Collections.Generic.IList<Microsoft.Build.Utilities.TargetPlatformSDK> GetTargetPlatformSdks(string[] diskRoots, string registryRoot) { throw null; } public static System.Runtime.Versioning.FrameworkName HighestVersionOfTargetFrameworkIdentifier(string targetFrameworkRootDirectory, string frameworkIdentifier) { throw null; } } public abstract partial class ToolTask : Microsoft.Build.Utilities.Task, Microsoft.Build.Framework.ICancelableTask, Microsoft.Build.Framework.ITask { protected ToolTask() { } protected ToolTask(System.Resources.ResourceManager taskResources) { } protected ToolTask(System.Resources.ResourceManager taskResources, string helpKeywordPrefix) { } public bool EchoOff { get { throw null; } set { } } [System.ObsoleteAttribute("Use EnvironmentVariables property")] protected virtual System.Collections.Generic.Dictionary<string, string> EnvironmentOverride { get { throw null; } } public string[] EnvironmentVariables { get { throw null; } set { } } [Microsoft.Build.Framework.OutputAttribute] public int ExitCode { get { throw null; } } protected virtual bool HasLoggedErrors { get { throw null; } } public bool LogStandardErrorAsError { get { throw null; } set { } } protected virtual System.Text.Encoding ResponseFileEncoding { get { throw null; } } protected virtual System.Text.Encoding StandardErrorEncoding { get { throw null; } } public string StandardErrorImportance { get { throw null; } set { } } protected Microsoft.Build.Framework.MessageImportance StandardErrorImportanceToUse { get { throw null; } } protected virtual Microsoft.Build.Framework.MessageImportance StandardErrorLoggingImportance { get { throw null; } } protected virtual System.Text.Encoding StandardOutputEncoding { get { throw null; } } public string StandardOutputImportance { get { throw null; } set { } } protected Microsoft.Build.Framework.MessageImportance StandardOutputImportanceToUse { get { throw null; } } protected virtual Microsoft.Build.Framework.MessageImportance StandardOutputLoggingImportance { get { throw null; } } protected int TaskProcessTerminationTimeout { get { throw null; } set { } } public virtual int Timeout { get { throw null; } set { } } protected System.Threading.ManualResetEvent ToolCanceled { get { throw null; } } public virtual string ToolExe { get { throw null; } set { } } protected abstract string ToolName { get; } public string ToolPath { get { throw null; } set { } } public bool UseCommandProcessor { get { throw null; } set { } } public bool YieldDuringToolExecution { get { throw null; } set { } } protected virtual string AdjustCommandsForOperatingSystem(string input) { throw null; } protected virtual bool CallHostObjectToExecute() { throw null; } public virtual void Cancel() { } protected void DeleteTempFile(string fileName) { } public override bool Execute() { throw null; } protected virtual int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { throw null; } protected virtual string GenerateCommandLineCommands() { throw null; } protected abstract string GenerateFullPathToTool(); protected virtual string GenerateResponseFileCommands() { throw null; } protected virtual System.Diagnostics.ProcessStartInfo GetProcessStartInfo(string pathToTool, string commandLineCommands, string responseFileSwitch) { throw null; } protected virtual string GetResponseFileSwitch(string responseFilePath) { throw null; } protected virtual string GetWorkingDirectory() { throw null; } protected virtual bool HandleTaskExecutionErrors() { throw null; } protected virtual Microsoft.Build.Utilities.HostObjectInitializationStatus InitializeHostObject() { throw null; } protected virtual void LogEventsFromTextOutput(string singleLine, Microsoft.Build.Framework.MessageImportance messageImportance) { } protected virtual void LogPathToTool(string toolName, string pathToTool) { } protected virtual void LogToolCommand(string message) { } protected virtual void ProcessStarted() { } protected virtual string ResponseFileEscape(string responseString) { throw null; } protected virtual bool SkipTaskExecution() { throw null; } protected internal virtual bool ValidateParameters() { throw null; } } public static partial class TrackedDependencies { public static Microsoft.Build.Framework.ITaskItem[] ExpandWildcards(Microsoft.Build.Framework.ITaskItem[] expand) { throw null; } } public enum VisualStudioVersion { Version100 = 0, Version110 = 1, Version120 = 2, Version140 = 3, Version150 = 4, VersionLatest = 4, } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Management.SFlowGlobalsBinding", Namespace="urn:iControl")] public partial class ManagementSFlowGlobals : iControlInterface { public ManagementSFlowGlobals() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // get_http_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_http_description( ) { object [] results = this.Invoke("get_http_description", new object [0]); return ((string)(results[0])); } public System.IAsyncResult Beginget_http_description(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_http_description", new object[0], callback, asyncState); } public string Endget_http_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_http_poll_interval //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_http_poll_interval( ) { object [] results = this.Invoke("get_http_poll_interval", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_http_poll_interval(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_http_poll_interval", new object[0], callback, asyncState); } public long Endget_http_poll_interval(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_http_sampling_rate //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_http_sampling_rate( ) { object [] results = this.Invoke("get_http_sampling_rate", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_http_sampling_rate(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_http_sampling_rate", new object[0], callback, asyncState); } public long Endget_http_sampling_rate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_interface_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_interface_description( ) { object [] results = this.Invoke("get_interface_description", new object [0]); return ((string)(results[0])); } public System.IAsyncResult Beginget_interface_description(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_interface_description", new object[0], callback, asyncState); } public string Endget_interface_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_interface_poll_interval //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_interface_poll_interval( ) { object [] results = this.Invoke("get_interface_poll_interval", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_interface_poll_interval(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_interface_poll_interval", new object[0], callback, asyncState); } public long Endget_interface_poll_interval(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_system_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_system_description( ) { object [] results = this.Invoke("get_system_description", new object [0]); return ((string)(results[0])); } public System.IAsyncResult Beginget_system_description(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_system_description", new object[0], callback, asyncState); } public string Endget_system_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_system_poll_interval //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_system_poll_interval( ) { object [] results = this.Invoke("get_system_poll_interval", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_system_poll_interval(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_system_poll_interval", new object[0], callback, asyncState); } public long Endget_system_poll_interval(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_vlan_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_vlan_description( ) { object [] results = this.Invoke("get_vlan_description", new object [0]); return ((string)(results[0])); } public System.IAsyncResult Beginget_vlan_description(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vlan_description", new object[0], callback, asyncState); } public string Endget_vlan_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_vlan_poll_interval //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_vlan_poll_interval( ) { object [] results = this.Invoke("get_vlan_poll_interval", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_vlan_poll_interval(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vlan_poll_interval", new object[0], callback, asyncState); } public long Endget_vlan_poll_interval(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_vlan_sampling_rate //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_vlan_sampling_rate( ) { object [] results = this.Invoke("get_vlan_sampling_rate", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_vlan_sampling_rate(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_vlan_sampling_rate", new object[0], callback, asyncState); } public long Endget_vlan_sampling_rate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // set_http_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] public void set_http_description( string description ) { this.Invoke("set_http_description", new object [] { description}); } public System.IAsyncResult Beginset_http_description(string description, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_http_description", new object[] { description}, callback, asyncState); } public void Endset_http_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_http_poll_interval //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] public void set_http_poll_interval( long interval ) { this.Invoke("set_http_poll_interval", new object [] { interval}); } public System.IAsyncResult Beginset_http_poll_interval(long interval, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_http_poll_interval", new object[] { interval}, callback, asyncState); } public void Endset_http_poll_interval(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_http_sampling_rate //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] public void set_http_sampling_rate( long rate ) { this.Invoke("set_http_sampling_rate", new object [] { rate}); } public System.IAsyncResult Beginset_http_sampling_rate(long rate, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_http_sampling_rate", new object[] { rate}, callback, asyncState); } public void Endset_http_sampling_rate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_interface_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] public void set_interface_description( string description ) { this.Invoke("set_interface_description", new object [] { description}); } public System.IAsyncResult Beginset_interface_description(string description, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_interface_description", new object[] { description}, callback, asyncState); } public void Endset_interface_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_interface_poll_interval //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] public void set_interface_poll_interval( long interval ) { this.Invoke("set_interface_poll_interval", new object [] { interval}); } public System.IAsyncResult Beginset_interface_poll_interval(long interval, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_interface_poll_interval", new object[] { interval}, callback, asyncState); } public void Endset_interface_poll_interval(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_system_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] public void set_system_description( string description ) { this.Invoke("set_system_description", new object [] { description}); } public System.IAsyncResult Beginset_system_description(string description, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_system_description", new object[] { description}, callback, asyncState); } public void Endset_system_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_system_poll_interval //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] public void set_system_poll_interval( long interval ) { this.Invoke("set_system_poll_interval", new object [] { interval}); } public System.IAsyncResult Beginset_system_poll_interval(long interval, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_system_poll_interval", new object[] { interval}, callback, asyncState); } public void Endset_system_poll_interval(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_vlan_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] public void set_vlan_description( string description ) { this.Invoke("set_vlan_description", new object [] { description}); } public System.IAsyncResult Beginset_vlan_description(string description, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_vlan_description", new object[] { description}, callback, asyncState); } public void Endset_vlan_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_vlan_poll_interval //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] public void set_vlan_poll_interval( long interval ) { this.Invoke("set_vlan_poll_interval", new object [] { interval}); } public System.IAsyncResult Beginset_vlan_poll_interval(long interval, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_vlan_poll_interval", new object[] { interval}, callback, asyncState); } public void Endset_vlan_poll_interval(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_vlan_sampling_rate //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/SFlowGlobals", RequestNamespace="urn:iControl:Management/SFlowGlobals", ResponseNamespace="urn:iControl:Management/SFlowGlobals")] public void set_vlan_sampling_rate( long rate ) { this.Invoke("set_vlan_sampling_rate", new object [] { rate}); } public System.IAsyncResult Beginset_vlan_sampling_rate(long rate, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_vlan_sampling_rate", new object[] { rate}, callback, asyncState); } public void Endset_vlan_sampling_rate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= }
/* * UInt64.cs - Implementation of the "System.UInt64" class. * * Copyright (C) 2001 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System { using System.Private; using System.Private.NumberFormat; using System.Globalization; [CLSCompliant(false)] public struct UInt64 : IComparable, IFormattable #if !ECMA_COMPAT , IConvertible #endif { private ulong value_; public const ulong MaxValue = 0xFFFFFFFFFFFFFFFF; public const ulong MinValue = 0; // Override inherited methods. public override int GetHashCode() { return unchecked((int)(value_ ^ (value_ >> 32))); } public override bool Equals(Object value) { if(value is UInt64) { return (value_ == ((UInt64)value).value_); } else { return false; } } // String conversion. public override String ToString() { return ToString(null, null); } public String ToString(String format) { return ToString(format, null); } public String ToString(IFormatProvider provider) { return ToString(null, provider); } public String ToString(String format, IFormatProvider provider) { if (format == null) format = "G"; return Formatter.CreateFormatter(format).Format(this, provider); } // Parsing methods. [CLSCompliant(false)] public static ulong Parse(String s, NumberStyles style, IFormatProvider provider) { NumberParser.ValidateIntegerStyle(style); return NumberParser.ParseUInt64 (s, style, NumberFormatInfo.GetInstance(provider), 0); } [CLSCompliant(false)] public static ulong Parse(String s) { return Parse(s, NumberStyles.Integer, null); } [CLSCompliant(false)] public static ulong Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } [CLSCompliant(false)] public static ulong Parse(String s, NumberStyles style) { return Parse(s, style, null); } // Implementation of the IComparable interface. public int CompareTo(Object value) { if(value != null) { if(!(value is UInt64)) { throw new ArgumentException(_("Arg_MustBeUInt64")); } ulong value2 = ((UInt64)value).value_; if(value_ < value2) { return -1; } else if(value_ > value2) { return 1; } else { return 0; } } else { return 1; } } #if !ECMA_COMPAT // Implementation of the IConvertible interface. public TypeCode GetTypeCode() { return TypeCode.UInt64; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(value_); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(value_); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(value_); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(value_); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(value_); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(value_); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(value_); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(value_); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(value_); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(value_); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(value_); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(value_); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(value_); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException (String.Format (_("InvalidCast_FromTo"), "UInt64", "DateTime")); } Object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return Convert.DefaultToType(this, conversionType, provider, true); } #endif // !ECMA_COMPAT }; // class UInt64 }; // namespace System
using System; using System.IO; using System.Text; namespace NAudio.Midi { /// <summary> /// Represents an individual MIDI event /// </summary> public class MidiEvent { /// <summary>The MIDI command code</summary> private MidiCommandCode commandCode; private int channel; private int deltaTime; private long absoluteTime; /// <summary> /// Creates a MidiEvent from a raw message received using /// the MME MIDI In APIs /// </summary> /// <param name="rawMessage">The short MIDI message</param> /// <returns>A new MIDI Event</returns> public static MidiEvent FromRawMessage(int rawMessage) { long absoluteTime = 0; int b = rawMessage & 0xFF; int data1 = (rawMessage >> 8) & 0xFF; int data2 = (rawMessage >> 16) & 0xFF; MidiCommandCode commandCode; int channel = 1; if ((b & 0xF0) == 0xF0) { // both bytes are used for command code in this case commandCode = (MidiCommandCode)b; } else { commandCode = (MidiCommandCode)(b & 0xF0); channel = (b & 0x0F) + 1; } MidiEvent me; switch (commandCode) { case MidiCommandCode.NoteOn: case MidiCommandCode.NoteOff: case MidiCommandCode.KeyAfterTouch: if (data2 > 0 && commandCode == MidiCommandCode.NoteOn) { me = new NoteOnEvent(absoluteTime, channel, data1, data2, 0); } else { me = new NoteEvent(absoluteTime, channel, commandCode, data1, data2); } break; case MidiCommandCode.TimingClock: case MidiCommandCode.StartSequence: case MidiCommandCode.ContinueSequence: case MidiCommandCode.StopSequence: case MidiCommandCode.AutoSensing: me = new MidiEvent(absoluteTime,channel,commandCode); break; case MidiCommandCode.MetaEvent: case MidiCommandCode.Sysex: default: throw new FormatException(String.Format("Unsupported MIDI Command Code for Raw Message {0}", commandCode)); } return me; } /// <summary> /// Constructs a MidiEvent from a BinaryStream /// </summary> /// <param name="br">The binary stream of MIDI data</param> /// <param name="previous">The previous MIDI event (pass null for first event)</param> /// <returns>A new MidiEvent</returns> public static MidiEvent ReadNextEvent(BinaryReader br, MidiEvent previous) { int deltaTime = MidiEvent.ReadVarInt(br); MidiCommandCode commandCode; int channel = 1; byte b = br.ReadByte(); if((b & 0x80) == 0) { // a running command - command & channel are same as previous commandCode = previous.CommandCode; channel = previous.Channel; br.BaseStream.Position--; // need to push this back } else { if((b & 0xF0) == 0xF0) { // both bytes are used for command code in this case commandCode = (MidiCommandCode) b; } else { commandCode = (MidiCommandCode) (b & 0xF0); channel = (b & 0x0F) + 1; } } MidiEvent me; switch(commandCode) { case MidiCommandCode.NoteOn: me = new NoteOnEvent(br); break; case MidiCommandCode.NoteOff: case MidiCommandCode.KeyAfterTouch: me = new NoteEvent(br); break; case MidiCommandCode.TimingClock: case MidiCommandCode.StartSequence: case MidiCommandCode.ContinueSequence: case MidiCommandCode.StopSequence: me = new MidiEvent(); break; case MidiCommandCode.Sysex: me = SysexEvent.ReadSysexEvent(br); break; case MidiCommandCode.MetaEvent: me = MetaEvent.ReadMetaEvent(br); break; default: throw new FormatException(String.Format("Unsupported MIDI Command Code {0:X2}",(byte) commandCode)); } me.channel = channel; me.deltaTime = deltaTime; me.commandCode = commandCode; return me; } /// <summary> /// Converts this MIDI event to a short message (32 bit integer) that /// can be sent by the Windows MIDI out short message APIs /// Cannot be implemented for all MIDI messages /// </summary> /// <returns>A short message</returns> public virtual int GetAsShortMessage() { return (channel - 1) + (int)commandCode; } /// <summary> /// Default constructor /// </summary> protected MidiEvent() { } /// <summary> /// Creates a MIDI event with specified parameters /// </summary> /// <param name="absoluteTime">Absolute time of this event</param> /// <param name="channel">MIDI channel number</param> /// <param name="commandCode">MIDI command code</param> public MidiEvent(long absoluteTime, int channel, MidiCommandCode commandCode) { this.absoluteTime = absoluteTime; this.Channel = channel; this.commandCode = commandCode; } /// <summary> /// The MIDI Channel Number for this event (1-16) /// </summary> public virtual int Channel { get { return channel; } set { if ((value < 1) || (value > 16)) { throw new ArgumentOutOfRangeException("value", value, String.Format("Channel must be 1-16 (Got {0})",value)); } channel = value; } } /// <summary> /// The Delta time for this event /// </summary> public int DeltaTime { get { return deltaTime; } } /// <summary> /// The absolute time for this event /// </summary> public long AbsoluteTime { get { return absoluteTime; } set { absoluteTime = value; } } /// <summary> /// The command code for this event /// </summary> public MidiCommandCode CommandCode { get { return commandCode; } } /// <summary> /// Whether this is a note off event /// </summary> public static bool IsNoteOff(MidiEvent midiEvent) { if (midiEvent != null) { if (midiEvent.CommandCode == MidiCommandCode.NoteOn) { NoteEvent ne = (NoteEvent)midiEvent; return (ne.Velocity == 0); } return (midiEvent.CommandCode == MidiCommandCode.NoteOff); } return false; } /// <summary> /// Whether this is a note on event /// </summary> public static bool IsNoteOn(MidiEvent midiEvent) { if (midiEvent != null) { if (midiEvent.CommandCode == MidiCommandCode.NoteOn) { NoteEvent ne = (NoteEvent)midiEvent; return (ne.Velocity > 0); } } return false; } /// <summary> /// Determines if this is an end track event /// </summary> public static bool IsEndTrack(MidiEvent midiEvent) { if (midiEvent != null) { MetaEvent me = midiEvent as MetaEvent; if (me != null) { return me.MetaEventType == MetaEventType.EndTrack; } } return false; } /// <summary> /// Displays a summary of the MIDI event /// </summary> /// <returns>A string containing a brief description of this MIDI event</returns> public override string ToString() { if(commandCode >= MidiCommandCode.Sysex) return String.Format("{0} {1}",absoluteTime,commandCode); else return String.Format("{0} {1} Ch: {2}", absoluteTime, commandCode, channel); } /// <summary> /// Utility function that can read a variable length integer from a binary stream /// </summary> /// <param name="br">The binary stream</param> /// <returns>The integer read</returns> public static int ReadVarInt(BinaryReader br) { int value = 0; byte b; for(int n = 0; n < 4; n++) { b = br.ReadByte(); value <<= 7; value += (b & 0x7F); if((b & 0x80) == 0) { return value; } } throw new FormatException("Invalid Var Int"); } /// <summary> /// Writes a variable length integer to a binary stream /// </summary> /// <param name="writer">Binary stream</param> /// <param name="value">The value to write</param> public static void WriteVarInt(BinaryWriter writer, int value) { if (value < 0) { throw new ArgumentOutOfRangeException("value", value, "Cannot write a negative Var Int"); } if (value > 0x0FFFFFFF) { throw new ArgumentOutOfRangeException("value", value, "Maximum allowed Var Int is 0x0FFFFFFF"); } int n = 0; byte[] buffer = new byte[4]; do { buffer[n++] = (byte)(value & 0x7F); value >>= 7; } while (value > 0); while (n > 0) { n--; if(n > 0) writer.Write((byte) (buffer[n] | 0x80)); else writer.Write(buffer[n]); } } /// <summary> /// Exports this MIDI event's data /// Overriden in derived classes, but they should call this version /// </summary> /// <param name="absoluteTime">Absolute time used to calculate delta. /// Is updated ready for the next delta calculation</param> /// <param name="writer">Stream to write to</param> public virtual void Export(ref long absoluteTime, BinaryWriter writer) { if (this.absoluteTime < absoluteTime) { throw new FormatException("Can't export unsorted MIDI events"); } WriteVarInt(writer,(int) (this.absoluteTime - absoluteTime)); absoluteTime = this.absoluteTime; int output = (int) commandCode; if (commandCode != MidiCommandCode.MetaEvent) { output += (channel - 1); } writer.Write((byte)output); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Primitives; using Newtonsoft.Json.Linq; using OrchardCore.ContentManagement.Metadata; using OrchardCore.ContentManagement.Metadata.Models; using OrchardCore.ContentManagement.Metadata.Records; using OrchardCore.Environment.Cache; namespace OrchardCore.ContentManagement { public class ContentDefinitionManager : IContentDefinitionManager { private const string CacheKey = nameof(ContentDefinitionManager); private readonly ISignal _signal; private readonly IContentDefinitionStore _contentDefinitionStore; private readonly IMemoryCache _memoryCache; private readonly ConcurrentDictionary<string, ContentTypeDefinition> _cachedTypeDefinitions; private readonly ConcurrentDictionary<string, ContentPartDefinition> _cachedPartDefinitions; private readonly Dictionary<string, ContentTypeDefinition> _scopedTypeDefinitions = new Dictionary<string, ContentTypeDefinition>(); private readonly Dictionary<string, ContentPartDefinition> _scopedPartDefinitions = new Dictionary<string, ContentPartDefinition>(); public ContentDefinitionManager( ISignal signal, IContentDefinitionStore contentDefinitionStore, IMemoryCache memoryCache) { _signal = signal; _contentDefinitionStore = contentDefinitionStore; _memoryCache = memoryCache; _cachedTypeDefinitions = _memoryCache.GetOrCreate("TypeDefinitions", entry => new ConcurrentDictionary<string, ContentTypeDefinition>()); _cachedPartDefinitions = _memoryCache.GetOrCreate("PartDefinitions", entry => new ConcurrentDictionary<string, ContentPartDefinition>()); } public IChangeToken ChangeToken => _signal.GetToken(CacheKey); public ContentTypeDefinition LoadTypeDefinition(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Argument cannot be null or empty", nameof(name)); } if (!_scopedTypeDefinitions.TryGetValue(name, out var typeDefinition)) { var contentTypeDefinitionRecord = LoadContentDefinitionRecord() .ContentTypeDefinitionRecords .FirstOrDefault(x => x.Name == name); _scopedTypeDefinitions[name] = typeDefinition = Build(contentTypeDefinitionRecord, LoadContentDefinitionRecord().ContentPartDefinitionRecords); }; return typeDefinition; } public ContentTypeDefinition GetTypeDefinition(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Argument cannot be null or empty", nameof(name)); } return _cachedTypeDefinitions.GetOrAdd(name, n => { var contentTypeDefinitionRecord = GetContentDefinitionRecord() .ContentTypeDefinitionRecords .FirstOrDefault(x => x.Name == name); return Build(contentTypeDefinitionRecord, GetContentDefinitionRecord().ContentPartDefinitionRecords); }); } public ContentPartDefinition LoadPartDefinition(string name) { if (!_scopedPartDefinitions.TryGetValue(name, out var partDefinition)) { _scopedPartDefinitions[name] = partDefinition = Build(LoadContentDefinitionRecord() .ContentPartDefinitionRecords .FirstOrDefault(x => x.Name == name)); }; return partDefinition; } public ContentPartDefinition GetPartDefinition(string name) { return _cachedPartDefinitions.GetOrAdd(name, n => { return Build(GetContentDefinitionRecord() .ContentPartDefinitionRecords .FirstOrDefault(x => x.Name == name)); }); } public IEnumerable<ContentTypeDefinition> LoadTypeDefinitions() { return LoadContentDefinitionRecord().ContentTypeDefinitionRecords.Select(x => LoadTypeDefinition(x.Name)).ToList(); } public IEnumerable<ContentTypeDefinition> ListTypeDefinitions() { return GetContentDefinitionRecord().ContentTypeDefinitionRecords.Select(x => GetTypeDefinition(x.Name)).ToList(); } public IEnumerable<ContentPartDefinition> LoadPartDefinitions() { return LoadContentDefinitionRecord().ContentPartDefinitionRecords.Select(x => LoadPartDefinition(x.Name)).ToList(); } public IEnumerable<ContentPartDefinition> ListPartDefinitions() { return GetContentDefinitionRecord().ContentPartDefinitionRecords.Select(x => GetPartDefinition(x.Name)).ToList(); } public void StoreTypeDefinition(ContentTypeDefinition contentTypeDefinition) { Apply(contentTypeDefinition, Acquire(contentTypeDefinition)); UpdateContentDefinitionRecord(); } public void StorePartDefinition(ContentPartDefinition contentPartDefinition) { Apply(contentPartDefinition, Acquire(contentPartDefinition)); UpdateContentDefinitionRecord(); } public void DeleteTypeDefinition(string name) { var record = LoadContentDefinitionRecord().ContentTypeDefinitionRecords.FirstOrDefault(x => x.Name == name); // deletes the content type record associated if (record != null) { LoadContentDefinitionRecord().ContentTypeDefinitionRecords.Remove(record); UpdateContentDefinitionRecord(); } } public void DeletePartDefinition(string name) { // remove parts from current types var typesWithPart = LoadTypeDefinitions().Where(typeDefinition => typeDefinition.Parts.Any(part => part.PartDefinition.Name == name)); foreach (var typeDefinition in typesWithPart) { this.AlterTypeDefinition(typeDefinition.Name, builder => builder.RemovePart(name)); } // delete part var record = LoadContentDefinitionRecord().ContentPartDefinitionRecords.FirstOrDefault(x => x.Name == name); if (record != null) { LoadContentDefinitionRecord().ContentPartDefinitionRecords.Remove(record); UpdateContentDefinitionRecord(); } } private ContentTypeDefinitionRecord Acquire(ContentTypeDefinition contentTypeDefinition) { var result = LoadContentDefinitionRecord().ContentTypeDefinitionRecords.FirstOrDefault(x => x.Name == contentTypeDefinition.Name); if (result == null) { result = new ContentTypeDefinitionRecord { Name = contentTypeDefinition.Name, DisplayName = contentTypeDefinition.DisplayName }; LoadContentDefinitionRecord().ContentTypeDefinitionRecords.Add(result); } return result; } private ContentPartDefinitionRecord Acquire(ContentPartDefinition contentPartDefinition) { var result = LoadContentDefinitionRecord().ContentPartDefinitionRecords.FirstOrDefault(x => x.Name == contentPartDefinition.Name); if (result == null) { result = new ContentPartDefinitionRecord { Name = contentPartDefinition.Name, }; LoadContentDefinitionRecord().ContentPartDefinitionRecords.Add(result); } return result; } private void Apply(ContentTypeDefinition model, ContentTypeDefinitionRecord record) { record.DisplayName = model.DisplayName; record.Settings = model.Settings; var toRemove = record.ContentTypePartDefinitionRecords .Where(typePartDefinitionRecord => !model.Parts.Any(part => typePartDefinitionRecord.Name == part.Name)) .ToList(); foreach (var remove in toRemove) { record.ContentTypePartDefinitionRecords.Remove(remove); } foreach (var part in model.Parts) { var typePartRecord = record.ContentTypePartDefinitionRecords.FirstOrDefault(r => r.Name == part.Name); if (typePartRecord == null) { typePartRecord = new ContentTypePartDefinitionRecord { PartName = part.PartDefinition.Name, Name = part.Name, Settings = part.Settings }; record.ContentTypePartDefinitionRecords.Add(typePartRecord); } Apply(part, typePartRecord); } } private void Apply(ContentTypePartDefinition model, ContentTypePartDefinitionRecord record) { record.Settings = model.Settings; } private void Apply(ContentPartDefinition model, ContentPartDefinitionRecord record) { record.Settings = model.Settings; var toRemove = record.ContentPartFieldDefinitionRecords .Where(partFieldDefinitionRecord => !model.Fields.Any(partField => partFieldDefinitionRecord.Name == partField.Name)) .ToList(); foreach (var remove in toRemove) { record.ContentPartFieldDefinitionRecords.Remove(remove); } foreach (var field in model.Fields) { var fieldName = field.Name; var partFieldRecord = record.ContentPartFieldDefinitionRecords.FirstOrDefault(r => r.Name == fieldName); if (partFieldRecord == null) { partFieldRecord = new ContentPartFieldDefinitionRecord { FieldName = field.FieldDefinition.Name, Name = field.Name }; record.ContentPartFieldDefinitionRecords.Add(partFieldRecord); } Apply(field, partFieldRecord); } } private void Apply(ContentPartFieldDefinition model, ContentPartFieldDefinitionRecord record) { record.Settings = model.Settings; } private ContentTypeDefinition Build(ContentTypeDefinitionRecord source, IList<ContentPartDefinitionRecord> partDefinitionRecords) { if (source == null) { return null; } var contentTypeDefinition = new ContentTypeDefinition( source.Name, source.DisplayName, source.ContentTypePartDefinitionRecords.Select(tp => Build(tp, partDefinitionRecords.FirstOrDefault(p => p.Name == tp.PartName))), source.Settings); return contentTypeDefinition; } private ContentTypePartDefinition Build(ContentTypePartDefinitionRecord source, ContentPartDefinitionRecord partDefinitionRecord) { return source == null ? null : new ContentTypePartDefinition( source.Name, Build(partDefinitionRecord) ?? new ContentPartDefinition(source.PartName, Enumerable.Empty<ContentPartFieldDefinition>(), new JObject()), source.Settings); } private ContentPartDefinition Build(ContentPartDefinitionRecord source) { return source == null ? null : new ContentPartDefinition( source.Name, source.ContentPartFieldDefinitionRecords.Select(Build), source.Settings); } private ContentPartFieldDefinition Build(ContentPartFieldDefinitionRecord source) { return source == null ? null : new ContentPartFieldDefinition( Build(new ContentFieldDefinitionRecord { Name = source.FieldName }), source.Name, source.Settings ); } private ContentFieldDefinition Build(ContentFieldDefinitionRecord source) { return source == null ? null : new ContentFieldDefinition(source.Name); } public Task<int> GetTypesHashAsync() { return Task.FromResult(GetContentDefinitionRecord().Serial); } /// <summary> /// Returns the document from the store to be updated. /// </summary> private ContentDefinitionRecord LoadContentDefinitionRecord() => _contentDefinitionStore.LoadContentDefinitionAsync().GetAwaiter().GetResult(); private ContentDefinitionRecord GetContentDefinitionRecord() { if (!_memoryCache.TryGetValue<ContentDefinitionRecord>(CacheKey, out var record)) { var changeToken = ChangeToken; var typeDefinitions = _cachedTypeDefinitions; var partDefinitions = _cachedPartDefinitions; // Using local vars prevents the lambda from holding a ref on this scoped service. changeToken.RegisterChangeCallback((state) => { typeDefinitions.Clear(); partDefinitions.Clear(); }, state: null); bool cacheable; (cacheable, record) = _contentDefinitionStore.GetContentDefinitionAsync().GetAwaiter().GetResult(); if (cacheable) { _memoryCache.Set(CacheKey, record, changeToken); } } return record; } private void UpdateContentDefinitionRecord() { var contentDefinitionRecord = LoadContentDefinitionRecord(); contentDefinitionRecord.Serial++; _contentDefinitionStore.SaveContentDefinitionAsync(contentDefinitionRecord).GetAwaiter().GetResult(); // Cache invalidation at the end of the scope. _signal.DeferredSignalToken(CacheKey); // If multiple updates in the same scope, types and parts may need to be rebuilt. _scopedTypeDefinitions.Clear(); _scopedPartDefinitions.Clear(); } } }
using System; partial class formItemManagement : System.Windows.Forms.Form { /// <summary> /// Designer variable used to keep track of non-visual components. /// </summary> private System.ComponentModel.IContainer components; /// <summary> /// Disposes resources used by the form. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } /// <summary> /// This method is required for Windows Forms designer support. /// Do not change the method contents inside the source code editor. The Forms designer might /// not be able to load this method if it was changed manually. /// </summary> private void InitializeComponent() { this.labelStoreTotalLevel = new System.Windows.Forms.Label(); this.updownStoreLevel = new System.Windows.Forms.NumericUpDown(); this.labelStoreLevel = new System.Windows.Forms.Label(); this.labelStoreShelf = new System.Windows.Forms.Label(); this.updownStoreShelf = new System.Windows.Forms.NumericUpDown(); this.labelStoreTotalShelf = new System.Windows.Forms.Label(); this.labelStoreTotalBin = new System.Windows.Forms.Label(); this.updownStoreBin = new System.Windows.Forms.NumericUpDown(); this.labelStoreBin = new System.Windows.Forms.Label(); this.groupboxStoreNavigation = new System.Windows.Forms.GroupBox(); this.groupboxStoreSelected = new System.Windows.Forms.GroupBox(); this.updownStorePrice = new System.Windows.Forms.NumericUpDown(); this.textboxStoreQuantity = new System.Windows.Forms.TextBox(); this.labelStorePrice = new System.Windows.Forms.Label(); this.textboxStoreName = new System.Windows.Forms.TextBox(); this.labelStoreQuantity = new System.Windows.Forms.Label(); this.textboxStorePhItem = new System.Windows.Forms.TextBox(); this.labelStoreName = new System.Windows.Forms.Label(); this.labelStorePhItem = new System.Windows.Forms.Label(); this.textboxStoragePhItem = new System.Windows.Forms.TextBox(); this.labelStoragePhItem = new System.Windows.Forms.Label(); this.buttonToStore = new System.Windows.Forms.Button(); this.buttonToStorage = new System.Windows.Forms.Button(); this.buttonClose = new System.Windows.Forms.Button(); this.groupboxStore = new System.Windows.Forms.GroupBox(); this.labelStorageQuantity = new System.Windows.Forms.Label(); this.labelStorageLastBuy = new System.Windows.Forms.Label(); this.labelStorageLastSell = new System.Windows.Forms.Label(); this.groupboxStorage = new System.Windows.Forms.GroupBox(); this.groupboxStorageNavigation = new System.Windows.Forms.GroupBox(); this.labelStorageArticle = new System.Windows.Forms.Label(); this.labelStorageSection = new System.Windows.Forms.Label(); this.updownStorageArticle = new System.Windows.Forms.NumericUpDown(); this.labelStorageTotalSection = new System.Windows.Forms.Label(); this.labelStorageTotalArticle = new System.Windows.Forms.Label(); this.updownStorageSection = new System.Windows.Forms.NumericUpDown(); this.groupboxStorageSelected = new System.Windows.Forms.GroupBox(); this.textboxStorageLastBuy = new System.Windows.Forms.TextBox(); this.textboxStorageName = new System.Windows.Forms.TextBox(); this.textboxStorageLastSell = new System.Windows.Forms.TextBox(); this.textboxStorageQuantity = new System.Windows.Forms.TextBox(); this.labelStorageName = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)this.updownStoreLevel).BeginInit(); ((System.ComponentModel.ISupportInitialize)this.updownStoreShelf).BeginInit(); ((System.ComponentModel.ISupportInitialize)this.updownStoreBin).BeginInit(); this.groupboxStoreNavigation.SuspendLayout(); this.groupboxStoreSelected.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)this.updownStorePrice).BeginInit(); this.groupboxStore.SuspendLayout(); this.groupboxStorage.SuspendLayout(); this.groupboxStorageNavigation.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)this.updownStorageArticle).BeginInit(); ((System.ComponentModel.ISupportInitialize)this.updownStorageSection).BeginInit(); this.groupboxStorageSelected.SuspendLayout(); this.SuspendLayout(); // //labelStoreTotalLevel // this.labelStoreTotalLevel.AutoSize = true; this.labelStoreTotalLevel.Location = new System.Drawing.Point(46, 34); this.labelStoreTotalLevel.Name = "labelStoreTotalLevel"; this.labelStoreTotalLevel.Size = new System.Drawing.Size(21, 13); this.labelStoreTotalLevel.TabIndex = 1; this.labelStoreTotalLevel.Text = "\\ 0"; // //updownStoreLevel // this.updownStoreLevel.Location = new System.Drawing.Point(6, 32); this.updownStoreLevel.Name = "updownStoreLevel"; this.updownStoreLevel.Size = new System.Drawing.Size(34, 20); this.updownStoreLevel.TabIndex = 2; this.updownStoreLevel.ValueChanged += this.updownStoreLevel_ValueChanged; // //labelStoreLevel // this.labelStoreLevel.AutoSize = true; this.labelStoreLevel.Location = new System.Drawing.Point(6, 16); this.labelStoreLevel.Name = "labelStoreLevel"; this.labelStoreLevel.Size = new System.Drawing.Size(36, 13); this.labelStoreLevel.TabIndex = 3; this.labelStoreLevel.Text = "Level:"; // //labelStoreShelf // this.labelStoreShelf.AutoSize = true; this.labelStoreShelf.Location = new System.Drawing.Point(98, 16); this.labelStoreShelf.Name = "labelStoreShelf"; this.labelStoreShelf.Size = new System.Drawing.Size(34, 13); this.labelStoreShelf.TabIndex = 6; this.labelStoreShelf.Text = "Shelf:"; // //updownStoreShelf // this.updownStoreShelf.Location = new System.Drawing.Point(98, 32); this.updownStoreShelf.Name = "updownStoreShelf"; this.updownStoreShelf.Size = new System.Drawing.Size(34, 20); this.updownStoreShelf.TabIndex = 5; this.updownStoreShelf.ValueChanged += this.updownStoreShelf_ValueChanged; // //labelStoreTotalShelf // this.labelStoreTotalShelf.AutoSize = true; this.labelStoreTotalShelf.Location = new System.Drawing.Point(138, 34); this.labelStoreTotalShelf.Name = "labelStoreTotalShelf"; this.labelStoreTotalShelf.Size = new System.Drawing.Size(21, 13); this.labelStoreTotalShelf.TabIndex = 4; this.labelStoreTotalShelf.Text = "\\ 0"; // //labelStoreTotalBin // this.labelStoreTotalBin.AutoSize = true; this.labelStoreTotalBin.Location = new System.Drawing.Point(233, 34); this.labelStoreTotalBin.Name = "labelStoreTotalBin"; this.labelStoreTotalBin.Size = new System.Drawing.Size(21, 13); this.labelStoreTotalBin.TabIndex = 4; this.labelStoreTotalBin.Text = "\\ 0"; // //updownStoreBin // this.updownStoreBin.Location = new System.Drawing.Point(193, 32); this.updownStoreBin.Name = "updownStoreBin"; this.updownStoreBin.Size = new System.Drawing.Size(34, 20); this.updownStoreBin.TabIndex = 5; this.updownStoreBin.ValueChanged += this.updownStoreBin_ValueChanged; // //labelStoreBin // this.labelStoreBin.AutoSize = true; this.labelStoreBin.Location = new System.Drawing.Point(193, 16); this.labelStoreBin.Name = "labelStoreBin"; this.labelStoreBin.Size = new System.Drawing.Size(25, 13); this.labelStoreBin.TabIndex = 6; this.labelStoreBin.Text = "Bin:"; // //groupboxStoreNavigation // this.groupboxStoreNavigation.Controls.Add(this.labelStoreLevel); this.groupboxStoreNavigation.Controls.Add(this.labelStoreBin); this.groupboxStoreNavigation.Controls.Add(this.labelStoreTotalLevel); this.groupboxStoreNavigation.Controls.Add(this.labelStoreShelf); this.groupboxStoreNavigation.Controls.Add(this.updownStoreLevel); this.groupboxStoreNavigation.Controls.Add(this.updownStoreBin); this.groupboxStoreNavigation.Controls.Add(this.labelStoreTotalShelf); this.groupboxStoreNavigation.Controls.Add(this.labelStoreTotalBin); this.groupboxStoreNavigation.Controls.Add(this.updownStoreShelf); this.groupboxStoreNavigation.Location = new System.Drawing.Point(6, 19); this.groupboxStoreNavigation.Name = "groupboxStoreNavigation"; this.groupboxStoreNavigation.Size = new System.Drawing.Size(260, 57); this.groupboxStoreNavigation.TabIndex = 7; this.groupboxStoreNavigation.TabStop = false; this.groupboxStoreNavigation.Text = "Navigation"; // //groupboxStoreSelected // this.groupboxStoreSelected.Controls.Add(this.updownStorePrice); this.groupboxStoreSelected.Controls.Add(this.textboxStoreQuantity); this.groupboxStoreSelected.Controls.Add(this.labelStorePrice); this.groupboxStoreSelected.Controls.Add(this.textboxStoreName); this.groupboxStoreSelected.Controls.Add(this.labelStoreQuantity); this.groupboxStoreSelected.Controls.Add(this.textboxStorePhItem); this.groupboxStoreSelected.Controls.Add(this.labelStoreName); this.groupboxStoreSelected.Controls.Add(this.labelStorePhItem); this.groupboxStoreSelected.Location = new System.Drawing.Point(6, 82); this.groupboxStoreSelected.Name = "groupboxStoreSelected"; this.groupboxStoreSelected.Size = new System.Drawing.Size(260, 142); this.groupboxStoreSelected.TabIndex = 8; this.groupboxStoreSelected.TabStop = false; this.groupboxStoreSelected.Text = "Selected Bin"; // //updownStorePrice // this.updownStorePrice.Location = new System.Drawing.Point(112, 97); this.updownStorePrice.Name = "updownStorePrice"; this.updownStorePrice.Size = new System.Drawing.Size(141, 20); this.updownStorePrice.TabIndex = 4; this.updownStorePrice.LostFocus += this.updownStorePrice_LostFocus; // //textboxStoreQuantity // this.textboxStoreQuantity.Location = new System.Drawing.Point(112, 71); this.textboxStoreQuantity.Name = "textboxStoreQuantity"; this.textboxStoreQuantity.Size = new System.Drawing.Size(141, 20); this.textboxStoreQuantity.TabIndex = 3; // //labelStorePrice // this.labelStorePrice.AutoSize = true; this.labelStorePrice.Location = new System.Drawing.Point(5, 100); this.labelStorePrice.Name = "labelStorePrice"; this.labelStorePrice.Size = new System.Drawing.Size(68, 13); this.labelStorePrice.TabIndex = 2; this.labelStorePrice.Text = "Selling Price:"; // //textboxStoreName // this.textboxStoreName.Location = new System.Drawing.Point(112, 45); this.textboxStoreName.Name = "textboxStoreName"; this.textboxStoreName.Size = new System.Drawing.Size(141, 20); this.textboxStoreName.TabIndex = 3; // //labelStoreQuantity // this.labelStoreQuantity.AutoSize = true; this.labelStoreQuantity.Location = new System.Drawing.Point(5, 74); this.labelStoreQuantity.Name = "labelStoreQuantity"; this.labelStoreQuantity.Size = new System.Drawing.Size(49, 13); this.labelStoreQuantity.TabIndex = 2; this.labelStoreQuantity.Text = "Quantity:"; // //textboxStorePhItem // this.textboxStorePhItem.Location = new System.Drawing.Point(112, 19); this.textboxStorePhItem.Name = "textboxStorePhItem"; this.textboxStorePhItem.Size = new System.Drawing.Size(141, 20); this.textboxStorePhItem.TabIndex = 3; // //labelStoreName // this.labelStoreName.AutoSize = true; this.labelStoreName.Location = new System.Drawing.Point(5, 48); this.labelStoreName.Name = "labelStoreName"; this.labelStoreName.Size = new System.Drawing.Size(61, 13); this.labelStoreName.TabIndex = 2; this.labelStoreName.Text = "Item Name:"; // //labelStorePhItem // this.labelStorePhItem.AutoSize = true; this.labelStorePhItem.Location = new System.Drawing.Point(5, 22); this.labelStorePhItem.Name = "labelStorePhItem"; this.labelStorePhItem.Size = new System.Drawing.Size(49, 13); this.labelStorePhItem.TabIndex = 2; this.labelStorePhItem.Text = "Ph. Item:"; // //textboxStoragePhItem // this.textboxStoragePhItem.Location = new System.Drawing.Point(113, 13); this.textboxStoragePhItem.Name = "textboxStoragePhItem"; this.textboxStoragePhItem.Size = new System.Drawing.Size(146, 20); this.textboxStoragePhItem.TabIndex = 3; // //labelStoragePhItem // this.labelStoragePhItem.AutoSize = true; this.labelStoragePhItem.Location = new System.Drawing.Point(6, 16); this.labelStoragePhItem.Name = "labelStoragePhItem"; this.labelStoragePhItem.Size = new System.Drawing.Size(49, 13); this.labelStoragePhItem.TabIndex = 2; this.labelStoragePhItem.Text = "Ph. Item:"; // //buttonToStore // this.buttonToStore.Location = new System.Drawing.Point(295, 77); this.buttonToStore.Name = "buttonToStore"; this.buttonToStore.Size = new System.Drawing.Size(74, 65); this.buttonToStore.TabIndex = 1; this.buttonToStore.Text = "Bin >>"; this.buttonToStore.UseVisualStyleBackColor = true; this.buttonToStore.Click += this.buttonToStore_Click; // //buttonToStorage // this.buttonToStorage.Location = new System.Drawing.Point(295, 12); this.buttonToStorage.Name = "buttonToStorage"; this.buttonToStorage.Size = new System.Drawing.Size(74, 59); this.buttonToStorage.TabIndex = 0; this.buttonToStorage.Text = "<< Storage"; this.buttonToStorage.UseVisualStyleBackColor = true; this.buttonToStorage.Click += this.buttonToStorage_Click; // //buttonClose // this.buttonClose.Location = new System.Drawing.Point(295, 148); this.buttonClose.Name = "buttonClose"; this.buttonClose.Size = new System.Drawing.Size(74, 94); this.buttonClose.TabIndex = 0; this.buttonClose.Text = "Close"; this.buttonClose.UseVisualStyleBackColor = true; this.buttonClose.Click += this.buttonClose_Click; // //groupboxStore // this.groupboxStore.Controls.Add(this.groupboxStoreNavigation); this.groupboxStore.Controls.Add(this.groupboxStoreSelected); this.groupboxStore.Location = new System.Drawing.Point(375, 12); this.groupboxStore.Name = "groupboxStore"; this.groupboxStore.Size = new System.Drawing.Size(272, 230); this.groupboxStore.TabIndex = 10; this.groupboxStore.TabStop = false; this.groupboxStore.Text = "Store"; // //labelStorageQuantity // this.labelStorageQuantity.AutoSize = true; this.labelStorageQuantity.Location = new System.Drawing.Point(6, 68); this.labelStorageQuantity.Name = "labelStorageQuantity"; this.labelStorageQuantity.Size = new System.Drawing.Size(46, 13); this.labelStorageQuantity.TabIndex = 0; this.labelStorageQuantity.Text = "Quantity"; // //labelStorageLastBuy // this.labelStorageLastBuy.AutoSize = true; this.labelStorageLastBuy.Location = new System.Drawing.Point(6, 120); this.labelStorageLastBuy.Name = "labelStorageLastBuy"; this.labelStorageLastBuy.Size = new System.Drawing.Size(89, 13); this.labelStorageLastBuy.TabIndex = 0; this.labelStorageLastBuy.Text = "Last Buying Price"; // //labelStorageLastSell // this.labelStorageLastSell.AutoSize = true; this.labelStorageLastSell.Location = new System.Drawing.Point(6, 94); this.labelStorageLastSell.Name = "labelStorageLastSell"; this.labelStorageLastSell.Size = new System.Drawing.Size(88, 13); this.labelStorageLastSell.TabIndex = 0; this.labelStorageLastSell.Text = "Last Selling Price"; // //groupboxStorage // this.groupboxStorage.Controls.Add(this.groupboxStorageNavigation); this.groupboxStorage.Controls.Add(this.groupboxStorageSelected); this.groupboxStorage.Location = new System.Drawing.Point(12, 12); this.groupboxStorage.Name = "groupboxStorage"; this.groupboxStorage.Size = new System.Drawing.Size(277, 230); this.groupboxStorage.TabIndex = 9; this.groupboxStorage.TabStop = false; this.groupboxStorage.Text = "Storage"; // //groupboxStorageNavigation // this.groupboxStorageNavigation.Controls.Add(this.labelStorageArticle); this.groupboxStorageNavigation.Controls.Add(this.labelStorageSection); this.groupboxStorageNavigation.Controls.Add(this.updownStorageArticle); this.groupboxStorageNavigation.Controls.Add(this.labelStorageTotalSection); this.groupboxStorageNavigation.Controls.Add(this.labelStorageTotalArticle); this.groupboxStorageNavigation.Controls.Add(this.updownStorageSection); this.groupboxStorageNavigation.Location = new System.Drawing.Point(6, 19); this.groupboxStorageNavigation.Name = "groupboxStorageNavigation"; this.groupboxStorageNavigation.Size = new System.Drawing.Size(265, 57); this.groupboxStorageNavigation.TabIndex = 7; this.groupboxStorageNavigation.TabStop = false; this.groupboxStorageNavigation.Text = "Navigation"; // //labelStorageArticle // this.labelStorageArticle.AutoSize = true; this.labelStorageArticle.Location = new System.Drawing.Point(198, 16); this.labelStorageArticle.Name = "labelStorageArticle"; this.labelStorageArticle.Size = new System.Drawing.Size(39, 13); this.labelStorageArticle.TabIndex = 6; this.labelStorageArticle.Text = "Article:"; // //labelStorageSection // this.labelStorageSection.AutoSize = true; this.labelStorageSection.Location = new System.Drawing.Point(12, 16); this.labelStorageSection.Name = "labelStorageSection"; this.labelStorageSection.Size = new System.Drawing.Size(46, 13); this.labelStorageSection.TabIndex = 6; this.labelStorageSection.Text = "Section:"; // //updownStorageArticle // this.updownStorageArticle.Location = new System.Drawing.Point(198, 32); this.updownStorageArticle.Name = "updownStorageArticle"; this.updownStorageArticle.Size = new System.Drawing.Size(34, 20); this.updownStorageArticle.TabIndex = 5; this.updownStorageArticle.ValueChanged += this.updownStorageArticle_ValueChanged; // //labelStorageTotalSection // this.labelStorageTotalSection.AutoSize = true; this.labelStorageTotalSection.Location = new System.Drawing.Point(52, 34); this.labelStorageTotalSection.Name = "labelStorageTotalSection"; this.labelStorageTotalSection.Size = new System.Drawing.Size(21, 13); this.labelStorageTotalSection.TabIndex = 4; this.labelStorageTotalSection.Text = "\\ 0"; // //labelStorageTotalArticle // this.labelStorageTotalArticle.AutoSize = true; this.labelStorageTotalArticle.Location = new System.Drawing.Point(238, 34); this.labelStorageTotalArticle.Name = "labelStorageTotalArticle"; this.labelStorageTotalArticle.Size = new System.Drawing.Size(21, 13); this.labelStorageTotalArticle.TabIndex = 4; this.labelStorageTotalArticle.Text = "\\ 0"; // //updownStorageSection // this.updownStorageSection.Location = new System.Drawing.Point(12, 32); this.updownStorageSection.Name = "updownStorageSection"; this.updownStorageSection.Size = new System.Drawing.Size(34, 20); this.updownStorageSection.TabIndex = 5; this.updownStorageSection.ValueChanged += this.updownStorageSection_ValueChanged; // //groupboxStorageSelected // this.groupboxStorageSelected.Controls.Add(this.labelStorageQuantity); this.groupboxStorageSelected.Controls.Add(this.textboxStorageLastBuy); this.groupboxStorageSelected.Controls.Add(this.textboxStorageName); this.groupboxStorageSelected.Controls.Add(this.textboxStoragePhItem); this.groupboxStorageSelected.Controls.Add(this.textboxStorageLastSell); this.groupboxStorageSelected.Controls.Add(this.labelStorageLastBuy); this.groupboxStorageSelected.Controls.Add(this.labelStorageLastSell); this.groupboxStorageSelected.Controls.Add(this.textboxStorageQuantity); this.groupboxStorageSelected.Controls.Add(this.labelStoragePhItem); this.groupboxStorageSelected.Controls.Add(this.labelStorageName); this.groupboxStorageSelected.Location = new System.Drawing.Point(6, 82); this.groupboxStorageSelected.Name = "groupboxStorageSelected"; this.groupboxStorageSelected.Size = new System.Drawing.Size(265, 142); this.groupboxStorageSelected.TabIndex = 8; this.groupboxStorageSelected.TabStop = false; this.groupboxStorageSelected.Text = "Selected Article"; // //textboxStorageLastBuy // this.textboxStorageLastBuy.Location = new System.Drawing.Point(113, 117); this.textboxStorageLastBuy.Name = "textboxStorageLastBuy"; this.textboxStorageLastBuy.Size = new System.Drawing.Size(146, 20); this.textboxStorageLastBuy.TabIndex = 3; // //textboxStorageName // this.textboxStorageName.Location = new System.Drawing.Point(113, 39); this.textboxStorageName.Name = "textboxStorageName"; this.textboxStorageName.Size = new System.Drawing.Size(146, 20); this.textboxStorageName.TabIndex = 3; // //textboxStorageLastSell // this.textboxStorageLastSell.Location = new System.Drawing.Point(113, 91); this.textboxStorageLastSell.Name = "textboxStorageLastSell"; this.textboxStorageLastSell.Size = new System.Drawing.Size(146, 20); this.textboxStorageLastSell.TabIndex = 3; // //textboxStorageQuantity // this.textboxStorageQuantity.Location = new System.Drawing.Point(113, 65); this.textboxStorageQuantity.Name = "textboxStorageQuantity"; this.textboxStorageQuantity.Size = new System.Drawing.Size(146, 20); this.textboxStorageQuantity.TabIndex = 3; // //labelStorageName // this.labelStorageName.AutoSize = true; this.labelStorageName.Location = new System.Drawing.Point(6, 42); this.labelStorageName.Name = "labelStorageName"; this.labelStorageName.Size = new System.Drawing.Size(61, 13); this.labelStorageName.TabIndex = 2; this.labelStorageName.Text = "Item Name:"; // //formItemManagement // this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(660, 254); this.Controls.Add(this.groupboxStore); this.Controls.Add(this.groupboxStorage); this.Controls.Add(this.buttonClose); this.Controls.Add(this.buttonToStorage); this.Controls.Add(this.buttonToStore); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "formItemManagement"; this.Text = "My First Store"; Load += this.formItemManagement_Load; ((System.ComponentModel.ISupportInitialize)this.updownStoreLevel).EndInit(); ((System.ComponentModel.ISupportInitialize)this.updownStoreShelf).EndInit(); ((System.ComponentModel.ISupportInitialize)this.updownStoreBin).EndInit(); this.groupboxStoreNavigation.ResumeLayout(false); this.groupboxStoreNavigation.PerformLayout(); this.groupboxStoreSelected.ResumeLayout(false); this.groupboxStoreSelected.PerformLayout(); ((System.ComponentModel.ISupportInitialize)this.updownStorePrice).EndInit(); this.groupboxStore.ResumeLayout(false); this.groupboxStorage.ResumeLayout(false); this.groupboxStorageNavigation.ResumeLayout(false); this.groupboxStorageNavigation.PerformLayout(); ((System.ComponentModel.ISupportInitialize)this.updownStorageArticle).EndInit(); ((System.ComponentModel.ISupportInitialize)this.updownStorageSection).EndInit(); this.groupboxStorageSelected.ResumeLayout(false); this.groupboxStorageSelected.PerformLayout(); this.ResumeLayout(false); } private System.Windows.Forms.Label labelStorageName; private System.Windows.Forms.TextBox textboxStorageLastSell; private System.Windows.Forms.TextBox textboxStorageName; private System.Windows.Forms.TextBox textboxStorageLastBuy; private System.Windows.Forms.Label labelStorePhItem; private System.Windows.Forms.TextBox textboxStorePhItem; private System.Windows.Forms.GroupBox groupboxStorageSelected; private System.Windows.Forms.NumericUpDown updownStorageSection; private System.Windows.Forms.Label labelStorageTotalArticle; private System.Windows.Forms.Label labelStorageTotalSection; private System.Windows.Forms.NumericUpDown updownStorageArticle; private System.Windows.Forms.Label labelStorageSection; private System.Windows.Forms.Label labelStorageArticle; private System.Windows.Forms.GroupBox groupboxStorageNavigation; private System.Windows.Forms.GroupBox groupboxStorage; private System.Windows.Forms.TextBox textboxStorageQuantity; private System.Windows.Forms.Label labelStorageLastSell; private System.Windows.Forms.Label labelStorageLastBuy; private System.Windows.Forms.Label labelStorageQuantity; private System.Windows.Forms.GroupBox groupboxStore; private System.Windows.Forms.NumericUpDown updownStorePrice; private System.Windows.Forms.Button buttonClose; private System.Windows.Forms.Button buttonToStorage; private System.Windows.Forms.Button buttonToStore; private System.Windows.Forms.Label labelStoragePhItem; private System.Windows.Forms.Label labelStoreName; private System.Windows.Forms.TextBox textboxStoragePhItem; private System.Windows.Forms.Label labelStoreQuantity; private System.Windows.Forms.TextBox textboxStoreName; private System.Windows.Forms.Label labelStorePrice; private System.Windows.Forms.TextBox textboxStoreQuantity; private System.Windows.Forms.GroupBox groupboxStoreSelected; private System.Windows.Forms.GroupBox groupboxStoreNavigation; private System.Windows.Forms.Label labelStoreBin; private System.Windows.Forms.NumericUpDown updownStoreBin; private System.Windows.Forms.Label labelStoreTotalBin; private System.Windows.Forms.Label labelStoreTotalShelf; private System.Windows.Forms.NumericUpDown updownStoreShelf; private System.Windows.Forms.Label labelStoreShelf; private System.Windows.Forms.Label labelStoreLevel; private System.Windows.Forms.NumericUpDown updownStoreLevel; private System.Windows.Forms.Label labelStoreTotalLevel; }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { [ExportLanguageService(typeof(ISyntaxFactsService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxFactsService : ISyntaxFactsService { public bool IsAwaitKeyword(SyntaxToken token) { return token.IsKind(SyntaxKind.AwaitKeyword); } public bool IsIdentifier(SyntaxToken token) { return token.IsKind(SyntaxKind.IdentifierToken); } public bool IsGlobalNamespaceKeyword(SyntaxToken token) { return token.IsKind(SyntaxKind.GlobalKeyword); } public bool IsVerbatimIdentifier(SyntaxToken token) { return token.IsVerbatimIdentifier(); } public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && token.Parent is BinaryExpressionSyntax) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsKeywordKind(kind); // both contextual and reserved keywords } public bool IsContextualKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsContextualKeyword(kind); } public bool IsPreprocessorKeyword(SyntaxToken token) { var kind = (SyntaxKind)token.RawKind; return SyntaxFacts.IsPreprocessorKeyword(kind); } public bool IsHashToken(SyntaxToken token) { return (SyntaxKind)token.RawKind == SyntaxKind.HashToken; } public bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsInInactiveRegion(position, cancellationToken); } public bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsInNonUserCode(position, cancellationToken); } public bool IsEntirelyWithinStringOrCharLiteral(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var csharpTree = syntaxTree as SyntaxTree; if (csharpTree == null) { return false; } return csharpTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective(SyntaxNode node) { return node is DirectiveTriviaSyntax; } public bool TryGetExternalSourceInfo(SyntaxNode node, out ExternalSourceInfo info) { var lineDirective = node as LineDirectiveTriviaSyntax; if (lineDirective != null) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default(ExternalSourceInfo); return false; } public bool IsRightSideOfQualifiedName(SyntaxNode node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public bool IsMemberAccessExpressionName(SyntaxNode node) { var name = node as SimpleNameSyntax; return name.IsMemberAccessExpressionName(); } public bool IsObjectCreationExpressionType(SyntaxNode node) { return node.IsParentKind(SyntaxKind.ObjectCreationExpression) && ((ObjectCreationExpressionSyntax)node.Parent).Type == node; } public bool IsAttributeName(SyntaxNode node) { return SyntaxFacts.IsAttributeName(node); } public bool IsInvocationExpression(SyntaxNode node) { return node is InvocationExpressionSyntax; } public bool IsAnonymousFunction(SyntaxNode node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsGenericName(SyntaxNode node) { return node is GenericNameSyntax; } public bool IsNamedParameter(SyntaxNode node) { return node.CheckParent<NameColonSyntax>(p => p.Name == node); } public bool IsSkippedTokensTrivia(SyntaxNode node) { return node is SkippedTokensTriviaSyntax; } public bool HasIncompleteParentMember(SyntaxNode node) { return node.IsParentKind(SyntaxKind.IncompleteMember); } public SyntaxToken GetIdentifierOfGenericName(SyntaxNode genericName) { var csharpGenericName = genericName as GenericNameSyntax; return csharpGenericName != null ? csharpGenericName.Identifier : default(SyntaxToken); } public bool IsCaseSensitive { get { return true; } } public bool IsUsingDirectiveName(SyntaxNode node) { return node.IsParentKind(SyntaxKind.UsingDirective) && ((UsingDirectiveSyntax)node.Parent).Name == node; } public bool IsForEachStatement(SyntaxNode node) { return node is ForEachStatementSyntax; } public bool IsLockStatement(SyntaxNode node) { return node is LockStatementSyntax; } public bool IsUsingStatement(SyntaxNode node) { return node is UsingStatementSyntax; } public bool IsThisConstructorInitializer(SyntaxToken token) { return token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) && ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token; } public bool IsBaseConstructorInitializer(SyntaxToken token) { return token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer) && ((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token; } public bool IsQueryExpression(SyntaxNode node) { return node is QueryExpressionSyntax; } public bool IsPredefinedType(SyntaxToken token) { PredefinedType actualType; return TryGetPredefinedType(token, out actualType) && actualType != PredefinedType.None; } public bool IsPredefinedType(SyntaxToken token, PredefinedType type) { PredefinedType actualType; return TryGetPredefinedType(token, out actualType) && actualType == type; } public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private PredefinedType GetPredefinedType(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.BoolKeyword: return PredefinedType.Boolean; case SyntaxKind.ByteKeyword: return PredefinedType.Byte; case SyntaxKind.SByteKeyword: return PredefinedType.SByte; case SyntaxKind.IntKeyword: return PredefinedType.Int32; case SyntaxKind.UIntKeyword: return PredefinedType.UInt32; case SyntaxKind.ShortKeyword: return PredefinedType.Int16; case SyntaxKind.UShortKeyword: return PredefinedType.UInt16; case SyntaxKind.LongKeyword: return PredefinedType.Int64; case SyntaxKind.ULongKeyword: return PredefinedType.UInt64; case SyntaxKind.FloatKeyword: return PredefinedType.Single; case SyntaxKind.DoubleKeyword: return PredefinedType.Double; case SyntaxKind.DecimalKeyword: return PredefinedType.Decimal; case SyntaxKind.StringKeyword: return PredefinedType.String; case SyntaxKind.CharKeyword: return PredefinedType.Char; case SyntaxKind.ObjectKeyword: return PredefinedType.Object; case SyntaxKind.VoidKeyword: return PredefinedType.Void; default: return PredefinedType.None; } } public bool IsPredefinedOperator(SyntaxToken token) { PredefinedOperator actualOperator; return TryGetPredefinedOperator(token, out actualOperator) && actualOperator != PredefinedOperator.None; } public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) { PredefinedOperator actualOperator; return TryGetPredefinedOperator(token, out actualOperator) && actualOperator == op; } public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) { return SyntaxFacts.GetText((SyntaxKind)kind); } public bool IsIdentifierStartCharacter(char c) { return SyntaxFacts.IsIdentifierStartCharacter(c); } public bool IsIdentifierPartCharacter(char c) { return SyntaxFacts.IsIdentifierPartCharacter(c); } public bool IsIdentifierEscapeCharacter(char c) { return c == '@'; } public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) { return false; } public bool IsStartOfUnicodeEscapeSequence(char c) { return c == '\\'; } public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; } return false; } public bool IsStringLiteral(SyntaxToken token) { return token.IsKind(SyntaxKind.StringLiteralToken); } public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, SyntaxNode parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration)) { declaredType = ((VariableDeclarationSyntax)typedParent.Parent).Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration)) { declaredType = ((FieldDeclarationSyntax)typedParent.Parent).Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, SyntaxNode parent) { var typedParent = parent as ExpressionSyntax; if (typedParent != null) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } return false; } public bool IsMemberAccessExpression(SyntaxNode node) { return node is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.SimpleMemberAccessExpression; } public bool IsConditionalMemberAccessExpression(SyntaxNode node) { return node is ConditionalAccessExpressionSyntax; } public bool IsPointerMemberAccessExpression(SyntaxNode node) { return node is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.PointerMemberAccessExpression; } public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity) { name = null; arity = 0; var simpleName = node as SimpleNameSyntax; if (simpleName != null) { name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } } public SyntaxNode GetExpressionOfMemberAccessExpression(SyntaxNode node) { if (node.IsKind(SyntaxKind.MemberBindingExpression)) { if (node.IsParentKind(SyntaxKind.ConditionalAccessExpression)) { return GetExpressionOfConditionalMemberAccessExpression(node.Parent); } if (node.IsParentKind(SyntaxKind.InvocationExpression) && node.Parent.IsParentKind(SyntaxKind.ConditionalAccessExpression)) { return GetExpressionOfConditionalMemberAccessExpression(node.Parent.Parent); } } return (node as MemberAccessExpressionSyntax)?.Expression; } public SyntaxNode GetExpressionOfConditionalMemberAccessExpression(SyntaxNode node) { return (node as ConditionalAccessExpressionSyntax)?.Expression; } public bool IsInStaticContext(SyntaxNode node) { return node.IsInStaticContext(); } public bool IsInNamespaceOrTypeContext(SyntaxNode node) { return SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); } public SyntaxNode GetExpressionOfArgument(SyntaxNode node) { return ((ArgumentSyntax)node).Expression; } public RefKind GetRefKindOfArgument(SyntaxNode node) { return (node as ArgumentSyntax).GetRefKind(); } public bool IsInConstantContext(SyntaxNode node) { return (node as ExpressionSyntax).IsInConstantContext(); } public bool IsInConstructor(SyntaxNode node) { return node.GetAncestor<ConstructorDeclarationSyntax>() != null; } public bool IsUnsafeContext(SyntaxNode node) { return node.IsUnsafeContext(); } public SyntaxNode GetNameOfAttribute(SyntaxNode node) { return ((AttributeSyntax)node).Name; } public bool IsAttribute(SyntaxNode node) { return node is AttributeSyntax; } public bool IsAttributeNamedArgumentIdentifier(SyntaxNode node) { var identifier = node as IdentifierNameSyntax; return identifier != null && identifier.IsParentKind(SyntaxKind.NameEquals) && identifier.Parent.IsParentKind(SyntaxKind.AttributeArgument); } public SyntaxNode GetContainingTypeDeclaration(SyntaxNode root, int position) { if (root == null) { throw new ArgumentNullException("root"); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException("position"); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode node) { throw ExceptionUtilities.Unreachable; } public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsObjectCreationExpression(SyntaxNode node) { return node is ObjectCreationExpressionSyntax; } public bool IsObjectInitializerNamedAssignmentIdentifier(SyntaxNode node) { var identifier = node as IdentifierNameSyntax; return identifier != null && identifier.IsLeftSideOfAssignExpression() && identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression); } public bool IsElementAccessExpression(SyntaxNode node) { return node.Kind() == SyntaxKind.ElementAccessExpression; } public SyntaxNode ConvertToSingleLine(SyntaxNode node) { return node.ConvertToSingleLine(); } public SyntaxToken ToIdentifierToken(string name) { return name.ToIdentifierToken(); } public SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia) { return ((ExpressionSyntax)expression).Parenthesize(includeElasticTrivia); } public bool IsIndexerMemberCRef(SyntaxNode node) { return node.Kind() == SyntaxKind.IndexerMemberCref; } public SyntaxNode GetContainingMemberDeclaration(SyntaxNode root, int position) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (node is MemberDeclarationSyntax) { return node; } node = node.Parent; } return null; } public bool IsMethodLevelMember(SyntaxNode node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers(SyntaxNode node) { return node is NamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } public bool TryGetDeclaredSymbolInfo(SyntaxNode node, out DeclaredSymbolInfo declaredSymbolInfo) { switch (node.Kind()) { case SyntaxKind.ClassDeclaration: var classDecl = (ClassDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(classDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Class, classDecl.Identifier.Span); return true; case SyntaxKind.ConstructorDeclaration: var ctorDecl = (ConstructorDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo( ctorDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Constructor, ctorDecl.Identifier.Span, parameterCount: (ushort)(ctorDecl.ParameterList?.Parameters.Count ?? 0)); return true; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(delegateDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Delegate, delegateDecl.Identifier.Span); return true; case SyntaxKind.EnumDeclaration: var enumDecl = (EnumDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(enumDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Enum, enumDecl.Identifier.Span); return true; case SyntaxKind.EnumMemberDeclaration: var enumMember = (EnumMemberDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(enumMember.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.EnumMember, enumMember.Identifier.Span); return true; case SyntaxKind.EventDeclaration: var eventDecl = (EventDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(eventDecl.Identifier.ValueText, eventDecl.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Event, eventDecl.Identifier.Span); return true; case SyntaxKind.IndexerDeclaration: var indexerDecl = (IndexerDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(WellKnownMemberNames.Indexer, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Indexer, indexerDecl.ThisKeyword.Span); return true; case SyntaxKind.InterfaceDeclaration: var interfaceDecl = (InterfaceDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(interfaceDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Interface, interfaceDecl.Identifier.Span); return true; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo( ExpandExplicitInterfaceName(method.Identifier.ValueText, method.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Method, method.Identifier.Span, parameterCount: (ushort)(method.ParameterList?.Parameters.Count ?? 0), typeParameterCount: (ushort)(method.TypeParameterList?.Parameters.Count ?? 0)); return true; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(property.Identifier.ValueText, property.ExplicitInterfaceSpecifier), GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Property, property.Identifier.Span); return true; case SyntaxKind.StructDeclaration: var structDecl = (StructDeclarationSyntax)node; declaredSymbolInfo = new DeclaredSymbolInfo(structDecl.Identifier.ValueText, GetContainerDisplayName(node.Parent), GetFullyQualifiedContainerName(node.Parent), DeclaredSymbolInfoKind.Struct, structDecl.Identifier.Span); return true; case SyntaxKind.VariableDeclarator: // could either be part of a field declaration or an event field declaration var variableDeclarator = (VariableDeclaratorSyntax)node; var variableDeclaration = variableDeclarator.Parent as VariableDeclarationSyntax; var fieldDeclaration = variableDeclaration?.Parent as BaseFieldDeclarationSyntax; if (fieldDeclaration != null) { var kind = fieldDeclaration is EventFieldDeclarationSyntax ? DeclaredSymbolInfoKind.Event : fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword) ? DeclaredSymbolInfoKind.Constant : DeclaredSymbolInfoKind.Field; declaredSymbolInfo = new DeclaredSymbolInfo(variableDeclarator.Identifier.ValueText, GetContainerDisplayName(fieldDeclaration.Parent), GetFullyQualifiedContainerName(fieldDeclaration.Parent), kind, variableDeclarator.Identifier.Span); return true; } break; } declaredSymbolInfo = default(DeclaredSymbolInfo); return false; } private static string ExpandExplicitInterfaceName(string identifier, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier) { if (explicitInterfaceSpecifier == null) { return identifier; } else { var builder = new StringBuilder(); ExpandTypeName(explicitInterfaceSpecifier.Name, builder); builder.Append('.'); builder.Append(identifier); return builder.ToString(); } } private static void ExpandTypeName(TypeSyntax type, StringBuilder builder) { switch (type.Kind()) { case SyntaxKind.AliasQualifiedName: var alias = (AliasQualifiedNameSyntax)type; builder.Append(alias.Alias.Identifier.ValueText); break; case SyntaxKind.ArrayType: var array = (ArrayTypeSyntax)type; ExpandTypeName(array.ElementType, builder); for (int i = 0; i < array.RankSpecifiers.Count; i++) { var rankSpecifier = array.RankSpecifiers[i]; builder.Append(rankSpecifier.OpenBracketToken.Text); for (int j = 1; j < rankSpecifier.Sizes.Count; j++) { builder.Append(','); } builder.Append(rankSpecifier.CloseBracketToken.Text); } break; case SyntaxKind.GenericName: var generic = (GenericNameSyntax)type; builder.Append(generic.Identifier.ValueText); if (generic.TypeArgumentList != null) { var arguments = generic.TypeArgumentList.Arguments; builder.Append(generic.TypeArgumentList.LessThanToken.Text); for (int i = 0; i < arguments.Count; i++) { if (i != 0) { builder.Append(','); } ExpandTypeName(arguments[i], builder); } builder.Append(generic.TypeArgumentList.GreaterThanToken.Text); } break; case SyntaxKind.IdentifierName: var identifierName = (IdentifierNameSyntax)type; builder.Append(identifierName.Identifier.ValueText); break; case SyntaxKind.NullableType: var nullable = (NullableTypeSyntax)type; ExpandTypeName(nullable.ElementType, builder); builder.Append(nullable.QuestionToken.Text); break; case SyntaxKind.OmittedTypeArgument: // do nothing since it was omitted, but don't reach the default block break; case SyntaxKind.PointerType: var pointer = (PointerTypeSyntax)type; ExpandTypeName(pointer.ElementType, builder); builder.Append(pointer.AsteriskToken.Text); break; case SyntaxKind.PredefinedType: var predefined = (PredefinedTypeSyntax)type; builder.Append(predefined.Keyword.Text); break; case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)type; ExpandTypeName(qualified.Left, builder); builder.Append(qualified.DotToken.Text); ExpandTypeName(qualified.Right, builder); break; default: Debug.Assert(false, "Unexpected type syntax " + type.Kind()); break; } } private static string GetContainerDisplayName(SyntaxNode node) { return GetContainer(node, immediate: true); } private static string GetFullyQualifiedContainerName(SyntaxNode node) { return GetContainer(node, immediate: false); } private static string GetContainer(SyntaxNode node, bool immediate) { var name = GetNodeName(node, includeTypeParameters: immediate); var names = new List<string> { name }; // check for nested classes and always add that to the container name. var parent = node.Parent; while (parent is TypeDeclarationSyntax) { var currentParent = (TypeDeclarationSyntax)parent; names.Add(currentParent.Identifier.ValueText + (immediate ? ExpandTypeParameterList(currentParent.TypeParameterList) : "")); parent = currentParent.Parent; } // If they're just asking for the immediate parent, then we're done. Otherwise keep // walking all the way to the root, adding the names. if (!immediate) { while (parent != null && parent.Kind() != SyntaxKind.CompilationUnit) { names.Add(GetNodeName(parent, includeTypeParameters: false)); parent = parent.Parent; } } names.Reverse(); return string.Join(".", names); } private static string GetNodeName(SyntaxNode node, bool includeTypeParameters) { string name; TypeParameterListSyntax typeParameterList; switch (node.Kind()) { case SyntaxKind.ClassDeclaration: var classDecl = (ClassDeclarationSyntax)node; name = classDecl.Identifier.ValueText; typeParameterList = classDecl.TypeParameterList; break; case SyntaxKind.CompilationUnit: return string.Empty; case SyntaxKind.DelegateDeclaration: var delegateDecl = (DelegateDeclarationSyntax)node; name = delegateDecl.Identifier.ValueText; typeParameterList = delegateDecl.TypeParameterList; break; case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)node).Identifier.ValueText; case SyntaxKind.IdentifierName: return ((IdentifierNameSyntax)node).Identifier.ValueText; case SyntaxKind.InterfaceDeclaration: var interfaceDecl = (InterfaceDeclarationSyntax)node; name = interfaceDecl.Identifier.ValueText; typeParameterList = interfaceDecl.TypeParameterList; break; case SyntaxKind.MethodDeclaration: var methodDecl = (MethodDeclarationSyntax)node; name = methodDecl.Identifier.ValueText; typeParameterList = methodDecl.TypeParameterList; break; case SyntaxKind.NamespaceDeclaration: return GetNodeName(((NamespaceDeclarationSyntax)node).Name, includeTypeParameters: false); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetNodeName(qualified.Left, includeTypeParameters: false) + "." + GetNodeName(qualified.Right, includeTypeParameters: false); case SyntaxKind.StructDeclaration: var structDecl = (StructDeclarationSyntax)node; name = structDecl.Identifier.ValueText; typeParameterList = structDecl.TypeParameterList; break; default: Debug.Assert(false, "Unexpected node type " + node.Kind()); return null; } return name + (includeTypeParameters ? ExpandTypeParameterList(typeParameterList) : ""); } private static string ExpandTypeParameterList(TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { var builder = new StringBuilder(); builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (int i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(','); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); return builder.ToString(); } else { return null; } } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode root) { var list = new List<SyntaxNode>(); AppendMethodLevelMembers(root, list); return list; } private void AppendMethodLevelMembers(SyntaxNode node, List<SyntaxNode> list) { foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { AppendMethodLevelMembers(member, list); continue; } if (IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default(TextSpan); } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default(TextSpan); } // TODO: currently we only support method for now var method = member as BaseMethodDeclarationSyntax; if (method != null) { if (method.Body == null) { return default(TextSpan); } return GetBlockBodySpan(method.Body); } return default(TextSpan); } public bool ContainsInMemberBody(SyntaxNode node, TextSpan span) { var constructor = node as ConstructorDeclarationSyntax; if (constructor != null) { return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); } var method = node as BaseMethodDeclarationSyntax; if (method != null) { return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); } var property = node as BasePropertyDeclarationSyntax; if (property != null) { return property.AccessorList != null && property.AccessorList.Span.Contains(span); } var @enum = node as EnumMemberDeclarationSyntax; if (@enum != null) { return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); } var field = node as BaseFieldDeclarationSyntax; if (field != null) { return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private TextSpan GetBlockBodySpan(BlockSyntax body) { return TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); } public int GetMethodLevelMemberId(SyntaxNode root, SyntaxNode node) { Contract.Requires(root.SyntaxTree == node.SyntaxTree); int currentId = 0; SyntaxNode currentNode; Contract.ThrowIfFalse(TryGetMethodLevelMember(root, (n, i) => n == node, ref currentId, out currentNode)); Contract.ThrowIfFalse(currentId >= 0); CheckMemberId(root, node, currentId); return currentId; } public SyntaxNode GetMethodLevelMember(SyntaxNode root, int memberId) { int currentId = 0; SyntaxNode currentNode; if (!TryGetMethodLevelMember(root, (n, i) => i == memberId, ref currentId, out currentNode)) { return null; } Contract.ThrowIfNull(currentNode); CheckMemberId(root, currentNode, memberId); return currentNode; } private bool TryGetMethodLevelMember( SyntaxNode node, Func<SyntaxNode, int, bool> predicate, ref int currentId, out SyntaxNode currentNode) { foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (TryGetMethodLevelMember(member, predicate, ref currentId, out currentNode)) { return true; } continue; } if (IsMethodLevelMember(member)) { if (predicate(member, currentId)) { currentNode = member; return true; } currentId++; } } currentNode = null; return false; } [Conditional("DEBUG")] private void CheckMemberId(SyntaxNode root, SyntaxNode node, int memberId) { var list = GetMethodLevelMembers(root); var index = list.IndexOf(node); Contract.ThrowIfFalse(index == memberId); } public SyntaxNode GetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. var memberAccess = parent as MemberAccessExpressionSyntax; if (memberAccess != null) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. var qualifiedName = parent as QualifiedNameSyntax; if (qualifiedName != null) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. var aliasQualifiedName = parent as AliasQualifiedNameSyntax; if (aliasQualifiedName != null) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. var objectCreation = parent as ObjectCreationExpressionSyntax; if (objectCreation != null) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. var name = parent as NameSyntax; if (name == null) { break; } node = parent; } return node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode root, CancellationToken cancellationToken) { var compilationUnit = root as CompilationUnitSyntax; if (compilationUnit == null) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); var constructor = member as ConstructorDeclarationSyntax; if (constructor != null) { constructors.Add(constructor); continue; } var @namespace = member as NamespaceDeclarationSyntax; if (@namespace != null) { AppendConstructors(@namespace.Members, constructors, cancellationToken); } var @class = member as ClassDeclarationSyntax; if (@class != null) { AppendConstructors(@class.Members, constructors, cancellationToken); } var @struct = member as StructDeclarationSyntax; if (@struct != null) { AppendConstructors(@struct.Members, constructors, cancellationToken); } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.Item1; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default(SyntaxToken); return false; } } }
// // Azure Media Services REST API v2 - Functions // // Shared Library // using System; using Microsoft.WindowsAzure.MediaServices.Client; using System.IO; using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure.Storage.Table; using Microsoft.Azure.WebJobs.Host; using System.Xml.Linq; namespace media_functions_for_logic_app { public class ManifestHelpers { public static Stream GenerateStreamFromString(string s) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(s); writer.Flush(); stream.Position = 0; return stream; } public class ManifestGenerated { public string FileName; public string Content; } public static ManifestGenerated LoadAndUpdateManifestTemplate(IAsset asset, Microsoft.Azure.WebJobs.ExecutionContext execContext) { var mp4AssetFiles = asset.AssetFiles.ToList().Where(f => f.Name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase)).ToArray(); var m4aAssetFiles = asset.AssetFiles.ToList().Where(f => f.Name.EndsWith(".m4a", StringComparison.OrdinalIgnoreCase)).ToArray(); var mediaAssetFiles = asset.AssetFiles.ToList().Where(f => f.Name.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase) || f.Name.EndsWith(".m4a", StringComparison.OrdinalIgnoreCase)).ToArray(); if (mediaAssetFiles.Count() != 0) { // Prepare the manifest string mp4fileuniqueaudio = null; // let's load the manifest template string manifestPath = Path.Combine(System.IO.Directory.GetParent(execContext.FunctionDirectory).FullName, "presets", "Manifest.ism"); XDocument doc = XDocument.Load(manifestPath); XNamespace ns = "http://www.w3.org/2001/SMIL20/Language"; var bodyxml = doc.Element(ns + "smil"); var body2 = bodyxml.Element(ns + "body"); var switchxml = body2.Element(ns + "switch"); // audio tracks (m4a) foreach (var file in m4aAssetFiles) { switchxml.Add(new XElement(ns + "audio", new XAttribute("src", file.Name), new XAttribute("title", Path.GetFileNameWithoutExtension(file.Name)))); } if (m4aAssetFiles.Count() == 0) { // audio track(s) var mp4AudioAssetFilesName = mp4AssetFiles.Where(f => (f.Name.ToLower().Contains("audio") && !f.Name.ToLower().Contains("video")) || (f.Name.ToLower().Contains("aac") && !f.Name.ToLower().Contains("h264")) ); var mp4AudioAssetFilesSize = mp4AssetFiles.OrderBy(f => f.ContentFileSize); string mp4fileaudio = (mp4AudioAssetFilesName.Count() == 1) ? mp4AudioAssetFilesName.FirstOrDefault().Name : mp4AudioAssetFilesSize.FirstOrDefault().Name; // if there is one file with audio or AAC in the name then let's use it for the audio track switchxml.Add(new XElement(ns + "audio", new XAttribute("src", mp4fileaudio), new XAttribute("title", "audioname"))); if (mp4AudioAssetFilesName.Count() == 1 && mediaAssetFiles.Count() > 1) //looks like there is one audio file and dome other video files { mp4fileuniqueaudio = mp4fileaudio; } } // video tracks foreach (var file in mp4AssetFiles) { if (file.Name != mp4fileuniqueaudio) // we don't put the unique audio file as a video track { switchxml.Add(new XElement(ns + "video", new XAttribute("src", file.Name))); } } // manifest filename string name = CommonPrefix(mediaAssetFiles.Select(f => Path.GetFileNameWithoutExtension(f.Name)).ToArray()); if (string.IsNullOrEmpty(name)) { name = "manifest"; } else if (name.EndsWith("_") && name.Length > 1) // i string ends with "_", let's remove it { name = name.Substring(0, name.Length - 1); } name = name + ".ism"; return new ManifestGenerated() { Content = doc.Declaration.ToString() + Environment.NewLine + doc.ToString(), FileName = name }; } else { return new ManifestGenerated() { Content = null, FileName = string.Empty }; // no mp4 in asset } } public static string CommonPrefix(string[] ss) { if (ss.Length == 0) { return ""; } if (ss.Length == 1) { return ss[0]; } int prefixLength = 0; foreach (char c in ss[0]) { foreach (string s in ss) { if (s.Length <= prefixLength || s[prefixLength] != c) { return ss[0].Substring(0, prefixLength); } } prefixLength++; } return ss[0]; // all strings identical } static public ManifestTimingData GetManifestTimingData(CloudMediaContext context, IAsset asset, TraceWriter log) // Parse the manifest and get data from it { ManifestTimingData response = new ManifestTimingData() { IsLive = false, Error = false, TimestampOffset = 0, TimestampList = new List<ulong>(), DiscontinuityDetected = false }; try { ILocator mytemplocator = null; Uri myuri = MediaServicesHelper.GetValidOnDemandURI(context, asset); if (myuri == null) { mytemplocator = MediaServicesHelper.CreatedTemporaryOnDemandLocator(asset); myuri = MediaServicesHelper.GetValidOnDemandURI(context, asset); } if (myuri != null) { log.Info($"Asset URI {myuri.ToString()}"); XDocument manifest = XDocument.Load(myuri.ToString()); //log.Info($"manifest {manifest}"); var smoothmedia = manifest.Element("SmoothStreamingMedia"); var videotrack = smoothmedia.Elements("StreamIndex").Where(a => a.Attribute("Type").Value == "video"); // TIMESCALE string timescalefrommanifest = smoothmedia.Attribute("TimeScale").Value; if (videotrack.FirstOrDefault().Attribute("TimeScale") != null) // there is timescale value in the video track. Let's take this one. { timescalefrommanifest = videotrack.FirstOrDefault().Attribute("TimeScale").Value; } ulong timescale = ulong.Parse(timescalefrommanifest); response.TimeScale = (ulong?)timescale; // Timestamp offset if (videotrack.FirstOrDefault().Element("c").Attribute("t") != null) { response.TimestampOffset = ulong.Parse(videotrack.FirstOrDefault().Element("c").Attribute("t").Value); } else { response.TimestampOffset = 0; // no timestamp, so it should be 0 } ulong totalduration = 0; ulong durationpreviouschunk = 0; ulong durationchunk; int repeatchunk; foreach (var chunk in videotrack.Elements("c")) { durationchunk = chunk.Attribute("d") != null ? ulong.Parse(chunk.Attribute("d").Value) : 0; log.Info($"duration d {durationchunk}"); repeatchunk = chunk.Attribute("r") != null ? int.Parse(chunk.Attribute("r").Value) : 1; log.Info($"repeat r {repeatchunk}"); if (chunk.Attribute("t") != null) { ulong tvalue = ulong.Parse(chunk.Attribute("t").Value); response.TimestampList.Add(tvalue); if (tvalue != response.TimestampOffset) { totalduration = tvalue - response.TimestampOffset; // Discountinuity ? We calculate the duration from the offset response.DiscontinuityDetected = true; // let's flag it } } else { response.TimestampList.Add(response.TimestampList[response.TimestampList.Count() - 1] + durationpreviouschunk); } totalduration += durationchunk * (ulong)repeatchunk; for (int i = 1; i < repeatchunk; i++) { response.TimestampList.Add(response.TimestampList[response.TimestampList.Count() - 1] + durationchunk); } durationpreviouschunk = durationchunk; } response.TimestampEndLastChunk = response.TimestampList[response.TimestampList.Count() - 1] + durationpreviouschunk; if (smoothmedia.Attribute("IsLive") != null && smoothmedia.Attribute("IsLive").Value == "TRUE") { // Live asset.... No duration to read (but we can read scaling and compute duration if no gap) response.IsLive = true; response.AssetDuration = TimeSpan.FromSeconds((double)totalduration / ((double)timescale)); } else { totalduration = ulong.Parse(smoothmedia.Attribute("Duration").Value); response.AssetDuration = TimeSpan.FromSeconds((double)totalduration / ((double)timescale)); } } else { response.Error = true; } if (mytemplocator != null) mytemplocator.Delete(); } catch (Exception ex) { response.Error = true; } return response; } public static EndTimeInTable RetrieveLastEndTime(CloudTable table, string programID) { TableOperation tableOperation = TableOperation.Retrieve<EndTimeInTable>(programID, "lastEndTime"); TableResult tableResult = table.Execute(tableOperation); return tableResult.Result as EndTimeInTable; } public static void UpdateLastEndTime(CloudTable table, TimeSpan endtime, string programId, int id, ProgramState state) { var EndTimeInTableEntity = new EndTimeInTable(); EndTimeInTableEntity.ProgramId = programId; EndTimeInTableEntity.Id = id.ToString(); EndTimeInTableEntity.ProgramState = state.ToString(); EndTimeInTableEntity.LastEndTime = endtime.ToString(); EndTimeInTableEntity.AssignPartitionKey(); EndTimeInTableEntity.AssignRowKey(); TableOperation tableOperation = TableOperation.InsertOrReplace(EndTimeInTableEntity); table.Execute(tableOperation); } public static IAsset GetAssetFromProgram(CloudMediaContext context, string programId) { IAsset asset = null; try { IProgram program = context.Programs.Where(p => p.Id == programId).FirstOrDefault(); if (program != null) { asset = program.Asset; } } catch { } return asset; } // return the exact timespan on GOP static public TimeSpan ReturnTimeSpanOnGOP(ManifestTimingData data, TimeSpan ts) { var response = ts; ulong timestamp = (ulong)(ts.TotalSeconds * data.TimeScale); int i = 0; foreach (var t in data.TimestampList) { if (t < timestamp && i < (data.TimestampList.Count - 1) && timestamp < data.TimestampList[i + 1]) { response = TimeSpan.FromSeconds((double)t / (double)data.TimeScale); break; } i++; } return response; } public class ManifestTimingData { public TimeSpan AssetDuration { get; set; } public ulong TimestampOffset { get; set; } public ulong? TimeScale { get; set; } public bool IsLive { get; set; } public bool Error { get; set; } public List<ulong> TimestampList { get; set; } public ulong TimestampEndLastChunk { get; set; } public bool DiscontinuityDetected { get; set; } } public class SubclipInfo { public TimeSpan subclipStart { get; set; } public TimeSpan subclipDuration { get; set; } public string programId { get; set; } } public class EndTimeInTable : TableEntity { private string programId; private string lastendtime; private string id; private string programState; public void AssignRowKey() { this.RowKey = "lastEndTime"; } public void AssignPartitionKey() { this.PartitionKey = programId; } public string ProgramId { get { return programId; } set { programId = value; } } public string LastEndTime { get { return lastendtime; } set { lastendtime = value; } } public string Id { get { return id; } set { id = value; } } public string ProgramState { get { return programState; } set { programState = value; } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Text; using System.Reflection; using System.Xml; using System.Xml.Serialization; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenMetaverse; using log4net; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// A new version of the old Channel class, simplified /// </summary> public class TerrainChannel : ITerrainChannel { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[TERRAIN CHANNEL]"; protected TerrainData m_terrainData; public int Width { get { return m_terrainData.SizeX; } } // X dimension // Unfortunately, for historical reasons, in this module 'Width' is X and 'Height' is Y public int Height { get { return m_terrainData.SizeY; } } // Y dimension public int Altitude { get { return m_terrainData.SizeZ; } } // Y dimension // Default, not-often-used builder public TerrainChannel() { m_terrainData = new HeightmapTerrainData((int)Constants.RegionSize, (int)Constants.RegionSize, (int)Constants.RegionHeight); FlatLand(); // PinHeadIsland(); } // Create terrain of given size public TerrainChannel(int pX, int pY) { m_terrainData = new HeightmapTerrainData(pX, pY, (int)Constants.RegionHeight); } // Create terrain of specified size and initialize with specified terrain. // TODO: join this with the terrain initializers. public TerrainChannel(String type, int pX, int pY, int pZ) { m_terrainData = new HeightmapTerrainData(pX, pY, pZ); if (type.Equals("flat")) FlatLand(); else PinHeadIsland(); } // Create channel passed a heightmap and expected dimensions of the region. // The heightmap might not fit the passed size so accomodations must be made. public TerrainChannel(double[,] pM, int pSizeX, int pSizeY, int pAltitude) { int hmSizeX = pM.GetLength(0); int hmSizeY = pM.GetLength(1); m_terrainData = new HeightmapTerrainData(pSizeX, pSizeY, pAltitude); for (int xx = 0; xx < pSizeX; xx++) for (int yy = 0; yy < pSizeY; yy++) if (xx > hmSizeX || yy > hmSizeY) m_terrainData[xx, yy] = TerrainData.DefaultTerrainHeight; else m_terrainData[xx, yy] = (float)pM[xx, yy]; } public TerrainChannel(TerrainData pTerrData) { m_terrainData = pTerrData; } #region ITerrainChannel Members // ITerrainChannel.MakeCopy() public ITerrainChannel MakeCopy() { return this.Copy(); } // ITerrainChannel.GetTerrainData() public TerrainData GetTerrainData() { return m_terrainData; } // ITerrainChannel.GetFloatsSerialized() // This one dimensional version is ordered so height = map[y*sizeX+x]; // DEPRECATED: don't use this function as it does not retain the dimensions of the terrain // and the caller will probably do the wrong thing if the terrain is not the legacy 256x256. public float[] GetFloatsSerialised() { return m_terrainData.GetFloatsSerialized(); } // ITerrainChannel.GetDoubles() public double[,] GetDoubles() { double[,] heights = new double[Width, Height]; int idx = 0; // index into serialized array for (int ii = 0; ii < Width; ii++) { for (int jj = 0; jj < Height; jj++) { heights[ii, jj] = (double)m_terrainData[ii, jj]; idx++; } } return heights; } // ITerrainChannel.this[x,y] public double this[int x, int y] { get { if (x < 0 || x >= Width || y < 0 || y >= Height) return 0; return (double)m_terrainData[x, y]; } set { if (Double.IsNaN(value) || Double.IsInfinity(value)) return; m_terrainData[x, y] = (float)value; } } // ITerrainChannel.GetHieghtAtXYZ(x, y, z) public float GetHeightAtXYZ(float x, float y, float z) { if (x < 0 || x >= Width || y < 0 || y >= Height) return 0; return m_terrainData[(int)x, (int)y]; } // ITerrainChannel.Tainted() public bool Tainted(int x, int y) { return m_terrainData.IsTaintedAt(x, y); } // ITerrainChannel.SaveToXmlString() public string SaveToXmlString() { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Util.UTF8; using (StringWriter sw = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sw, settings)) { WriteXml(writer); } string output = sw.ToString(); return output; } } // ITerrainChannel.LoadFromXmlString() public void LoadFromXmlString(string data) { using(StringReader sr = new StringReader(data)) { using(XmlTextReader reader = new XmlTextReader(sr)) ReadXml(reader); } } // ITerrainChannel.Merge public void Merge(ITerrainChannel newTerrain, Vector3 displacement, float radianRotation, Vector2 rotationDisplacement) { m_log.DebugFormat("{0} Merge. inSize=<{1},{2}>, disp={3}, rot={4}, rotDisp={5}, outSize=<{6},{7}>", LogHeader, newTerrain.Width, newTerrain.Height, displacement, radianRotation, rotationDisplacement, m_terrainData.SizeX, m_terrainData.SizeY); for (int xx = 0; xx < newTerrain.Width; xx++) { for (int yy = 0; yy < newTerrain.Height; yy++) { int dispX = (int)displacement.X; int dispY = (int)displacement.Y; float newHeight = (float)newTerrain[xx, yy] + displacement.Z; if (radianRotation == 0) { // If no rotation, place the new height in the specified location dispX += xx; dispY += yy; if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY) { m_terrainData[dispX, dispY] = newHeight; } } else { // If rotating, we have to smooth the result because the conversion // to ints will mean heightmap entries will not get changed // First compute the rotation location for the new height. dispX += (int)(rotationDisplacement.X + ((float)xx - rotationDisplacement.X) * Math.Cos(radianRotation) - ((float)yy - rotationDisplacement.Y) * Math.Sin(radianRotation) ); dispY += (int)(rotationDisplacement.Y + ((float)xx - rotationDisplacement.X) * Math.Sin(radianRotation) + ((float)yy - rotationDisplacement.Y) * Math.Cos(radianRotation) ); if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY) { float oldHeight = m_terrainData[dispX, dispY]; // Smooth the heights around this location if the old height is far from this one for (int sxx = dispX - 2; sxx < dispX + 2; sxx++) { for (int syy = dispY - 2; syy < dispY + 2; syy++) { if (sxx >= 0 && sxx < m_terrainData.SizeX && syy >= 0 && syy < m_terrainData.SizeY) { if (sxx == dispX && syy == dispY) { // Set height for the exact rotated point m_terrainData[dispX, dispY] = newHeight; } else { if (Math.Abs(m_terrainData[sxx, syy] - newHeight) > 1f) { // If the adjacent height is far off, force it to this height m_terrainData[sxx, syy] = newHeight; } } } } } } if (dispX >= 0 && dispX < m_terrainData.SizeX && dispY >= 0 && dispY < m_terrainData.SizeY) { m_terrainData[dispX, dispY] = (float)newTerrain[xx, yy]; } } } } } /// <summary> /// A new version of terrain merge that processes the terrain in a specific order and corrects the problems with rotated terrains /// having 'holes' in that need to be smoothed. The correct way to rotate something is to iterate over the target, taking data from /// the source, not the other way around. This ensures that the target has no holes in it. /// The processing order of an incoming terrain is: /// 1. Apply rotation /// 2. Apply bounding rectangle /// 3. Apply displacement /// rotationCenter is no longer needed and has been discarded. /// </summary> /// <param name="newTerrain"></param> /// <param name="displacement">&lt;x, y, z&gt;</param> /// <param name="rotationDegrees"></param> /// <param name="boundingOrigin">&lt;x, y&gt;</param> /// <param name="boundingSize">&lt;x, y&gt;</param> public void MergeWithBounding(ITerrainChannel newTerrain, Vector3 displacement, float rotationDegrees, Vector2 boundingOrigin, Vector2 boundingSize) { m_log.DebugFormat("{0} MergeWithBounding: inSize=<{1},{2}>, rot={3}, boundingOrigin={4}, boundingSize={5}, disp={6}, outSize=<{7},{8}>", LogHeader, newTerrain.Width, newTerrain.Height, rotationDegrees, boundingOrigin.ToString(), boundingSize.ToString(), displacement, m_terrainData.SizeX, m_terrainData.SizeY); // get the size of the incoming terrain int baseX = newTerrain.Width; int baseY = newTerrain.Height; // create an intermediate terrain map that is 25% bigger on each side that we can work with to handle rotation int offsetX = baseX / 4; // the original origin will now be at these coordinates so now we can have imaginary negative coordinates ;) int offsetY = baseY / 4; int tmpX = baseX + baseX / 2; int tmpY = baseY + baseY / 2; int centreX = tmpX / 2; int centreY = tmpY / 2; TerrainData terrain_tmp = new HeightmapTerrainData(tmpX, tmpY, (int)Constants.RegionHeight); for (int xx = 0; xx < tmpX; xx++) for (int yy = 0; yy < tmpY; yy++) terrain_tmp[xx, yy] = -65535f; //use this height like an 'alpha' mask channel double radianRotation = Math.PI * rotationDegrees / 180f; double cosR = Math.Cos(radianRotation); double sinR = Math.Sin(radianRotation); if (rotationDegrees < 0f) rotationDegrees += 360f; //-90=270 -180=180 -270=90 // So first we apply the rotation to the incoming terrain, storing the result in terrain_tmp // We special case orthogonal rotations for accuracy because even using double precision math, Math.Cos(90 degrees) is never fully 0 // and we can never rotate around a centre 'pixel' because the 'bitmap' size is always even int x, y, sx, sy; for (y = 0; y <= tmpY; y++) { for (x = 0; x <= tmpX; x++) { if (rotationDegrees == 0f) { sx = x - offsetX; sy = y - offsetY; } else if (rotationDegrees == 90f) { sx = y - offsetX; sy = tmpY - 1 - x - offsetY; } else if (rotationDegrees == 180f) { sx = tmpX - 1 - x - offsetX; sy = tmpY - 1 - y - offsetY; } else if (rotationDegrees == 270f) { sx = tmpX - 1 - y - offsetX; sy = x - offsetY; } else { // arbitary rotation: hmmm should I be using (centreX - 0.5) and (centreY - 0.5) and round cosR and sinR to say only 5 decimal places? sx = centreX + (int)Math.Round((((double)x - centreX) * cosR) + (((double)y - centreY) * sinR)) - offsetX; sy = centreY + (int)Math.Round((((double)y - centreY) * cosR) - (((double)x - centreX) * sinR)) - offsetY; } if (sx >= 0 && sx < baseX && sy >= 0 && sy < baseY) { try { terrain_tmp[x, y] = (float)newTerrain[sx, sy]; } catch (Exception) //just in case we've still not taken care of every way the arrays might go out of bounds! ;) { m_log.DebugFormat("{0} MergeWithBounding - Rotate: Out of Bounds sx={1} sy={2} dx={3} dy={4}", sx, sy, x, y); } } } } // We could also incorporate the next steps, bounding-rectangle and displacement in the loop above, but it's simpler to visualise if done separately // and will also make it much easier when later I want the option for maybe a circular or oval bounding shape too ;). int newX = m_terrainData.SizeX; int newY = m_terrainData.SizeY; // displacement is relative to <0,0> in the destination region and defines where the origin of the data selected by the bounding-rectangle is placed int dispX = (int)Math.Floor(displacement.X); int dispY = (int)Math.Floor(displacement.Y); // startX/Y and endX/Y are coordinates in bitmap_tmp int startX = (int)Math.Floor(boundingOrigin.X) + offsetX; if (startX > tmpX) startX = tmpX; if (startX < 0) startX = 0; int startY = (int)Math.Floor(boundingOrigin.Y) + offsetY; if (startY > tmpY) startY = tmpY; if (startY < 0) startY = 0; int endX = (int)Math.Floor(boundingOrigin.X + boundingSize.X) + offsetX; if (endX > tmpX) endX = tmpX; if (endX < 0) endX = 0; int endY = (int)Math.Floor(boundingOrigin.Y + boundingSize.Y) + offsetY; if (endY > tmpY) endY = tmpY; if (endY < 0) endY = 0; //m_log.DebugFormat("{0} MergeWithBounding: inSize=<{1},{2}>, disp=<{3},{4}> rot={5}, offset=<{6},{7}>, boundingStart=<{8},{9}>, boundingEnd=<{10},{11}>, cosR={12}, sinR={13}, outSize=<{14},{15}>", LogHeader, // baseX, baseY, dispX, dispY, radianRotation, offsetX, offsetY, startX, startY, endX, endY, cosR, sinR, newX, newY); int dx, dy; for (y = startY; y < endY; y++) { for (x = startX; x < endX; x++) { dx = x - startX + dispX; dy = y - startY + dispY; if (dx >= 0 && dx < newX && dy >= 0 && dy < newY) { try { float newHeight = (float)terrain_tmp[x, y]; //use 'alpha' mask if (newHeight != -65535f) m_terrainData[dx, dy] = newHeight + displacement.Z; } catch (Exception) //just in case we've still not taken care of every way the arrays might go out of bounds! ;) { m_log.DebugFormat("{0} MergeWithBounding - Bound & Displace: Out of Bounds sx={1} sy={2} dx={3} dy={4}", x, y, dx, dy); } } } } } #endregion public TerrainChannel Copy() { TerrainChannel copy = new TerrainChannel(); copy.m_terrainData = m_terrainData.Clone(); return copy; } private void WriteXml(XmlWriter writer) { if (Width == Constants.RegionSize && Height == Constants.RegionSize) { // Downward compatibility for legacy region terrain maps. // If region is exactly legacy size, return the old format XML. writer.WriteStartElement(String.Empty, "TerrainMap", String.Empty); ToXml(writer); writer.WriteEndElement(); } else { // New format XML that includes width and length. writer.WriteStartElement(String.Empty, "TerrainMap2", String.Empty); ToXml2(writer); writer.WriteEndElement(); } } private void ReadXml(XmlReader reader) { // Check the first element. If legacy element, use the legacy reader. if (reader.IsStartElement("TerrainMap")) { reader.ReadStartElement("TerrainMap"); FromXml(reader); } else { reader.ReadStartElement("TerrainMap2"); FromXml2(reader); } } // Write legacy terrain map. Presumed to be 256x256 of data encoded as floats in a byte array. private void ToXml(XmlWriter xmlWriter) { float[] mapData = GetFloatsSerialised(); byte[] buffer = new byte[mapData.Length * 4]; for (int i = 0; i < mapData.Length; i++) { byte[] value = BitConverter.GetBytes(mapData[i]); Array.Copy(value, 0, buffer, (i * 4), 4); } XmlSerializer serializer = new XmlSerializer(typeof(byte[])); serializer.Serialize(xmlWriter, buffer); } // Read legacy terrain map. Presumed to be 256x256 of data encoded as floats in a byte array. private void FromXml(XmlReader xmlReader) { XmlSerializer serializer = new XmlSerializer(typeof(byte[])); byte[] dataArray = (byte[])serializer.Deserialize(xmlReader); int index = 0; m_terrainData = new HeightmapTerrainData(Height, Width, (int)Constants.RegionHeight); for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { float value; value = BitConverter.ToSingle(dataArray, index); index += 4; this[x, y] = (double)value; } } } private class TerrainChannelXMLPackage { public int Version; public int SizeX; public int SizeY; public int SizeZ; public float CompressionFactor; public float[] Map; public TerrainChannelXMLPackage(int pX, int pY, int pZ, float pCompressionFactor, float[] pMap) { Version = 1; SizeX = pX; SizeY = pY; SizeZ = pZ; CompressionFactor = pCompressionFactor; Map = pMap; } } // New terrain serialization format that includes the width and length. private void ToXml2(XmlWriter xmlWriter) { TerrainChannelXMLPackage package = new TerrainChannelXMLPackage(Width, Height, Altitude, m_terrainData.CompressionFactor, m_terrainData.GetCompressedMap()); XmlSerializer serializer = new XmlSerializer(typeof(TerrainChannelXMLPackage)); serializer.Serialize(xmlWriter, package); } // New terrain serialization format that includes the width and length. private void FromXml2(XmlReader xmlReader) { XmlSerializer serializer = new XmlSerializer(typeof(TerrainChannelXMLPackage)); TerrainChannelXMLPackage package = (TerrainChannelXMLPackage)serializer.Deserialize(xmlReader); m_terrainData = new HeightmapTerrainData(package.Map, package.CompressionFactor, package.SizeX, package.SizeY, package.SizeZ); } // Fill the heightmap with the center bump terrain private void PinHeadIsland() { float cx = m_terrainData.SizeX * 0.5f; float cy = m_terrainData.SizeY * 0.5f; float h; for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { // h = (float)TerrainUtil.PerlinNoise2D(x, y, 2, 0.125) * 10; h = 1.0f; float spherFacA = (float)(TerrainUtil.SphericalFactor(x, y, cx, cy, 50) * 0.01d); float spherFacB = (float)(TerrainUtil.SphericalFactor(x, y, cx, cy, 100) * 0.001d); if (h < spherFacA) h = spherFacA; if (h < spherFacB) h = spherFacB; m_terrainData[x, y] = h; } } } private void FlatLand() { m_terrainData.ClearLand(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection.DefinedTypeTests.Data; // Need to disable warning related to CLS Compliance as using Array as cusom attribute is not CLS compliant #pragma warning disable 3016 [assembly: Attr(77, name = "AttrSimple"), Int32Attr(77, name = "Int32AttrSimple"), Int64Attr((Int64)77, name = "Int64AttrSimple"), StringAttr("hello", name = "StringAttrSimple"), EnumAttr(MyColorEnum.RED, name = "EnumAttrSimple"), TypeAttr(typeof(Object), name = "TypeAttrSimple") ] namespace System.Reflection.DefinedTypeTests.Data { public enum MyColorEnum { RED = 1, BLUE = 2, GREEN = 3 } public class Util { public static string ObjectToString(Object o) { string s = string.Empty; if (o != null) { if (o is Array) { Array a = (Array)o; for (int i = 0; i < a.Length; i += 1) { if (i > 0) { s = s + ", "; } if (a.GetValue(i) is Array) s = s + Util.ObjectToString((Array)a.GetValue(i)); else s = s + a.GetValue(i).ToString(); } } else s = s + o.ToString(); } return s; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class Attr : Attribute { public Attr(int i) { value = i; sValue = null; } public Attr(int i, string s) { value = i; sValue = s; } public override string ToString() { return "Attr ToString : " + value.ToString() + " " + sValue; } public string name; public int value; public string sValue; } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class Int32Attr : Attribute { public Int32Attr(int i) { value = i; arrayValue = null; } public Int32Attr(int i, int[] a) { value = i; arrayValue = a; } public string name; public readonly int value; public int field; public readonly int[] arrayValue; public int[] arrayField; private int _property = 0; public int property { get { return _property; } set { _property = value; } } private int[] _arrayProperty; public int[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } } public override string ToString() { return GetType().ToString() + " - name : " + name + "; value : " + Util.ObjectToString(value) + "; field : " + Util.ObjectToString(field) + "; property : " + Util.ObjectToString(property) + "; array value : " + Util.ObjectToString(arrayValue) + "; array field : " + Util.ObjectToString(arrayField) + "; array property : " + Util.ObjectToString(arrayProperty); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class Int64Attr : Attribute { public Int64Attr(long l) { value = l; arrayValue = null; } public Int64Attr(long l, long[] a) { value = l; arrayValue = a; } public string name; public readonly long value; public long field; public readonly long[] arrayValue; public long[] arrayField; private long _property = 0; public long property { get { return _property; } set { _property = value; } } private long[] _arrayProperty; public long[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } } public override string ToString() { return GetType().ToString() + " - name : " + name + "; value : " + Util.ObjectToString(value) + "; field : " + Util.ObjectToString(field) + "; property : " + Util.ObjectToString(property) + "; array value : " + Util.ObjectToString(arrayValue) + "; array field : " + Util.ObjectToString(arrayField) + "; array property : " + Util.ObjectToString(arrayProperty); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class EnumAttr : Attribute { public EnumAttr(MyColorEnum e) { value = e; arrayValue = null; } public EnumAttr(MyColorEnum e, MyColorEnum[] a) { value = e; arrayValue = a; } public string name; public readonly MyColorEnum value; public MyColorEnum field; public readonly MyColorEnum[] arrayValue; public MyColorEnum[] arrayField; private MyColorEnum _property = 0; public MyColorEnum property { get { return _property; } set { _property = value; } } private MyColorEnum[] _arrayProperty; public MyColorEnum[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } } public override string ToString() { return GetType().ToString() + " - name : " + name + "; value : " + Util.ObjectToString(value) + "; field : " + Util.ObjectToString(field) + "; property : " + Util.ObjectToString(property) + "; array value : " + Util.ObjectToString(arrayValue) + "; array field : " + Util.ObjectToString(arrayField) + "; array property : " + Util.ObjectToString(arrayProperty); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class StringAttr : Attribute { public StringAttr(string s) { value = s; arrayValue = null; } public StringAttr(string s, string[] a) { value = s; arrayValue = a; } public string name; public readonly string value; public string field; public readonly string[] arrayValue; public string[] arrayField; private string _property; public string property { get { return _property; } set { _property = value; } } private string[] _arrayProperty; public string[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } } public override string ToString() { return GetType().ToString() + " - name : " + name + "; value : " + Util.ObjectToString(value) + "; field : " + Util.ObjectToString(field) + "; property : " + Util.ObjectToString(property) + "; array value : " + Util.ObjectToString(arrayValue) + "; array field : " + Util.ObjectToString(arrayField) + "; array property : " + Util.ObjectToString(arrayProperty); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class TypeAttr : Attribute { public TypeAttr(Type t) { value = t; arrayValue = null; } public TypeAttr(Type t, Type[] a) { value = t; arrayValue = a; } public string name; public readonly Type value; public Type field; public readonly Type[] arrayValue; public Type[] arrayField; private Type _property; public Type property { get { return _property; } set { _property = value; } } private Type[] _arrayProperty; public Type[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } } public override string ToString() { return GetType().ToString() + " - name : " + name + "; value : " + Util.ObjectToString(value) + "; field : " + Util.ObjectToString(field) + "; property : " + Util.ObjectToString(property) + "; array value : " + Util.ObjectToString(arrayValue) + "; array field : " + Util.ObjectToString(arrayField) + "; array property : " + Util.ObjectToString(arrayProperty); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class ObjectAttr : Attribute { public ObjectAttr(Object v) { value = v; arrayValue = null; } public ObjectAttr(Object v, Object[] a) { value = v; arrayValue = a; } public string name; public readonly Object value; public Object field; public readonly Object[] arrayValue; public Object[] arrayField; private Object _property = 0; public Object property { get { return _property; } set { _property = value; } } private Object[] _arrayProperty; public Object[] arrayProperty { get { return _arrayProperty; } set { _arrayProperty = value; } } public override string ToString() { return GetType().ToString() + " - name : " + name + "; value : " + Util.ObjectToString(value) + "; field : " + Util.ObjectToString(field) + "; property : " + Util.ObjectToString(property) + "; array value : " + Util.ObjectToString(arrayValue) + "; array field : " + Util.ObjectToString(arrayField) + "; array property : " + Util.ObjectToString(arrayProperty); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] public class NullAttr : Attribute { public NullAttr(string s, Type t, int[] a) { } public NullAttr(String s) { } public string name; public string stringField; public Type typeField; public int[] arrayField; public string stringProperty { get { return null; } set { } } public Type typeProperty { get { return null; } set { } } public int[] arrayProperty { get { return null; } set { } } } } namespace System.Reflection.Tests { public class DefinedTypeTests { //Negative Test for Attribute of type System.Int32 [Fact] public void Test_DefinedTypeInt32() { Assert.False(IsTypeDefined(typeof(System.Int32))); } //Negative Test for Attribute of type ObsoleteAttribute [Fact] public void Test_DefinedTypeObsAttr() { Assert.False(IsTypeDefined(typeof(ObsoleteAttribute))); } //Test for Attribute of type System.Reflection.DefinedTypeTests.Data.Attr [Fact] public void Test_DefinedTypeAttr() { Assert.True(IsTypeDefined(typeof(System.Reflection.DefinedTypeTests.Data.Attr))); } //Test for Attribute of type System.Reflection.DefinedTypeTests.Data.Int32Attr [Fact] public void Test_DefinedTypeInt32Attr() { Assert.True(IsTypeDefined(typeof(System.Reflection.DefinedTypeTests.Data.Int32Attr))); } //Test for Attribute of type System.Reflection.DefinedTypeTests.Data.Int64Attr [Fact] public void Test_DefinedTypeInt64Attr() { Assert.True(IsTypeDefined(typeof(System.Reflection.DefinedTypeTests.Data.Int64Attr))); } //Test for Attribute of type System.Reflection.DefinedTypeTests.Data.StringAttr [Fact] public void Test_DefinedTypeStringAttr() { Assert.True(IsTypeDefined(typeof(System.Reflection.DefinedTypeTests.Data.StringAttr))); } //Test for Attribute of type System.Reflection.DefinedTypeTests.Data.EnumAttr [Fact] public void Test_DefinedTypeEnumAttr() { Assert.True(IsTypeDefined(typeof(System.Reflection.DefinedTypeTests.Data.EnumAttr))); } //Test for Attribute of type System.Reflection.DefinedTypeTests.Data.TypeAttr [Fact] public void Test_DefinedType_TypeAttr() { Assert.True(IsTypeDefined(typeof(System.Reflection.DefinedTypeTests.Data.TypeAttr))); } //Test for Attribute of type System.Reflection.DefinedTypeTests.Data.ObjectAttr [Fact] public void Test_DefinedTypeObjectAttr() { Assert.True(IsTypeDefined(typeof(System.Reflection.DefinedTypeTests.Data.ObjectAttr))); } //Test for Attribute of type System.Reflection.DefinedTypeTests.Data.NullAttr [Fact] public void Test_DefinedTypeNullAttr() { Assert.True(IsTypeDefined(typeof(System.Reflection.DefinedTypeTests.Data.NullAttr))); } private static bool IsTypeDefined(Type type) { bool typeDefined = false; Assembly asm = GetExecutingAssembly(); IEnumerator<TypeInfo> alldefinedTypes = asm.DefinedTypes.GetEnumerator(); TypeInfo ti = null; while (alldefinedTypes.MoveNext()) { ti = alldefinedTypes.Current; if (ti.AsType().Equals(type)) { //found type typeDefined = true; break; } } return typeDefined; } private static Assembly GetExecutingAssembly() { Assembly asm = null; Type t = typeof(DefinedTypeTests); TypeInfo ti = t.GetTypeInfo(); asm = ti.Assembly; return asm; } } }
// 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. // ----------------------------------------------------------------------------- // The following code is a port of SpriteBatch from DirectXTk // http://go.microsoft.com/fwlink/?LinkId=248929 // ----------------------------------------------------------------------------- // Microsoft Public License (Ms-PL) // // This license governs use of the accompanying software. If you use the // software, you accept this license. If you do not accept the license, do not // use the software. // // 1. Definitions // The terms "reproduce," "reproduction," "derivative works," and // "distribution" have the same meaning here as under U.S. copyright law. // A "contribution" is the original software, or any additions or changes to // the software. // A "contributor" is any person that distributes its contribution under this // license. // "Licensed patents" are a contributor's patent claims that read directly on // its contribution. // // 2. Grant of Rights // (A) Copyright Grant- Subject to the terms of this license, including the // license conditions and limitations in section 3, each contributor grants // you a non-exclusive, worldwide, royalty-free copyright license to reproduce // its contribution, prepare derivative works of its contribution, and // distribute its contribution or any derivative works that you create. // (B) Patent Grant- Subject to the terms of this license, including the license // conditions and limitations in section 3, each contributor grants you a // non-exclusive, worldwide, royalty-free license under its licensed patents to // make, have made, use, sell, offer for sale, import, and/or otherwise dispose // of its contribution in the software or derivative works of the contribution // in the software. // // 3. Conditions and Limitations // (A) No Trademark License- This license does not grant you rights to use any // contributors' name, logo, or trademarks. // (B) If you bring a patent claim against any contributor over patents that // you claim are infringed by the software, your patent license from such // contributor to the software ends automatically. // (C) If you distribute any portion of the software, you must retain all // copyright, patent, trademark, and attribution notices that are present in the // software. // (D) If you distribute any portion of the software in source code form, you // may do so only under this license by including a complete copy of this // license with your distribution. If you distribute any portion of the software // in compiled or object code form, you may only do so under a license that // complies with this license. // (E) The software is licensed "as-is." You bear the risk of using it. The // contributors give no express warranties, guarantees or conditions. You may // have additional consumer rights under your local laws which this license // cannot change. To the extent permitted under your local laws, the // contributors exclude the implied warranties of merchantability, fitness for a // particular purpose and non-infringement. //-------------------------------------------------------------------- using System; using SharpDX.Direct3D; namespace SharpDX.Toolkit.Graphics { /// <summary> /// Primitive batch implementation using generic. /// </summary> /// <typeparam name="T">Type of a Vertex element</typeparam> public class PrimitiveBatch<T> : PrimitiveBatchBase where T : struct { const int DefaultBatchSize = 2048; /// <summary> /// The quad indices /// </summary> private static readonly short[] QuadIndices = new short[] { 0, 1, 2, 0, 2, 3 }; private readonly VertexInputLayout vertexInputLayout; /// <summary> /// Initializes a new instance of the <see cref="PrimitiveBatch{T}" /> class. /// </summary> /// <param name="graphicsDevice">The device.</param> /// <param name="maxIndices">The max indices.</param> /// <param name="maxVertices">The max vertices.</param> public PrimitiveBatch(GraphicsDevice graphicsDevice, int maxIndices = DefaultBatchSize * 3, int maxVertices = DefaultBatchSize) : base(graphicsDevice, maxIndices, maxVertices, Utilities.SizeOf<T>()) { var vertexElements = VertexElement.FromType<T>(); // If the type has some VertexElement description, we can use them directly to setup the vertex input layout. if (vertexElements != null) { vertexInputLayout = VertexInputLayout.New(0, vertexElements); } } public override void Begin() { base.Begin(); // Setup the Vertex Input layout if we have one. if (vertexInputLayout != null) { GraphicsDevice.SetVertexInputLayout(vertexInputLayout); } } /// <summary> /// Draws vertices for the specified topology. /// </summary> /// <param name="topology">The topology.</param> /// <param name="vertices">The vertices.</param> public unsafe void Draw(PrimitiveType topology, T[] vertices) { var mappedVertices = Draw(topology, false, IntPtr.Zero, 0, vertices.Length); Utilities.Pin(vertices, ptr => { Utilities.CopyMemory(mappedVertices, ptr, vertices.Length * VertexSize) ; }); } /// <summary> /// Draws the indexed vertices with the specified topology. /// </summary> /// <param name="topology">The topology.</param> /// <param name="indices">The indices.</param> /// <param name="vertices">The vertices.</param> public unsafe void DrawIndexed(PrimitiveType topology, short[] indices, T[] vertices) { Utilities.Pin(indices, indicesPtr => { var mappedVertices = Draw(topology, true, indicesPtr, indices.Length, vertices.Length); Utilities.Pin(vertices, verticesPtr => { Utilities.CopyMemory(mappedVertices, verticesPtr, vertices.Length * VertexSize) ; }); }); } /// <summary> /// Draws a line. /// </summary> /// <param name="v1">The v1 starting point.</param> /// <param name="v2">The v2 end point.</param> public unsafe void DrawLine(T v1, T v2) { var mappedVertices = Draw(PrimitiveTopology.LineList, false, IntPtr.Zero, 0, 2); Utilities.Write(mappedVertices, ref v1); Utilities.Write(new IntPtr((byte*)mappedVertices + VertexSize), ref v2); } /// <summary> /// Draws a triangle (points must be ordered in CW or CCW depending on rasterizer settings). /// </summary> /// <param name="v1">The v1.</param> /// <param name="v2">The v2.</param> /// <param name="v3">The v3.</param> public unsafe void DrawTriangle(T v1, T v2, T v3) { var mappedVertices = Draw(PrimitiveTopology.TriangleList, false, IntPtr.Zero, 0, 3); Utilities.Write(mappedVertices, ref v1); Utilities.Write(new IntPtr((byte*)mappedVertices + VertexSize), ref v2); Utilities.Write(new IntPtr((byte*)mappedVertices + VertexSize + VertexSize), ref v3); } /// <summary> /// Draws a quad (points must be ordered in CW or CCW depending on rasterizer settings). /// </summary> /// <param name="v1">The v1.</param> /// <param name="v2">The v2.</param> /// <param name="v3">The v3.</param> /// <param name="v4">The v4.</param> public unsafe void DrawQuad(T v1, T v2, T v3, T v4) { Utilities.Pin(QuadIndices, ptr => { var mappedVertices = (byte*)Draw(PrimitiveTopology.TriangleList, true, ptr, 6, 4); Utilities.Write((IntPtr)mappedVertices, ref v1); mappedVertices += VertexSize; Utilities.Write((IntPtr)mappedVertices, ref v2); mappedVertices += VertexSize; Utilities.Write((IntPtr)mappedVertices, ref v3); mappedVertices += VertexSize; Utilities.Write((IntPtr)mappedVertices, ref v4); }); } } }
// 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.Diagnostics; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions.Interpreter { internal abstract class SubInstruction : Instruction { private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "Sub"; } } private SubInstruction() { } internal sealed class SubInt32 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(unchecked((Int32)l - (Int32)r)); } frame.StackIndex--; return +1; } } internal sealed class SubInt16 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((Int16)((Int16)l - (Int16)r)); } frame.StackIndex--; return +1; } } internal sealed class SubInt64 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((Int64)((Int64)l - (Int64)r)); } frame.StackIndex--; return +1; } } internal sealed class SubUInt16 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((UInt16)((UInt16)l - (UInt16)r)); } frame.StackIndex--; return +1; } } internal sealed class SubUInt32 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((UInt32)((UInt32)l - (UInt32)r)); } frame.StackIndex--; return +1; } } internal sealed class SubUInt64 : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = unchecked((UInt64)((UInt64)l - (UInt64)r)); } frame.StackIndex--; return +1; } } internal sealed class SubSingle : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Single)((Single)l - (Single)r); } frame.StackIndex--; return +1; } } internal sealed class SubDouble : SubInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Double)l - (Double)r; } frame.StackIndex--; return +1; } } public static Instruction Create(Type type) { Debug.Assert(!type.GetTypeInfo().IsEnum); switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(TypeUtils.GetNonNullableType(type))) { case TypeCode.Int16: return s_int16 ?? (s_int16 = new SubInt16()); case TypeCode.Int32: return s_int32 ?? (s_int32 = new SubInt32()); case TypeCode.Int64: return s_int64 ?? (s_int64 = new SubInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubUInt64()); case TypeCode.Single: return s_single ?? (s_single = new SubSingle()); case TypeCode.Double: return s_double ?? (s_double = new SubDouble()); default: throw Error.ExpressionNotSupportedForType("Sub", type); } } public override string ToString() { return "Sub()"; } } internal abstract class SubOvfInstruction : Instruction { private static Instruction s_int16,s_int32,s_int64,s_UInt16,s_UInt32,s_UInt64,s_single,s_double; public override int ConsumedStack { get { return 2; } } public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "SubOvf"; } } private SubOvfInstruction() { } internal sealed class SubOvfInt32 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = ScriptingRuntimeHelpers.Int32ToObject(checked((Int32)l - (Int32)r)); } frame.StackIndex--; return +1; } } internal sealed class SubOvfInt16 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((Int16)((Int16)l - (Int16)r)); } frame.StackIndex--; return +1; } } internal sealed class SubOvfInt64 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((Int64)((Int64)l - (Int64)r)); } frame.StackIndex--; return +1; } } internal sealed class SubOvfUInt16 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((UInt16)((UInt16)l - (UInt16)r)); } frame.StackIndex--; return +1; } } internal sealed class SubOvfUInt32 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((UInt32)((UInt32)l - (UInt32)r)); } frame.StackIndex--; return +1; } } internal sealed class SubOvfUInt64 : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = checked((UInt64)((UInt64)l - (UInt64)r)); } frame.StackIndex--; return +1; } } internal sealed class SubOvfSingle : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Single)((Single)l - (Single)r); } frame.StackIndex--; return +1; } } internal sealed class SubOvfDouble : SubOvfInstruction { public override int Run(InterpretedFrame frame) { object l = frame.Data[frame.StackIndex - 2]; object r = frame.Data[frame.StackIndex - 1]; if (l == null || r == null) { frame.Data[frame.StackIndex - 2] = null; } else { frame.Data[frame.StackIndex - 2] = (Double)l - (Double)r; } frame.StackIndex--; return +1; } } public static Instruction Create(Type type) { Debug.Assert(!type.GetTypeInfo().IsEnum); switch (System.Dynamic.Utils.TypeExtensions.GetTypeCode(TypeUtils.GetNonNullableType(type))) { case TypeCode.Int16: return s_int16 ?? (s_int16 = new SubOvfInt16()); case TypeCode.Int32: return s_int32 ?? (s_int32 = new SubOvfInt32()); case TypeCode.Int64: return s_int64 ?? (s_int64 = new SubOvfInt64()); case TypeCode.UInt16: return s_UInt16 ?? (s_UInt16 = new SubOvfUInt16()); case TypeCode.UInt32: return s_UInt32 ?? (s_UInt32 = new SubOvfUInt32()); case TypeCode.UInt64: return s_UInt64 ?? (s_UInt64 = new SubOvfUInt64()); case TypeCode.Single: return s_single ?? (s_single = new SubOvfSingle()); case TypeCode.Double: return s_double ?? (s_double = new SubOvfDouble()); default: throw Error.ExpressionNotSupportedForType("SubOvf", type); } } public override string ToString() { return "SubOvf()"; } } }
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; namespace PlaneGame { /// <summary> /// Aeroplane controller computes the plane's behavior basing on user input. This isn't necessarily a physically /// accurate model, but ought to feel believable while being fun on short distance flights. /// </summary> [RequireComponent(typeof(Rigidbody))] public class AeroplaneController : MonoBehaviour { [SerializeField] private float m_MaxEnginePower = 40f; // The maximum output of the engine. [SerializeField] private float m_Lift = 0.002f; // The amount of lift generated by the aeroplane moving forwards. [SerializeField] private float m_ZeroLiftSpeed = 300; // The speed at which lift is no longer applied. [SerializeField] private float m_StallSpeed = 24; [SerializeField] private float m_RollEffect = 1f; // The strength of effect for roll input. [SerializeField] private float m_PitchEffect = 1f; // The strength of effect for pitch input. [SerializeField] private float m_YawEffect = 0.2f; // The strength of effect for yaw input. [SerializeField] private float m_BankedTurnEffect = 0.5f; // The amount of turn from doing a banked turn. [SerializeField] private float m_AerodynamicEffect = 0.02f; // How much aerodynamics affect the speed of the aeroplane. [SerializeField] private float m_AutoTurnPitch = 0.5f; // How much the aeroplane automatically pitches when in a banked turn. [SerializeField] private float m_AutoRollLevel = 0.2f; // How much the aeroplane tries to level when not rolling. [SerializeField] private float m_AutoPitchLevel = 0.2f; // How much the aeroplane tries to level when not pitching. [SerializeField] private float m_AirBrakesEffect = 3f; // How much the air brakes effect the drag. [SerializeField] private float m_WheelBrakesTorque = 50f; [SerializeField] private float m_ThrottleChangeSpeed = 0.3f; // The speed with which the throttle changes. [SerializeField] private float m_DragIncreaseFactor = 0.001f; // how much drag should increase with speed. [SerializeField] private float m_FlapsChangeSpeed = 0.1f; [SerializeField] private float m_MaxNoseWheelAngle = 45f; [SerializeField] private List<WheelCollider> m_SteeredWheels; // List of wheels to which steering is applied. [SerializeField] private List<WheelCollider> m_BrakedWheels; // List of wheels to which brake force is applied. private GameObject m_GameManager; private float m_OriginalDrag; // The drag when the scene starts. private float m_OriginalAngularDrag; // The angular drag when the scene starts. private float m_AeroFactor; private bool m_Immobilized = false; // used for making the plane uncontrollable, i.e. if it has been hit or crashed. private float m_BankedTurnAmount; private Rigidbody m_Rigidbody; WheelCollider[] m_WheelColliders; // Necessary mostly for debug output public float Altitude { get; private set; } public float Throttle { get; private set; } public bool AirBrakes { get; private set; } public float WheelBrakes { get; private set; } public float Flaps { get; private set; } public float ForwardSpeed { get; private set; } // How fast the aeroplane is traveling in it's forward direction. public float EnginePower { get; private set; } // How much power the engine is being given. public float MaxEnginePower{ get { return m_MaxEnginePower; } } // The maximum output of the engine. public float RollAngle { get; private set; } public float PitchAngle { get; private set; } public float RollInput { get; private set; } public float PitchInput { get; private set; } public float YawInput { get; private set; } public float ThrottleInput { get; private set; } public float FlapsInput { get; private set; } public Transform CenterOfMass; private void Start () { m_GameManager = GameObject.Find("GameManager"); m_Rigidbody = GetComponent<Rigidbody> (); m_Rigidbody.centerOfMass = CenterOfMass.localPosition; // Store original drag settings, these are modified during flight. m_OriginalDrag = m_Rigidbody.drag; m_OriginalAngularDrag = m_Rigidbody.angularDrag; m_WheelColliders = transform.GetComponentsInChildren<WheelCollider> (); // Override flaps to "always extended" Flaps = 1.0f; } public void Move (float rollInput, float pitchInput, float yawInput, float throttleInput, float flapsInput, bool airBrakes, float wheelBrakes) { // transfer input parameters into properties.s RollInput = rollInput; PitchInput = pitchInput; YawInput = yawInput; ThrottleInput = throttleInput; FlapsInput = flapsInput; AirBrakes = airBrakes; WheelBrakes = wheelBrakes; ClampInputs (); CalculateRollAndPitchAngles (); AutoLevel (); CalculateForwardSpeed (); ControlThrottle (); ControlFlaps (); CalculateDrag (); CalculateAerodynamicEffect (); CalculateLinearForces (); CalculateTorque (); CalculateAltitude (); UpdateWheels (); ExecuteEvents.Execute<IGUIUpdateTarget>(m_GameManager, null, (t, y) => (t.UpdateSpeed(ForwardSpeed))); // Draw a line that helps determine necessary runway lengths. // bool grounded = false; // foreach (WheelCollider w in m_WheelColliders) { // if (w.isGrounded) { // grounded = true; // m_LineEnd = transform.position; // } // } // if (!grounded) { // Debug.Log ((m_LineEnd - m_LineStart).magnitude); // } // Debug.DrawLine (m_LineStart, m_LineEnd, Color.green); } private void ClampInputs () { // clamp the inputs to -1 to 1 range RollInput = Mathf.Clamp (RollInput, -1, 1); PitchInput = Mathf.Clamp (PitchInput, -1, 1); YawInput = Mathf.Clamp (YawInput, -1, 1); ThrottleInput = Mathf.Clamp (ThrottleInput, 0, 1); } private void CalculateRollAndPitchAngles () { // Calculate roll & pitch angles // Calculate the flat forward direction (with no y component). var flatForward = transform.forward; flatForward.y = 0; // If the flat forward vector is non-zero (which would only happen if the plane was pointing exactly straight upwards) if (flatForward.sqrMagnitude > 0) { flatForward.Normalize (); // calculate current pitch angle var localFlatForward = transform.InverseTransformDirection (flatForward); PitchAngle = Mathf.Atan2 (localFlatForward.y, localFlatForward.z); // calculate current roll angle var flatRight = Vector3.Cross (Vector3.up, flatForward); var localFlatRight = transform.InverseTransformDirection (flatRight); RollAngle = Mathf.Atan2 (localFlatRight.y, localFlatRight.x); } } private void AutoLevel () { // The banked turn amount (between -1 and 1) is the sine of the roll angle. // this is an amount applied to elevator input if the user is only using the banking controls, // because that's what people expect to happen in games! m_BankedTurnAmount = Mathf.Sin (RollAngle); // auto level roll, if there's no roll input: // if (RollInput == 0f) { // RollInput = -RollAngle * m_AutoRollLevel; // } // auto correct pitch, if no pitch input (but also apply the banked turn amount) if (PitchInput == 0f) { // Always tend to pitch straight into the airstream // We're borrowing the pitch angle calculation from CalculateRollAndPitchAngles here. Vector3 actualDir = m_Rigidbody.velocity; // In contrast to the direction the plane is heading in! actualDir.Normalize (); Vector3 localActualDir = transform.InverseTransformDirection (actualDir); PitchInput = -Mathf.Atan2 (localActualDir.y, localActualDir.z) * m_AutoPitchLevel; PitchInput -= Mathf.Abs (m_BankedTurnAmount * m_BankedTurnAmount * m_AutoTurnPitch); } } private void CalculateForwardSpeed () { // Forward speed is the speed in the planes's forward direction (not the same as its velocity, eg if falling in a stall) var localVelocity = transform.InverseTransformDirection (m_Rigidbody.velocity); ForwardSpeed = Mathf.Max (0, localVelocity.z); } private void ControlThrottle () { // Adjust throttle based on throttle input (or immobilized state) Throttle = Mathf.Clamp01 (Mathf.Lerp (Throttle, ThrottleInput, m_ThrottleChangeSpeed * Time.deltaTime)); // Throttle = Mathf.Clamp01 (Throttle + ThrottleInput * Time.deltaTime * m_ThrottleChangeSpeed); // current engine power is just: EnginePower = Throttle * m_MaxEnginePower; ExecuteEvents.Execute<IGUIUpdateTarget>(m_GameManager, null, (t, y) => (t.UpdateThrottle(ThrottleInput))); } private void ControlFlaps () { Flaps = Mathf.Clamp01 (Mathf.Lerp (Flaps, FlapsInput, m_FlapsChangeSpeed * Time.deltaTime)); ExecuteEvents.Execute<IGUIUpdateTarget>(m_GameManager, null, (t, y) => (t.UpdateEngineThrottle(FlapsInput))); } private void CalculateDrag () { // increase the drag based on speed, since a constant drag doesn't seem "Real" (tm) enough float extraDrag = m_Rigidbody.velocity.magnitude * m_DragIncreaseFactor; // Air brakes work by directly modifying drag. This part is actually pretty realistic! m_Rigidbody.drag = (AirBrakes ? (m_OriginalDrag + extraDrag) * m_AirBrakesEffect : m_OriginalDrag + extraDrag); // Forward speed affects angular drag - at high forward speed, it's much harder for the plane to spin m_Rigidbody.angularDrag = m_OriginalAngularDrag * ForwardSpeed; } private void CalculateAerodynamicEffect () { // "Aerodynamic" calculations. This is a very simple approximation of the effect that a plane // will naturally try to align itself in the direction that it's facing when moving at speed. // Without this, the plane would behave a bit like the asteroids spaceship! if (m_Rigidbody.velocity.magnitude > 0) { // compare the direction we're pointing with the direction we're moving: m_AeroFactor = Vector3.Dot (transform.forward, m_Rigidbody.velocity.normalized); // Simulate stalling by decreasing the aero factor below stall (zero lift) speed m_AeroFactor *= Mathf.Lerp (0, 1, Mathf.Clamp01 (ForwardSpeed / m_ZeroLiftSpeed)); // multipled by itself results in a desirable rolloff curve of the effect m_AeroFactor *= m_AeroFactor; // Finally we calculate a new velocity by bending the current velocity direction towards // the the direction the plane is facing, by an amount based on this aeroFactor var newVelocity = Vector3.Lerp (m_Rigidbody.velocity, transform.forward * ForwardSpeed, m_AeroFactor * ForwardSpeed * m_AerodynamicEffect * Time.deltaTime); m_Rigidbody.velocity = newVelocity; // also rotate the plane towards the direction of movement - this should be a very small effect, but // means the plane ends up pointing downwards in a stall m_Rigidbody.rotation = Quaternion.Slerp (m_Rigidbody.rotation, Quaternion.LookRotation (m_Rigidbody.velocity, transform.up), m_AerodynamicEffect * Time.deltaTime); } } private void CalculateLinearForces () { // Now calculate forces acting on the aeroplane: // we accumulate forces into this variable: var forces = Vector3.zero; // Add the engine power in the forward direction forces += EnginePower * transform.forward; // The direction that the lift force is applied is at right angles to the plane's velocity (usually, this is 'up'!) var liftDirection = Vector3.Cross (m_Rigidbody.velocity, transform.right).normalized; // The amount of lift drops off as the plane increases speed - in reality this occurs as the pilot retracts the flaps // shortly after takeoff, giving the plane less drag, but less lift. Because we don't simulate flaps, this is // a simple way of doing it automatically: // var zeroLiftFactor = Mathf.InverseLerp (m_ZeroLiftSpeed, 0, ForwardSpeed); // Divisions are expensive, but I don't care at this point :) var dynamicStallSpeed = m_StallSpeed - Flaps * (m_StallSpeed / 2.0f); var stallFactor = Mathf.Clamp01 (Mathf.InverseLerp (dynamicStallSpeed - 10, dynamicStallSpeed, ForwardSpeed)); // Calculate and add the lift power var liftPower = ForwardSpeed/* * ForwardSpeed*/ * m_Lift/* * zeroLiftFactor*/ * stallFactor * m_AeroFactor; forces += liftPower * liftDirection; // Apply the calculated forces to the the Rigidbody m_Rigidbody.AddForce (forces); } private void CalculateTorque () { // We accumulate torque forces into this variable: var torque = Vector3.zero; // Add torque for the pitch based on the pitch input. torque += PitchInput * m_PitchEffect * transform.right; // Add torque for the yaw based on the yaw input. torque += YawInput * m_YawEffect * transform.up; // Add torque for the roll based on the roll input. torque += -RollInput * m_RollEffect * transform.forward; // Add torque for banked turning. torque += m_BankedTurnAmount * m_BankedTurnEffect * transform.up; // The total torque is multiplied by the forward speed, so the controls have more effect at high speed, // and little effect at low speed, or when not moving in the direction of the nose of the plane // (i.e. falling while stalled) m_Rigidbody.AddTorque (torque * ForwardSpeed * m_AeroFactor); } private void CalculateAltitude () { // Altitude calculations - we raycast downwards from the aeroplane // starting a safe distance below the plane to avoid colliding with any of the plane's own colliders // var ray = new Ray (transform.position - Vector3.up * 2, -Vector3.up); // RaycastHit hit; // Altitude = Physics.Raycast (ray, out hit) ? hit.distance + 2 : transform.position.y; // ExecuteEvents.Execute<IGUIUpdateTarget>(m_Canvas, null, (t, y) => (t.UpdateAltitude(Altitude))); // Why are we even doing this raycast complexity? ExecuteEvents.Execute<IGUIUpdateTarget>(m_GameManager, null, (t, y) => (t.UpdateAltitude(transform.position.y))); } private void UpdateWheels () { // Allow the wheels to sleep if the plane is not moving. // TODO Wheels don't seem to go to sleep as expected. // TODO Does this conflict with RigidbodyDragger? foreach (var wheel in m_WheelColliders) { if (Throttle > 0.001f) { wheel.motorTorque = 0.0001f; } else { wheel.motorTorque = 0; } } foreach (WheelCollider wheel in m_SteeredWheels) { wheel.steerAngle = m_MaxNoseWheelAngle * YawInput; } foreach (WheelCollider wheel in m_BrakedWheels) { wheel.brakeTorque = m_WheelBrakesTorque * WheelBrakes; } } // Immobilize can be called from other objects, for example if this plane is hit by a weapon and should become uncontrollable public void Immobilize () { m_Immobilized = true; } // Reset is called via the ObjectResetter script, if present. public void Reset () { m_Immobilized = false; } } }
/* * 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.Collections.Specialized; using System.Reflection; using Nwc.XmlRpc; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; /*************************************************************************** * Simian Data Map * =============== * * OwnerID -> Type -> Key * ----------------------- * * UserID -> Group -> ActiveGroup * + GroupID * * UserID -> GroupSessionDropped -> GroupID * UserID -> GroupSessionInvited -> GroupID * * UserID -> GroupMember -> GroupID * + SelectedRoleID [UUID] * + AcceptNotices [bool] * + ListInProfile [bool] * + Contribution [int] * * UserID -> GroupRole[GroupID] -> RoleID * * * GroupID -> Group -> GroupName * + Charter * + ShowInList * + InsigniaID * + MembershipFee * + OpenEnrollment * + AllowPublish * + MaturePublish * + FounderID * + EveryonePowers * + OwnerRoleID * + OwnersPowers * * GroupID -> GroupRole -> RoleID * + Name * + Description * + Title * + Powers * * GroupID -> GroupMemberInvite -> InviteID * + AgentID * + RoleID * * GroupID -> GroupNotice -> NoticeID * + TimeStamp [uint] * + FromName [string] * + Subject [string] * + Message [string] * + BinaryBucket [byte[]] * * */ namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class SimianGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome | GroupPowers.Accountable | GroupPowers.JoinChat | GroupPowers.AllowVoiceChat | GroupPowers.ReceiveNotices | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; // Would this be cleaner as (GroupPowers)ulong.MaxValue; public const GroupPowers m_DefaultOwnerPowers = GroupPowers.Accountable | GroupPowers.AllowEditLand | GroupPowers.AllowFly | GroupPowers.AllowLandmark | GroupPowers.AllowRez | GroupPowers.AllowSetHome | GroupPowers.AllowVoiceChat | GroupPowers.AssignMember | GroupPowers.AssignMemberLimited | GroupPowers.ChangeActions | GroupPowers.ChangeIdentity | GroupPowers.ChangeMedia | GroupPowers.ChangeOptions | GroupPowers.CreateRole | GroupPowers.DeedObject | GroupPowers.DeleteRole | GroupPowers.Eject | GroupPowers.FindPlaces | GroupPowers.Invite | GroupPowers.JoinChat | GroupPowers.LandChangeIdentity | GroupPowers.LandDeed | GroupPowers.LandDivideJoin | GroupPowers.LandEdit | GroupPowers.LandEjectAndFreeze | GroupPowers.LandGardening | GroupPowers.LandManageAllowed | GroupPowers.LandManageBanned | GroupPowers.LandManagePasses | GroupPowers.LandOptions | GroupPowers.LandRelease | GroupPowers.LandSetSale | GroupPowers.ModerateChat | GroupPowers.ObjectManipulate | GroupPowers.ObjectSetForSale | GroupPowers.ReceiveNotices | GroupPowers.RemoveMember | GroupPowers.ReturnGroupOwned | GroupPowers.ReturnGroupSet | GroupPowers.ReturnNonGroup | GroupPowers.RoleProperties | GroupPowers.SendNotices | GroupPowers.SetLandingPoint | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; private bool m_connectorEnabled = false; private string m_groupsServerURI = string.Empty; private bool m_debugEnabled = false; private ExpiringCache<string, OSDMap> m_memoryCache; private int m_cacheTimeout = 30; // private IUserAccountService m_accountService = null; #region IRegionModuleBase Members public string Name { get { return "SimianGroupsServicesConnector"; } } // this module is not intended to be replaced, but there should only be 1 of them. public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { // if groups aren't enabled, we're not needed. // if we're not specified as the connector to use, then we're not wanted if ((groupsConfig.GetBoolean("Enabled", false) == false) || (groupsConfig.GetString("ServicesConnectorModule", "Default") != Name)) { m_connectorEnabled = false; return; } m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR]: Initializing {0}", this.Name); m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", string.Empty); if ((m_groupsServerURI == null) || (m_groupsServerURI == string.Empty)) { m_log.ErrorFormat("Please specify a valid Simian Server for GroupsServerURI in OpenSim.ini, [Groups]"); m_connectorEnabled = false; return; } m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30); if (m_cacheTimeout == 0) { m_log.WarnFormat("[SIMIAN-GROUPS-CONNECTOR] Groups Cache Disabled."); } else { m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Groups Cache Timeout set to {0}.", m_cacheTimeout); } m_memoryCache = new ExpiringCache<string,OSDMap>(); // If we got all the config options we need, lets start'er'up m_connectorEnabled = true; m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true); } } public void Close() { m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR]: Closing {0}", this.Name); } public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene) { if (m_connectorEnabled) { scene.RegisterModuleInterface<IGroupsServicesConnector>(this); } } public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene) { if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this) { scene.UnregisterModuleInterface<IGroupsServicesConnector>(this); } } public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene) { // TODO: May want to consider listenning for Agent Connections so we can pre-cache group info // scene.EventManager.OnNewClient += OnNewClient; } #endregion #region ISharedRegionModule Members public void PostInitialise() { // NoOp } #endregion #region IGroupsServicesConnector Members /// <summary> /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role. /// </summary> public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); UUID GroupID = UUID.Random(); UUID OwnerRoleID = UUID.Random(); OSDMap GroupInfoMap = new OSDMap(); GroupInfoMap["Charter"] = OSD.FromString(charter); GroupInfoMap["ShowInList"] = OSD.FromBoolean(showInList); GroupInfoMap["InsigniaID"] = OSD.FromUUID(insigniaID); GroupInfoMap["MembershipFee"] = OSD.FromInteger(0); GroupInfoMap["OpenEnrollment"] = OSD.FromBoolean(openEnrollment); GroupInfoMap["AllowPublish"] = OSD.FromBoolean(allowPublish); GroupInfoMap["MaturePublish"] = OSD.FromBoolean(maturePublish); GroupInfoMap["FounderID"] = OSD.FromUUID(founderID); GroupInfoMap["EveryonePowers"] = OSD.FromULong((ulong)m_DefaultEveryonePowers); GroupInfoMap["OwnerRoleID"] = OSD.FromUUID(OwnerRoleID); GroupInfoMap["OwnersPowers"] = OSD.FromULong((ulong)m_DefaultOwnerPowers); if(SimianAddGeneric(GroupID, "Group", name, GroupInfoMap)) { AddGroupRole(requestingAgentID, GroupID, UUID.Zero, "Everyone", "Members of " + name, "Member of " + name, (ulong)m_DefaultEveryonePowers); AddGroupRole(requestingAgentID, GroupID, OwnerRoleID, "Owners", "Owners of " + name, "Owner of " + name, (ulong)m_DefaultOwnerPowers); AddAgentToGroup(requestingAgentID, requestingAgentID, GroupID, OwnerRoleID); return GroupID; } else { return UUID.Zero; } } public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: Check to make sure requestingAgentID has permission to update group string GroupName; OSDMap GroupInfoMap; if( SimianGetFirstGenericEntry(groupID, "GroupInfo", out GroupName, out GroupInfoMap) ) { GroupInfoMap["Charter"] = OSD.FromString(charter); GroupInfoMap["ShowInList"] = OSD.FromBoolean(showInList); GroupInfoMap["InsigniaID"] = OSD.FromUUID(insigniaID); GroupInfoMap["MembershipFee"] = OSD.FromInteger(0); GroupInfoMap["OpenEnrollment"] = OSD.FromBoolean(openEnrollment); GroupInfoMap["AllowPublish"] = OSD.FromBoolean(allowPublish); GroupInfoMap["MaturePublish"] = OSD.FromBoolean(maturePublish); SimianAddGeneric(groupID, "Group", GroupName, GroupInfoMap); } } public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap GroupRoleInfo = new OSDMap(); GroupRoleInfo["Name"] = OSD.FromString(name); GroupRoleInfo["Description"] = OSD.FromString(description); GroupRoleInfo["Title"] = OSD.FromString(title); GroupRoleInfo["Powers"] = OSD.FromULong((ulong)powers); // TODO: Add security, make sure that requestingAgentID has permision to add roles SimianAddGeneric(groupID, "GroupRole", roleID.ToString(), GroupRoleInfo); } public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: Add security // Can't delete the Everyone Role if (roleID != UUID.Zero) { // Remove all GroupRole Members from Role Dictionary<UUID, OSDMap> GroupRoleMembers; string GroupRoleMemberType = "GroupRole" + groupID.ToString(); if (SimianGetGenericEntries(GroupRoleMemberType, roleID.ToString(), out GroupRoleMembers)) { foreach(UUID UserID in GroupRoleMembers.Keys) { EnsureRoleNotSelectedByMember(groupID, roleID, UserID); SimianRemoveGenericEntry(UserID, GroupRoleMemberType, roleID.ToString()); } } // Remove role SimianRemoveGenericEntry(groupID, "GroupRole", roleID.ToString()); } } public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // TODO: Security, check that requestingAgentID is allowed to update group roles OSDMap GroupRoleInfo; if (SimianGetGenericEntry(groupID, "GroupRole", roleID.ToString(), out GroupRoleInfo)) { if (name != null) { GroupRoleInfo["Name"] = OSD.FromString(name); } if (description != null) { GroupRoleInfo["Description"] = OSD.FromString(description); } if (title != null) { GroupRoleInfo["Title"] = OSD.FromString(title); } GroupRoleInfo["Powers"] = OSD.FromULong((ulong)powers); } SimianAddGeneric(groupID, "GroupRole", roleID.ToString(), GroupRoleInfo); } public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID groupID, string groupName) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap GroupInfoMap = null; if (groupID != UUID.Zero) { if (!SimianGetFirstGenericEntry(groupID, "Group", out groupName, out GroupInfoMap)) { return null; } } else if ((groupName != null) && (groupName != string.Empty)) { if (!SimianGetFirstGenericEntry("Group", groupName, out groupID, out GroupInfoMap)) { return null; } } GroupRecord GroupInfo = new GroupRecord(); GroupInfo.GroupID = groupID; GroupInfo.GroupName = groupName; GroupInfo.Charter = GroupInfoMap["Charter"].AsString(); GroupInfo.ShowInList = GroupInfoMap["ShowInList"].AsBoolean(); GroupInfo.GroupPicture = GroupInfoMap["InsigniaID"].AsUUID(); GroupInfo.MembershipFee = GroupInfoMap["MembershipFee"].AsInteger(); GroupInfo.OpenEnrollment = GroupInfoMap["OpenEnrollment"].AsBoolean(); GroupInfo.AllowPublish = GroupInfoMap["AllowPublish"].AsBoolean(); GroupInfo.MaturePublish = GroupInfoMap["MaturePublish"].AsBoolean(); GroupInfo.FounderID = GroupInfoMap["FounderID"].AsUUID(); GroupInfo.OwnerRoleID = GroupInfoMap["OwnerRoleID"].AsUUID(); return GroupInfo; } public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID groupID, UUID memberID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap groupProfile; string groupName; if (!SimianGetFirstGenericEntry(groupID, "Group", out groupName, out groupProfile)) { // GroupProfileData is not nullable return new GroupProfileData(); } GroupProfileData MemberGroupProfile = new GroupProfileData(); MemberGroupProfile.GroupID = groupID; MemberGroupProfile.Name = groupName; if (groupProfile["Charter"] != null) { MemberGroupProfile.Charter = groupProfile["Charter"].AsString(); } MemberGroupProfile.ShowInList = groupProfile["ShowInList"].AsString() == "1"; MemberGroupProfile.InsigniaID = groupProfile["InsigniaID"].AsUUID(); MemberGroupProfile.MembershipFee = groupProfile["MembershipFee"].AsInteger(); MemberGroupProfile.OpenEnrollment = groupProfile["OpenEnrollment"].AsBoolean(); MemberGroupProfile.AllowPublish = groupProfile["AllowPublish"].AsBoolean(); MemberGroupProfile.MaturePublish = groupProfile["MaturePublish"].AsBoolean(); MemberGroupProfile.FounderID = groupProfile["FounderID"].AsUUID();; MemberGroupProfile.OwnerRole = groupProfile["OwnerRoleID"].AsUUID(); Dictionary<UUID, OSDMap> Members; if (SimianGetGenericEntries("GroupMember",groupID.ToString(), out Members)) { MemberGroupProfile.GroupMembershipCount = Members.Count; } Dictionary<string, OSDMap> Roles; if (SimianGetGenericEntries(groupID, "GroupRole", out Roles)) { MemberGroupProfile.GroupRolesCount = Roles.Count; } // TODO: Get Group Money balance from somewhere // group.Money = 0; GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, memberID, groupID); MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle; MemberGroupProfile.PowersMask = MemberInfo.GroupPowers; return MemberGroupProfile; } public void SetAgentActiveGroup(UUID requestingAgentID, UUID agentID, UUID groupID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap ActiveGroup = new OSDMap(); ActiveGroup.Add("GroupID", OSD.FromUUID(groupID)); SimianAddGeneric(agentID, "Group", "ActiveGroup", ActiveGroup); } public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap GroupMemberInfo; if (!SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out GroupMemberInfo)) { GroupMemberInfo = new OSDMap(); } GroupMemberInfo["SelectedRoleID"] = OSD.FromUUID(roleID); SimianAddGeneric(agentID, "GroupMember", groupID.ToString(), GroupMemberInfo); } public void SetAgentGroupInfo(UUID requestingAgentID, UUID agentID, UUID groupID, bool acceptNotices, bool listInProfile) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap GroupMemberInfo; if (!SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out GroupMemberInfo)) { GroupMemberInfo = new OSDMap(); } GroupMemberInfo["AcceptNotices"] = OSD.FromBoolean(acceptNotices); GroupMemberInfo["ListInProfile"] = OSD.FromBoolean(listInProfile); GroupMemberInfo["Contribution"] = OSD.FromInteger(0); GroupMemberInfo["SelectedRole"] = OSD.FromUUID(UUID.Zero); SimianAddGeneric(agentID, "GroupMember", groupID.ToString(), GroupMemberInfo); } public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap Invite = new OSDMap(); Invite["AgentID"] = OSD.FromUUID(agentID); Invite["RoleID"] = OSD.FromUUID(roleID); SimianAddGeneric(groupID, "GroupMemberInvite", inviteID.ToString(), Invite); } public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap GroupMemberInvite; UUID GroupID; if (!SimianGetFirstGenericEntry("GroupMemberInvite", inviteID.ToString(), out GroupID, out GroupMemberInvite)) { return null; } GroupInviteInfo inviteInfo = new GroupInviteInfo(); inviteInfo.InviteID = inviteID; inviteInfo.GroupID = GroupID; inviteInfo.AgentID = GroupMemberInvite["AgentID"].AsUUID(); inviteInfo.RoleID = GroupMemberInvite["RoleID"].AsUUID(); return inviteInfo; } public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupInviteInfo invite = GetAgentToGroupInvite(requestingAgentID, inviteID); SimianRemoveGenericEntry(invite.GroupID, "GroupMemberInvite", inviteID.ToString()); } public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Setup Agent/Group information SetAgentGroupInfo(requestingAgentID, AgentID, GroupID, true, true); // Add agent to Everyone Group AddAgentToGroupRole(requestingAgentID, AgentID, GroupID, UUID.Zero); // Add agent to Specified Role AddAgentToGroupRole(requestingAgentID, AgentID, GroupID, RoleID); // Set selected role in this group to specified role SetAgentActiveGroupRole(requestingAgentID, AgentID, GroupID, RoleID); } public void RemoveAgentFromGroup(UUID requestingAgentID, UUID agentID, UUID groupID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // If current active group is the group the agent is being removed from, change their group to UUID.Zero GroupMembershipData memberActiveMembership = GetAgentActiveMembership(requestingAgentID, agentID); if (memberActiveMembership.GroupID == groupID) { SetAgentActiveGroup(agentID, agentID, UUID.Zero); } // Remove Group Member information for this group SimianRemoveGenericEntry(agentID, "GroupMember", groupID.ToString()); // By using a Simian Generics Type consisting of a prefix and a groupID, // combined with RoleID as key allows us to get a list of roles a particular member // of a group is assigned to. string GroupRoleMemberType = "GroupRole" + groupID.ToString(); // Take Agent out of all other group roles Dictionary<string, OSDMap> GroupRoles; if (SimianGetGenericEntries(agentID, GroupRoleMemberType, out GroupRoles)) { foreach (string roleID in GroupRoles.Keys) { SimianRemoveGenericEntry(agentID, GroupRoleMemberType, roleID); } } } public void AddAgentToGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); SimianAddGeneric(agentID, "GroupRole" + groupID.ToString(), roleID.ToString(), new OSDMap()); } public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID agentID, UUID groupID, UUID roleID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // Cannot remove members from the Everyone Role if (roleID != UUID.Zero) { EnsureRoleNotSelectedByMember(groupID, roleID, agentID); string GroupRoleMemberType = "GroupRole" + groupID.ToString(); SimianRemoveGenericEntry(agentID, GroupRoleMemberType, roleID.ToString()); } } public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>(); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetGenerics" }, { "Type", "Group" }, { "Key", search }, { "Fuzzy", "1" } }; OSDMap response = CachedPostRequest(requestArgs); if (response["Success"].AsBoolean() && response["Entries"] is OSDArray) { OSDArray entryArray = (OSDArray)response["Entries"]; foreach (OSDMap entryMap in entryArray) { DirGroupsReplyData data = new DirGroupsReplyData(); data.groupID = entryMap["OwnerID"].AsUUID(); data.groupName = entryMap["Key"].AsString(); // TODO: is there a better way to do this? Dictionary<UUID, OSDMap> Members; if (SimianGetGenericEntries("GroupMember", data.groupID.ToString(), out Members)) { data.members = Members.Count; } else { data.members = 0; } // TODO: sort results? // data.searchOrder = order; findings.Add(data); } } return findings; } public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID agentID, UUID groupID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); GroupMembershipData data = new GroupMembershipData(); /////////////////////////////// // Agent Specific Information: // OSDMap UserActiveGroup; if (SimianGetGenericEntry(agentID, "Group", "ActiveGroup", out UserActiveGroup)) { data.Active = UserActiveGroup["GroupID"].AsUUID().Equals(groupID); } OSDMap UserGroupMemberInfo; if( SimianGetGenericEntry(agentID, "GroupMember", groupID.ToString(), out UserGroupMemberInfo) ) { data.AcceptNotices = UserGroupMemberInfo["AcceptNotices"].AsBoolean(); data.Contribution = UserGroupMemberInfo["Contribution"].AsInteger(); data.ListInProfile = UserGroupMemberInfo["ListInProfile"].AsBoolean(); data.ActiveRole = UserGroupMemberInfo["SelectedRoleID"].AsUUID(); /////////////////////////////// // Role Specific Information: // OSDMap GroupRoleInfo; if( SimianGetGenericEntry(groupID, "GroupRole", data.ActiveRole.ToString(), out GroupRoleInfo) ) { data.GroupTitle = GroupRoleInfo["Title"].AsString(); data.GroupPowers = GroupRoleInfo["Powers"].AsULong(); } } /////////////////////////////// // Group Specific Information: // OSDMap GroupInfo; string GroupName; if( SimianGetFirstGenericEntry(groupID, "Group", out GroupName, out GroupInfo) ) { data.GroupID = groupID; data.AllowPublish = GroupInfo["AllowPublish"].AsBoolean(); data.Charter = GroupInfo["Charter"].AsString(); data.FounderID = GroupInfo["FounderID"].AsUUID(); data.GroupName = GroupName; data.GroupPicture = GroupInfo["InsigniaID"].AsUUID(); data.MaturePublish = GroupInfo["MaturePublish"].AsBoolean(); data.MembershipFee = GroupInfo["MembershipFee"].AsInteger(); data.OpenEnrollment = GroupInfo["OpenEnrollment"].AsBoolean(); data.ShowInList = GroupInfo["ShowInList"].AsBoolean(); } return data; } public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID agentID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); UUID GroupID = UUID.Zero; OSDMap UserActiveGroup; if (SimianGetGenericEntry(agentID, "Group", "ActiveGroup", out UserActiveGroup)) { GroupID = UserActiveGroup["GroupID"].AsUUID(); } if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Active GroupID : {0}", GroupID.ToString()); return GetAgentGroupMembership(requestingAgentID, agentID, GroupID); } public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID agentID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupMembershipData> memberships = new List<GroupMembershipData>(); Dictionary<string,OSDMap> GroupMemberShips; if (SimianGetGenericEntries(agentID, "GroupMember", out GroupMemberShips)) { foreach (string key in GroupMemberShips.Keys) { memberships.Add(GetAgentGroupMembership(requestingAgentID, agentID, UUID.Parse(key))); } } return memberships; } public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID agentID, UUID groupID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> Roles = new List<GroupRolesData>(); Dictionary<string, OSDMap> GroupRoles; if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles)) { Dictionary<string, OSDMap> MemberRoles; if (SimianGetGenericEntries(agentID, "GroupRole" + groupID.ToString(), out MemberRoles)) { foreach (KeyValuePair<string, OSDMap> kvp in MemberRoles) { GroupRolesData data = new GroupRolesData(); data.RoleID = UUID.Parse(kvp.Key); data.Name = GroupRoles[kvp.Key]["Name"].AsString(); data.Description = GroupRoles[kvp.Key]["Description"].AsString(); data.Title = GroupRoles[kvp.Key]["Title"].AsString(); data.Powers = GroupRoles[kvp.Key]["Powers"].AsULong(); Roles.Add(data); } } } return Roles; } public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID groupID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRolesData> Roles = new List<GroupRolesData>(); Dictionary<string, OSDMap> GroupRoles; if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles)) { foreach (KeyValuePair<string, OSDMap> role in GroupRoles) { GroupRolesData data = new GroupRolesData(); data.RoleID = UUID.Parse(role.Key); data.Name = role.Value["Name"].AsString(); data.Description = role.Value["Description"].AsString(); data.Title = role.Value["Title"].AsString(); data.Powers = role.Value["Powers"].AsULong(); Dictionary<UUID, OSDMap> GroupRoleMembers; if (SimianGetGenericEntries("GroupRole" + groupID.ToString(), role.Key, out GroupRoleMembers)) { data.Members = GroupRoleMembers.Count; } else { data.Members = 0; } Roles.Add(data); } } return Roles; } public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupMembersData> members = new List<GroupMembersData>(); OSDMap GroupInfo; string GroupName; UUID GroupOwnerRoleID = UUID.Zero; if (!SimianGetFirstGenericEntry(GroupID, "Group", out GroupName, out GroupInfo)) { return members; } GroupOwnerRoleID = GroupInfo["OwnerRoleID"].AsUUID(); // Locally cache group roles, since we'll be needing this data for each member Dictionary<string,OSDMap> GroupRoles; SimianGetGenericEntries(GroupID, "GroupRole", out GroupRoles); // Locally cache list of group owners Dictionary<UUID, OSDMap> GroupOwners; SimianGetGenericEntries("GroupRole" + GroupID.ToString(), GroupOwnerRoleID.ToString(), out GroupOwners); Dictionary<UUID, OSDMap> GroupMembers; if (SimianGetGenericEntries("GroupMember", GroupID.ToString(), out GroupMembers)) { foreach (KeyValuePair<UUID, OSDMap> member in GroupMembers) { GroupMembersData data = new GroupMembersData(); data.AgentID = member.Key; UUID SelectedRoleID = member.Value["SelectedRoleID"].AsUUID(); data.AcceptNotices = member.Value["AcceptNotices"].AsBoolean(); data.ListInProfile = member.Value["ListInProfile"].AsBoolean(); data.Contribution = member.Value["Contribution"].AsInteger(); data.IsOwner = GroupOwners.ContainsKey(member.Key); OSDMap GroupRoleInfo = GroupRoles[SelectedRoleID.ToString()]; data.Title = GroupRoleInfo["Title"].AsString(); data.AgentPowers = GroupRoleInfo["Powers"].AsULong(); members.Add(data); } } return members; } public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID groupID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupRoleMembersData> members = new List<GroupRoleMembersData>(); Dictionary<string, OSDMap> GroupRoles; if (SimianGetGenericEntries(groupID, "GroupRole", out GroupRoles)) { foreach( KeyValuePair<string, OSDMap> Role in GroupRoles ) { Dictionary<UUID, OSDMap> GroupRoleMembers; if( SimianGetGenericEntries("GroupRole"+groupID.ToString(), Role.Key, out GroupRoleMembers) ) { foreach( KeyValuePair<UUID, OSDMap> GroupRoleMember in GroupRoleMembers ) { GroupRoleMembersData data = new GroupRoleMembersData(); data.MemberID = GroupRoleMember.Key; data.RoleID = UUID.Parse(Role.Key); members.Add(data); } } } } return members; } public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); List<GroupNoticeData> values = new List<GroupNoticeData>(); Dictionary<string, OSDMap> Notices; if (SimianGetGenericEntries(GroupID, "GroupNotice", out Notices)) { foreach (KeyValuePair<string, OSDMap> Notice in Notices) { GroupNoticeData data = new GroupNoticeData(); data.NoticeID = UUID.Parse(Notice.Key); data.Timestamp = Notice.Value["TimeStamp"].AsUInteger(); data.FromName = Notice.Value["FromName"].AsString(); data.Subject = Notice.Value["Subject"].AsString(); data.HasAttachment = Notice.Value["BinaryBucket"].AsBinary().Length > 0; //TODO: Figure out how to get this data.AssetType = 0; values.Add(data); } } return values; } public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap GroupNotice; UUID GroupID; if (SimianGetFirstGenericEntry("GroupNotice", noticeID.ToString(), out GroupID, out GroupNotice)) { GroupNoticeInfo data = new GroupNoticeInfo(); data.GroupID = GroupID; data.Message = GroupNotice["Message"].AsString(); data.BinaryBucket = GroupNotice["BinaryBucket"].AsBinary(); data.noticeData.NoticeID = noticeID; data.noticeData.Timestamp = GroupNotice["TimeStamp"].AsUInteger(); data.noticeData.FromName = GroupNotice["FromName"].AsString(); data.noticeData.Subject = GroupNotice["Subject"].AsString(); data.noticeData.HasAttachment = data.BinaryBucket.Length > 0; data.noticeData.AssetType = 0; if (data.Message == null) { data.Message = string.Empty; } return data; } return null; } public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap Notice = new OSDMap(); Notice["TimeStamp"] = OSD.FromUInteger((uint)Util.UnixTimeSinceEpoch()); Notice["FromName"] = OSD.FromString(fromName); Notice["Subject"] = OSD.FromString(subject); Notice["Message"] = OSD.FromString(message); Notice["BinaryBucket"] = OSD.FromBinary(binaryBucket); SimianAddGeneric(groupID, "GroupNotice", noticeID.ToString(), Notice); } #endregion #region GroupSessionTracking public void ResetAgentGroupChatSessions(UUID agentID) { Dictionary<string, OSDMap> agentSessions; if (SimianGetGenericEntries(agentID, "GroupSessionDropped", out agentSessions)) { foreach (string GroupID in agentSessions.Keys) { SimianRemoveGenericEntry(agentID, "GroupSessionDropped", GroupID); } } if (SimianGetGenericEntries(agentID, "GroupSessionInvited", out agentSessions)) { foreach (string GroupID in agentSessions.Keys) { SimianRemoveGenericEntry(agentID, "GroupSessionInvited", GroupID); } } } public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID) { OSDMap session; return SimianGetGenericEntry(agentID, "GroupSessionDropped", groupID.ToString(), out session); } public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID) { SimianAddGeneric(agentID, "GroupSessionDropped", groupID.ToString(), new OSDMap()); } public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID) { SimianAddGeneric(agentID, "GroupSessionInvited", groupID.ToString(), new OSDMap()); } public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID) { OSDMap session; return SimianGetGenericEntry(agentID, "GroupSessionDropped", groupID.ToString(), out session); } #endregion private void EnsureRoleNotSelectedByMember(UUID groupID, UUID roleID, UUID userID) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); // If member's SelectedRole is roleID, change their selected role to Everyone // before removing them from the role OSDMap UserGroupInfo; if (SimianGetGenericEntry(userID, "GroupMember", groupID.ToString(), out UserGroupInfo)) { if (UserGroupInfo["SelectedRoleID"].AsUUID() == roleID) { UserGroupInfo["SelectedRoleID"] = OSD.FromUUID(UUID.Zero); } SimianAddGeneric(userID, "GroupMember", groupID.ToString(), UserGroupInfo); } } #region Simian Util Methods private bool SimianAddGeneric(UUID ownerID, string type, string key, OSDMap map) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key); string value = OSDParser.SerializeJsonString(map); if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] value: {0}", value); NameValueCollection RequestArgs = new NameValueCollection { { "RequestMethod", "AddGeneric" }, { "OwnerID", ownerID.ToString() }, { "Type", type }, { "Key", key }, { "Value", value} }; OSDMap Response = CachedPostRequest(RequestArgs); if (Response["Success"].AsBoolean()) { return true; } else { m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error {0}, {1}, {2}, {3}", ownerID, type, key, Response["Message"]); return false; } } /// <summary> /// Returns the first of possibly many entries for Owner/Type pair /// </summary> private bool SimianGetFirstGenericEntry(UUID ownerID, string type, out string key, out OSDMap map) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type); NameValueCollection RequestArgs = new NameValueCollection { { "RequestMethod", "GetGenerics" }, { "OwnerID", ownerID.ToString() }, { "Type", type } }; OSDMap Response = CachedPostRequest(RequestArgs); if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray) { OSDArray entryArray = (OSDArray)Response["Entries"]; if (entryArray.Count >= 1) { OSDMap entryMap = entryArray[0] as OSDMap; key = entryMap["Key"].AsString(); map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString()); if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString()); return true; } else { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results"); } } else { m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]); } key = null; map = null; return false; } private bool SimianGetFirstGenericEntry(string type, string key, out UUID ownerID, out OSDMap map) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, type, key); NameValueCollection RequestArgs = new NameValueCollection { { "RequestMethod", "GetGenerics" }, { "Type", type }, { "Key", key} }; OSDMap Response = CachedPostRequest(RequestArgs); if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray) { OSDArray entryArray = (OSDArray)Response["Entries"]; if (entryArray.Count >= 1) { OSDMap entryMap = entryArray[0] as OSDMap; ownerID = entryMap["OwnerID"].AsUUID(); map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString()); if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString()); return true; } else { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results"); } } else { m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]); } ownerID = UUID.Zero; map = null; return false; } private bool SimianGetGenericEntry(UUID ownerID, string type, string key, out OSDMap map) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key); NameValueCollection RequestArgs = new NameValueCollection { { "RequestMethod", "GetGenerics" }, { "OwnerID", ownerID.ToString() }, { "Type", type }, { "Key", key} }; OSDMap Response = CachedPostRequest(RequestArgs); if (Response["Success"].AsBoolean() && Response["Entries"] is OSDArray) { OSDArray entryArray = (OSDArray)Response["Entries"]; if (entryArray.Count == 1) { OSDMap entryMap = entryArray[0] as OSDMap; key = entryMap["Key"].AsString(); map = (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString()); if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString()); return true; } else { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results"); } } else { m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", Response["Message"]); } map = null; return false; } private bool SimianGetGenericEntries(UUID ownerID, string type, out Dictionary<string, OSDMap> maps) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name,ownerID, type); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetGenerics" }, { "OwnerID", ownerID.ToString() }, { "Type", type } }; OSDMap response = CachedPostRequest(requestArgs); if (response["Success"].AsBoolean() && response["Entries"] is OSDArray) { maps = new Dictionary<string, OSDMap>(); OSDArray entryArray = (OSDArray)response["Entries"]; foreach (OSDMap entryMap in entryArray) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString()); maps.Add(entryMap["Key"].AsString(), (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString())); } if(maps.Count == 0) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results"); } return true; } else { maps = null; m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error retrieving group info ({0})", response["Message"]); } return false; } private bool SimianGetGenericEntries(string type, string key, out Dictionary<UUID, OSDMap> maps) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2})", System.Reflection.MethodBase.GetCurrentMethod().Name, type, key); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "GetGenerics" }, { "Type", type }, { "Key", key } }; OSDMap response = CachedPostRequest(requestArgs); if (response["Success"].AsBoolean() && response["Entries"] is OSDArray) { maps = new Dictionary<UUID, OSDMap>(); OSDArray entryArray = (OSDArray)response["Entries"]; foreach (OSDMap entryMap in entryArray) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] Generics Result {0}", entryMap["Value"].AsString()); maps.Add(entryMap["OwnerID"].AsUUID(), (OSDMap)OSDParser.DeserializeJson(entryMap["Value"].AsString())); } if (maps.Count == 0) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] No Generics Results"); } return true; } else { maps = null; m_log.WarnFormat("[SIMIAN-GROUPS-CONNECTOR]: Error retrieving group info ({0})", response["Message"]); } return false; } private bool SimianRemoveGenericEntry(UUID ownerID, string type, string key) { if (m_debugEnabled) m_log.InfoFormat("[SIMIAN-GROUPS-CONNECTOR] {0} called ({1},{2},{3})", System.Reflection.MethodBase.GetCurrentMethod().Name, ownerID, type, key); NameValueCollection requestArgs = new NameValueCollection { { "RequestMethod", "RemoveGeneric" }, { "OwnerID", ownerID.ToString() }, { "Type", type }, { "Key", key } }; OSDMap response = CachedPostRequest(requestArgs); if (response["Success"].AsBoolean()) { return true; } else { m_log.WarnFormat("[SIMIAN GROUPS CONNECTOR]: Error {0}, {1}, {2}, {3}", ownerID, type, key, response["Message"]); return false; } } #endregion #region CheesyCache OSDMap CachedPostRequest(NameValueCollection requestArgs) { // Immediately forward the request if the cache is disabled. if (m_cacheTimeout == 0) { return WebUtil.PostToService(m_groupsServerURI, requestArgs); } // Check if this is an update or a request if ( requestArgs["RequestMethod"] == "RemoveGeneric" || requestArgs["RequestMethod"] == "AddGeneric" ) { // Any and all updates cause the cache to clear m_memoryCache.Clear(); // Send update to server, return the response without caching it return WebUtil.PostToService(m_groupsServerURI, requestArgs); } // If we're not doing an update, we must be requesting data // Create the cache key for the request and see if we have it cached string CacheKey = WebUtil.BuildQueryString(requestArgs); OSDMap response = null; if (!m_memoryCache.TryGetValue(CacheKey, out response)) { // if it wasn't in the cache, pass the request to the Simian Grid Services response = WebUtil.PostToService(m_groupsServerURI, requestArgs); // and cache the response m_memoryCache.AddOrUpdate(CacheKey, response, TimeSpan.FromSeconds(m_cacheTimeout)); } // return cached response return response; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Linq; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNetCore.Http.Tests { public class ResponseCookiesTest { private IFeatureCollection MakeFeatures(IHeaderDictionary headers) { var responseFeature = new HttpResponseFeature() { Headers = headers }; var features = new FeatureCollection(); features.Set<IHttpResponseFeature>(responseFeature); return features; } [Fact] public void AppendSameSiteNoneWithoutSecureLogsWarning() { var headers = (IHeaderDictionary)new HeaderDictionary(); var features = MakeFeatures(headers); var services = new ServiceCollection(); var sink = new TestSink(TestSink.EnableWithTypeName<ResponseCookies>); var loggerFactory = new TestLoggerFactory(sink, enabled: true); services.AddLogging(); services.AddSingleton<ILoggerFactory>(loggerFactory); features.Set<IServiceProvidersFeature>(new ServiceProvidersFeature() { RequestServices = services.BuildServiceProvider() }); var cookies = new ResponseCookies(features); var testCookie = "TestCookie"; cookies.Append(testCookie, "value", new CookieOptions() { SameSite = SameSiteMode.None, }); var cookieHeaderValues = headers.SetCookie; Assert.Single(cookieHeaderValues); Assert.StartsWith(testCookie, cookieHeaderValues[0]); Assert.Contains("path=/", cookieHeaderValues[0]); Assert.Contains("samesite=none", cookieHeaderValues[0]); Assert.DoesNotContain("secure", cookieHeaderValues[0]); var writeContext = Assert.Single(sink.Writes); Assert.Equal("The cookie 'TestCookie' has set 'SameSite=None' and must also set 'Secure'.", writeContext.Message); } [Fact] public void DeleteCookieShouldSetDefaultPath() { var headers = (IHeaderDictionary)new HeaderDictionary(); var features = MakeFeatures(headers); var cookies = new ResponseCookies(features); var testCookie = "TestCookie"; cookies.Delete(testCookie); var cookieHeaderValues = headers.SetCookie; Assert.Single(cookieHeaderValues); Assert.StartsWith(testCookie, cookieHeaderValues[0]); Assert.Contains("path=/", cookieHeaderValues[0]); Assert.Contains("expires=Thu, 01 Jan 1970 00:00:00 GMT", cookieHeaderValues[0]); } [Fact] public void DeleteCookieWithDomainAndPathDeletesPriorMatchingCookies() { var headers = (IHeaderDictionary)new HeaderDictionary(); var features = MakeFeatures(headers); var responseCookies = new ResponseCookies(features); var testCookies = new (string Key, string Path, string Domain)[] { new ("key1", "/path1/", null), new ("key1", "/path2/", null), new ("key2", "/path1/", "localhost"), new ("key2", "/path2/", "localhost"), }; foreach (var cookie in testCookies) { responseCookies.Delete(cookie.Key, new CookieOptions() { Domain = cookie.Domain, Path = cookie.Path }); } var deletedCookies = headers.SetCookie.ToArray(); Assert.Equal(testCookies.Length, deletedCookies.Length); Assert.Single(deletedCookies, cookie => cookie.StartsWith("key1", StringComparison.InvariantCulture) && cookie.Contains("path=/path1/")); Assert.Single(deletedCookies, cookie => cookie.StartsWith("key1", StringComparison.InvariantCulture) && cookie.Contains("path=/path2/")); Assert.Single(deletedCookies, cookie => cookie.StartsWith("key2", StringComparison.InvariantCulture) && cookie.Contains("path=/path1/") && cookie.Contains("domain=localhost")); Assert.Single(deletedCookies, cookie => cookie.StartsWith("key2", StringComparison.InvariantCulture) && cookie.Contains("path=/path2/") && cookie.Contains("domain=localhost")); Assert.All(deletedCookies, cookie => Assert.Contains("expires=Thu, 01 Jan 1970 00:00:00 GMT", cookie)); } [Fact] public void DeleteRemovesCookieWithDomainAndPathCreatedByAdd() { var headers = (IHeaderDictionary)new HeaderDictionary(); var features = MakeFeatures(headers); var responseCookies = new ResponseCookies(features); var testCookies = new (string Key, string Path, string Domain)[] { new ("key1", "/path1/", null), new ("key1", "/path1/", null), new ("key2", "/path1/", "localhost"), new ("key2", "/path1/", "localhost"), }; foreach (var cookie in testCookies) { responseCookies.Append(cookie.Key, cookie.Key, new CookieOptions() { Domain = cookie.Domain, Path = cookie.Path }); responseCookies.Delete(cookie.Key, new CookieOptions() { Domain = cookie.Domain, Path = cookie.Path }); } var deletedCookies = headers.SetCookie.ToArray(); Assert.Equal(2, deletedCookies.Length); Assert.Single(deletedCookies, cookie => cookie.StartsWith("key1", StringComparison.InvariantCulture) && cookie.Contains("path=/path1/")); Assert.Single(deletedCookies, cookie => cookie.StartsWith("key2", StringComparison.InvariantCulture) && cookie.Contains("path=/path1/") && cookie.Contains("domain=localhost")); Assert.All(deletedCookies, cookie => Assert.Contains("expires=Thu, 01 Jan 1970 00:00:00 GMT", cookie)); } [Fact] public void DeleteCookieWithCookieOptionsShouldKeepPropertiesOfCookieOptions() { var headers = (IHeaderDictionary)new HeaderDictionary(); var features = MakeFeatures(headers); var cookies = new ResponseCookies(features); var testCookie = "TestCookie"; var time = new DateTimeOffset(2000, 1, 1, 1, 1, 1, 1, TimeSpan.Zero); var options = new CookieOptions { Secure = true, HttpOnly = true, Path = "/", Expires = time, Domain = "example.com", SameSite = SameSiteMode.Lax }; cookies.Delete(testCookie, options); var cookieHeaderValues = headers.SetCookie; Assert.Single(cookieHeaderValues); Assert.StartsWith(testCookie, cookieHeaderValues[0]); Assert.Contains("path=/", cookieHeaderValues[0]); Assert.Contains("expires=Thu, 01 Jan 1970 00:00:00 GMT", cookieHeaderValues[0]); Assert.Contains("secure", cookieHeaderValues[0]); Assert.Contains("httponly", cookieHeaderValues[0]); Assert.Contains("samesite", cookieHeaderValues[0]); } [Fact] public void NoParamsDeleteRemovesCookieCreatedByAdd() { var headers = (IHeaderDictionary)new HeaderDictionary(); var features = MakeFeatures(headers); var cookies = new ResponseCookies(features); var testCookie = "TestCookie"; cookies.Append(testCookie, testCookie); cookies.Delete(testCookie); var cookieHeaderValues = headers.SetCookie; Assert.Single(cookieHeaderValues); Assert.StartsWith(testCookie, cookieHeaderValues[0]); Assert.Contains("path=/", cookieHeaderValues[0]); Assert.Contains("expires=Thu, 01 Jan 1970 00:00:00 GMT", cookieHeaderValues[0]); } [Fact] public void ProvidesMaxAgeWithCookieOptionsArgumentExpectMaxAgeToBeSet() { var headers = (IHeaderDictionary)new HeaderDictionary(); var features = MakeFeatures(headers); var cookies = new ResponseCookies(features); var cookieOptions = new CookieOptions(); var maxAgeTime = TimeSpan.FromHours(1); cookieOptions.MaxAge = TimeSpan.FromHours(1); var testCookie = "TestCookie"; cookies.Append(testCookie, testCookie, cookieOptions); var cookieHeaderValues = headers.SetCookie; Assert.Single(cookieHeaderValues); Assert.Contains($"max-age={maxAgeTime.TotalSeconds}", cookieHeaderValues[0]); } [Theory] [InlineData("value", "key=value")] [InlineData("!value", "key=%21value")] [InlineData("val^ue", "key=val%5Eue")] [InlineData("QUI+REU/Rw==", "key=QUI%2BREU%2FRw%3D%3D")] public void EscapesValuesBeforeSettingCookie(string value, string expected) { var headers = (IHeaderDictionary)new HeaderDictionary(); var features = MakeFeatures(headers); var cookies = new ResponseCookies(features); cookies.Append("key", value); var cookieHeaderValues = headers.SetCookie; Assert.Single(cookieHeaderValues); Assert.StartsWith(expected, cookieHeaderValues[0]); } [Theory] [InlineData("key,")] [InlineData("ke@y")] public void InvalidKeysThrow(string key) { var headers = new HeaderDictionary(); var features = MakeFeatures(headers); var cookies = new ResponseCookies(features); Assert.Throws<ArgumentException>(() => cookies.Append(key, "1")); } [Theory] [InlineData("key", "value", "key=value")] [InlineData("key,", "!value", "key%2C=%21value")] [InlineData("ke#y,", "val^ue", "ke%23y%2C=val%5Eue")] [InlineData("base64", "QUI+REU/Rw==", "base64=QUI%2BREU%2FRw%3D%3D")] public void AppContextSwitchEscapesKeysAndValuesBeforeSettingCookie(string key, string value, string expected) { var headers = (IHeaderDictionary)new HeaderDictionary(); var features = MakeFeatures(headers); var cookies = new ResponseCookies(features); cookies._enableCookieNameEncoding = true; cookies.Append(key, value); var cookieHeaderValues = headers.SetCookie; Assert.Single(cookieHeaderValues); Assert.StartsWith(expected, cookieHeaderValues[0]); } } }
/* * SqlFindObjectCommandTest.cs 12/26/2002 * * Copyright 2002 Screen Show, Inc. All rights reserved. * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ using System; using System.Data; using System.Data.SqlClient; using System.Collections; using NUnit.Framework; using Inform; namespace Inform.Tests.Common { /// <summary> /// Summary description for SqlFindCollectionCommand. /// </summary> [TestFixture] public abstract class FindCollectionCommandTest { DataStore dataStore; public abstract DataStore CreateDataStore(); [SetUp] public void InitializeConnection() { dataStore = CreateDataStore(); dataStore.Settings.AutoGenerate = true; dataStore.CreateStorage(typeof(Employee)); Employee e = new Employee(); e.EmployeeID = "1"; e.FirstName = "Don"; e.LastName = "Paulson"; e.Title = "Director"; e.Salary = 70000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "2"; e.FirstName = "Sam"; e.LastName = "Donaldson"; e.Title = "Director"; e.Salary = 70000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "3"; e.FirstName = "Jim"; e.LastName = "Davis"; e.Title = "Director"; e.Salary = 65000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "4"; e.FirstName = "Ralph"; e.LastName = "Emerson"; e.Title = "Director"; e.Salary = 65000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "5"; e.FirstName = "Steve"; e.LastName = "Johnson"; e.Title = "Director"; e.Salary = 65000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "6"; e.FirstName = "Bonnie"; e.LastName = "Illes"; e.Title = "Director"; e.Salary = 65000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "7"; e.FirstName = "Tim"; e.LastName = "Valdez"; e.Title = "Director"; e.Salary = 65000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "8"; e.FirstName = "Peter"; e.LastName = "Vanders"; e.Title = "Director"; e.Salary = 65000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "9"; e.FirstName = "Sallie"; e.LastName = "Johnston"; e.Title = "Director"; e.Salary = 65000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "10"; e.FirstName = "Mary"; e.LastName = "Stucker"; e.Title = "Marketing"; e.Salary = 65000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "11"; e.FirstName = "Tim"; e.LastName = "Valdez"; e.Title = "Sales"; e.Salary = 65000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "12"; e.FirstName = "Tim"; e.LastName = "Valdez"; e.Title = "Technician"; e.Salary = 70000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "13"; e.FirstName = "Tim"; e.LastName = "Valdez"; e.Title = "Sales"; e.Salary = 45000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "14"; e.FirstName = "Patti"; e.LastName = "Rollins"; e.Title = "Secretary"; e.Salary = 25000; dataStore.Insert(e); e = new Employee(); e.EmployeeID = "15"; e.FirstName = "Betty"; e.LastName = "Alexander"; e.Title = "Developer"; e.Salary = 75000; dataStore.Insert(e); } [TearDown] public void DeleteStorage() { dataStore.DeleteStorage(typeof(Employee)); } [Test] public void FindAllEmployee(){ //Create command IList list = dataStore.CreateFindCollectionCommand( typeof(Employee), "ORDER BY LastName").Execute(); Console.Out.WriteLine("-- All"); foreach (Employee e in list) { Console.Out.WriteLine(e.LastName); } //test command Assert.IsTrue(list.Count == 15,"Verify found 15 Employees"); Assert.AreEqual("Davis", ((Employee)list[1]).LastName, "Verify Last Name"); } [Test] public void FindEmployeesPaged() { //Create command int count = 0; IList list = dataStore.CreateFindCollectionCommand(typeof(Employee), "ORDER BY LastName").Execute(0, 5, out count); //test command Assert.AreEqual(5, list.Count, "Returned 5 Employees"); Assert.AreEqual("Alexander", ((Employee)list[0]).LastName, "Verify Last Name"); Assert.AreEqual(15, count, "Verify found 15 Employees"); list = dataStore.CreateFindCollectionCommand(typeof(Employee), "ORDER BY LastName").Execute(1, 5, out count); //test command Assert.AreEqual(5, list.Count, "Returned 5 Employees"); Assert.AreEqual("Johnston", ((Employee)list[1]).LastName, "Verify Last Name"); Assert.AreEqual(15, count, "Verify found 15 Employees"); list = dataStore.CreateFindCollectionCommand(typeof(Employee), "ORDER BY LastName").Execute(3, 5, out count); //test command Assert.AreEqual(0, list.Count, "Returned 0 Employees"); Assert.AreEqual(15, count, "Verify found 15 Employees"); list = dataStore.CreateFindCollectionCommand(typeof(Employee), "ORDER BY LastName").Execute(3, 4, out count); Console.Out.WriteLine("-- Page 4, pagesize 4"); foreach (Employee e in list) { Console.Out.WriteLine(e.LastName); } //test command Assert.AreEqual(3, list.Count, "Returned 3 Employees"); Assert.AreEqual("Valdez", ((Employee)list[1]).LastName, "Verify Last Name"); Assert.AreEqual(15, count, "Verify found 15 Employees"); } [Test] public void PolymorphicQuery(){ dataStore = CreateDataStore(); dataStore.Settings.AutoGenerate = true; try { dataStore.DeleteStorage(typeof(Circle)); } catch {} dataStore.CreateStorage(typeof(Circle)); try { dataStore.DeleteStorage(typeof(Rectangle)); } catch {} dataStore.CreateStorage(typeof(Rectangle)); Circle c = new Circle(); c.Color = "Green"; c.Radius = 5; dataStore.Insert(c); Rectangle r = new Rectangle(); r.Color = "Green"; r.Width = 5; r.Length = 2; dataStore.Insert(r); IList shapes = dataStore.CreateFindCollectionCommand(typeof(Shape), null, true).Execute(); Assert.IsTrue(shapes.Count == 2,"Returned Items = 2" + shapes.Count); Assert.IsTrue(((Shape)shapes[0]).GetArea() == 2 * Math.PI * Math.Pow(5,2),"Circle Area"); Assert.IsTrue(((Shape)shapes[1]).GetArea() == 10, "Rectangle Area"); dataStore.DeleteStorage(typeof(Circle)); dataStore.DeleteStorage(typeof(Rectangle)); dataStore.DeleteStorage(typeof(Shape)); } [Test] public void PolymorphicQueryWithFilter(){ dataStore = CreateDataStore(); dataStore.Settings.AutoGenerate = true; try { dataStore.DeleteStorage(typeof(Circle)); } catch {} dataStore.CreateStorage(typeof(Circle)); try { dataStore.DeleteStorage(typeof(Rectangle)); } catch {} dataStore.CreateStorage(typeof(Rectangle)); Circle c = new Circle(); c.Color = "Green"; c.Radius = 5; dataStore.Insert(c); Rectangle r = new Rectangle(); r.Color = "Green"; r.Width = 5; r.Length = 2; dataStore.Insert(r); IList shapes = dataStore.CreateFindCollectionCommand(typeof(Shape), null, true).Execute(); Assert.IsTrue(shapes.Count == 2,"Returned Items = " + shapes.Count); Assert.IsTrue(((Shape)shapes[0]).GetArea() == 2 * Math.PI * Math.Pow(5,2),"Circle Area"); Assert.IsTrue(((Shape)shapes[1]).GetArea() == 10,"Rectangle Area"); dataStore.DeleteStorage(typeof(Circle)); dataStore.DeleteStorage(typeof(Rectangle)); dataStore.DeleteStorage(typeof(Shape)); } } }
// <copyright file=SettingsTable.cs // <copyright> // Copyright (c) 2016, University of Stuttgart // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> // <license>MIT License</license> // <main contributors> // Markus Funk, Thomas Kosch, Sven Mayer // </main contributors> // <co-contributors> // Paul Brombosch, Mai El-Komy, Juana Heusler, // Matthias Hoppe, Robert Konrad, Alexander Martin // </co-contributors> // <patent information> // We are aware that this software implements patterns and ideas, // which might be protected by patents in your country. // Example patents in Germany are: // Patent reference number: DE 103 20 557.8 // Patent reference number: DE 10 2013 220 107.9 // Please make sure when using this software not to violate any existing patents in your country. // </patent information> // <date> 11/2/2016 12:25:56 PM</date> using System; using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Windows.Media.Media3D; namespace HciLab.motionEAP.InterfacesAndDataModel.Data { [ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] [Serializable()] public class SettingsTable : ISerializable, INotifyPropertyChanged { // Version private int m_SerVersion = 7; // all the important settings of this software // State of all checkboxes for debug mode private bool m_ShowFPS = false; private bool m_ShowDemoAnimation = false; private bool m_EditMode = false; private bool m_ShowInformations = false; private bool m_ShowWarnings = false; private bool m_ShowErrors = false; private bool m_ShowCriticals = false; // State of all checkboxes for video mode private bool m_IsFreeSpace = false; private bool m_IsObjectMapping = false; private bool m_IsTrackObject = false; private bool m_IsStartProjection = false; // State of all checkboxes for settings mode private bool m_IsSmoothingOn = false; private Point3D m_ProjCamPosition = new Point3D(300, 300, 300); private Vector3D m_ProjCamLookDirection = new Vector3D(0, -0.1, -1); private double m_ProjCamFOV = 45; private Rectangle m_KinectDrawing = new Rectangle(); private Rectangle m_KinectDrawing_AssemblyArea = new Rectangle(); private int m_tableHeight = 0; private String m_ImagePath = ""; private bool m_CheckBoxBoxFaultDetection; private bool m_CheckBoxEnableEnsensoSmoothing; private Rectangle m_EnsensoDrawing = new Rectangle(); private Rectangle m_EnsensoDrawing_AssemblyArea = new Rectangle(); public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } public SettingsTable() { } protected SettingsTable(SerializationInfo info, StreamingContext context) { int SerVersion = info.GetInt32("m_SerVersion"); // Check version of XML version if (SerVersion < 1) return; // 2D Touch m_ShowFPS = info.GetBoolean("m_ShowFPS"); m_ShowDemoAnimation = info.GetBoolean("m_ShowDemoAnimation"); m_EditMode = info.GetBoolean("m_EditMode"); m_ShowInformations = info.GetBoolean("m_ShowInformations"); m_ShowWarnings = info.GetBoolean("m_ShowWarnings"); m_ShowErrors = info.GetBoolean("m_ShowErrors"); m_ShowCriticals = info.GetBoolean("m_ShowCriticals"); m_IsFreeSpace = info.GetBoolean("m_IsFreeSpace"); m_IsObjectMapping = info.GetBoolean("m_IsObjectMapping"); m_IsTrackObject = info.GetBoolean("m_IsTrackObject"); m_IsStartProjection = info.GetBoolean("m_IsStartProjection"); m_IsSmoothingOn = info.GetBoolean("m_IsSmoothingOn"); m_tableHeight = info.GetInt32("m_tableHeight"); m_ImagePath = info.GetString("m_ImagePath"); if (SerVersion < 2) return; m_KinectDrawing_AssemblyArea = (Rectangle)info.GetValue("m_KinectDrawing_AssemblyAreaColor", typeof(Rectangle)); m_KinectDrawing = (Rectangle)info.GetValue("m_KinectDrawing", typeof(Rectangle)); if (SerVersion < 3) return; m_ProjCamPosition = (Point3D)info.GetValue("m_ProjCamPosition", typeof(Point3D)); m_ProjCamLookDirection = (Vector3D)info.GetValue("m_ProjCamLookDirection", typeof(Vector3D)); m_ProjCamFOV = info.GetDouble("m_ProjCamFOV"); if (SerVersion < 4) return; m_CheckBoxBoxFaultDetection = info.GetBoolean("m_CheckBoxBoxFaultDetection"); if (SerVersion < 5) return; // m_CheckBoxEnableEnsensoSmoothing = info.GetBoolean("m_CheckBoxEnableEnsensoSmoothing"); if (SerVersion < 6) return; m_EnsensoDrawing = (Rectangle)info.GetValue("m_EnsensoDrawing", typeof(Rectangle)); m_EnsensoDrawing_AssemblyArea = (Rectangle)info.GetValue("m_EnsensoDrawing_AssemblyArea", typeof(Rectangle)); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("m_SerVersion", m_SerVersion); info.AddValue("m_ShowFPS", m_ShowFPS); info.AddValue("m_ShowDemoAnimation", m_ShowDemoAnimation); info.AddValue("m_EditMode", m_EditMode); info.AddValue("m_ShowInformations", m_ShowInformations); info.AddValue("m_ShowWarnings", m_ShowWarnings); info.AddValue("m_ShowErrors", m_ShowErrors); info.AddValue("m_ShowCriticals", m_ShowCriticals); info.AddValue("m_IsFreeSpace", m_IsFreeSpace); info.AddValue("m_IsObjectMapping", m_IsObjectMapping); info.AddValue("m_IsTrackObject", m_IsTrackObject); info.AddValue("m_IsStartProjection", m_IsStartProjection); info.AddValue("m_IsSmoothingOn", m_IsSmoothingOn); info.AddValue("m_KinectDrawing", m_KinectDrawing); info.AddValue("m_KinectDrawing_AssemblyAreaColor", m_KinectDrawing_AssemblyArea); info.AddValue("m_tableHeight", m_tableHeight); info.AddValue("m_ImagePath", m_ImagePath); info.AddValue("m_ProjCamPosition", m_ProjCamPosition); info.AddValue("m_ProjCamLookDirection", m_ProjCamLookDirection); info.AddValue("m_ProjCamFOV", m_ProjCamFOV); info.AddValue("m_CheckBoxBoxFaultDetection", m_CheckBoxBoxFaultDetection); info.AddValue("m_CheckBoxEnableEnsensoSmoothing", m_CheckBoxEnableEnsensoSmoothing); info.AddValue("m_EnsensoDrawing", m_EnsensoDrawing); info.AddValue("m_EnsensoDrawing_AssemblyArea", m_EnsensoDrawing_AssemblyArea); } public delegate void ShowDemoAnimationHandler(object pSource, bool pVisible); public event ShowDemoAnimationHandler ShowDemoAnimationEvent; public void OnShowDemoAnimationEvent(object pSource, bool pVisible) { if (this.ShowDemoAnimationEvent != null) ShowDemoAnimationEvent(pSource, pVisible); } public String ImagePath { get { return m_ImagePath; } set { m_ImagePath = value; NotifyPropertyChanged("ImagePath"); } } public bool ShowFPS { get { return m_ShowFPS; } set { m_ShowFPS = value; NotifyPropertyChanged("ShowFPS"); } } public Boolean ShowDemoAnimation { get { return m_ShowDemoAnimation; } set { m_ShowDemoAnimation = value; OnShowDemoAnimationEvent(this, m_ShowDemoAnimation); NotifyPropertyChanged("ShowFPS"); } } public bool EditMode { get { return m_EditMode; } set { m_EditMode = value; NotifyPropertyChanged("EditMode"); } } public bool ShowWarnings { get { return m_ShowWarnings; } set { m_ShowWarnings = value; NotifyPropertyChanged("ShowWarnings"); } } public bool ShowInformations { get { return m_ShowInformations; } set { m_ShowInformations = value; NotifyPropertyChanged("ShowInformations"); } } public bool ShowCriticals { get { return m_ShowCriticals; } set { m_ShowCriticals = value; NotifyPropertyChanged("ShowCriticals"); } } public bool ShowErrors { get { return m_ShowErrors; } set { m_ShowErrors = value; NotifyPropertyChanged("ShowErrors"); } } public Point3D ProjCamPosition { get { return m_ProjCamPosition; } set { m_ProjCamPosition = value; NotifyPropertyChanged("ProjCamPosition"); } } public Vector3D ProjCamLookDirection { get { return m_ProjCamLookDirection; } set { m_ProjCamLookDirection = value; NotifyPropertyChanged("ProjCamLookDirection"); } } public double ProjCamFOV { get { return m_ProjCamFOV; } set { m_ProjCamFOV = value; NotifyPropertyChanged("ProjCamFOV"); } } public Rectangle KinectDrawing { get { return m_KinectDrawing; } set { m_KinectDrawing = value; NotifyPropertyChanged("KinectDrawing"); } } public Rectangle KinectDrawing_AssemblyArea { get { return m_KinectDrawing_AssemblyArea; } set { m_KinectDrawing_AssemblyArea = value; NotifyPropertyChanged("KinectDrawing_AssemblyArea"); } } public int TableHeight { get { return m_tableHeight; } set { m_tableHeight = value; NotifyPropertyChanged("TableHeight"); } } public bool EnableFaultBoxMode { get { return m_CheckBoxBoxFaultDetection; } set { m_CheckBoxBoxFaultDetection = value; NotifyPropertyChanged("EnableFaultBoxMode"); } } public bool CheckBoxEnableEnsensoSmoothing { get { return m_CheckBoxEnableEnsensoSmoothing; } set { m_CheckBoxEnableEnsensoSmoothing = value; NotifyPropertyChanged("CheckBoxEnableEnsensoSmoothing"); } } public Rectangle EnsensoDrawing { get { return m_EnsensoDrawing; } set { m_EnsensoDrawing = value; NotifyPropertyChanged("EnsensoDrawing"); } } public Rectangle EnsensoDrawing_AssemblyArea { get { return m_EnsensoDrawing_AssemblyArea; } set { m_EnsensoDrawing_AssemblyArea = value; NotifyPropertyChanged("EnsensoDrawing_AssemblyArea"); } } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using NQuery.Compilation; namespace NQuery { /// <summary> /// Represents an identifier in the query engine. This class cannot be directly instantiated. Instead use /// <see cref="CreateVerbatim"/>, <see cref="CreateNonVerbatim"/>, or <see cref="FromSource"/>. /// </summary> public sealed class Identifier { [Flags] private enum IdentifierFlags { None = 0x0000, Verbatim = 0x0001, Parenthesized = 0x0002 } private string _text; private IdentifierFlags _flags; private Identifier([SuppressMessage("Microsoft.Globalization", "CA1303")] string text, IdentifierFlags flags) { if (text == null) throw ExceptionBuilder.ArgumentNull("text"); _text = text; _flags = flags; } internal static readonly Identifier Missing = new Identifier("?", IdentifierFlags.Verbatim); /// <summary> /// Gets the textual value of this identifier, i.e. the name without any masking characters (e.g. quotes, brackets). /// </summary> public string Text { get { return _text; } } /// <summary> /// Gets a value indicating whether the textual value of this identifer is taken verbatim. This is equivalent to /// a quoted identifier. /// </summary> public bool Verbatim { get { return (_flags & IdentifierFlags.Verbatim) == IdentifierFlags.Verbatim; } } /// <summary> /// Gets a value indicating whether the textucal value can only be represented using brackets. /// </summary> public bool Parenthesized { get { return (_flags & IdentifierFlags.Parenthesized) == IdentifierFlags.Parenthesized; } } /// <summary> /// Creates a new verbatim (i.e. quoted) identifier. /// </summary> /// <param name="text">The textual value without any masking characters.</param> public static Identifier CreateVerbatim([SuppressMessage("Microsoft.Globalization", "CA1303")] string text) { return new Identifier(text, IdentifierFlags.Verbatim); } /// <summary> /// Creates a new non-verbatim (i.e. normal or parenthesized) identifier. /// </summary> /// <param name="text">The textual value without any masking characters.</param> public static Identifier CreateNonVerbatim([SuppressMessage("Microsoft.Globalization", "CA1303")] string text) { if (MustBeParenthesized(text)) return new Identifier(text, IdentifierFlags.Parenthesized); else return new Identifier(text, IdentifierFlags.None); } private static Identifier InternalFromSource([SuppressMessage("Microsoft.Globalization", "CA1303")] string text, bool allowInvalid) { if (text == null) throw ExceptionBuilder.ArgumentNull("text"); if (text.Length == 0 || (text[0] != '"' && text[0] != '[')) return CreateNonVerbatim(text); const char EOF = '\0'; IdentifierFlags flags; char endChar; string unterminatedMessage; if (text[0] == '[') { endChar = ']'; unterminatedMessage = Resources.UnterminatedParenthesizedIdentifier; flags = IdentifierFlags.Parenthesized; } else { endChar = '"'; unterminatedMessage = Resources.UnterminatedQuotedIdentifier; flags = IdentifierFlags.Verbatim; } StringBuilder sb = new StringBuilder(); int pos = 1; while (true) { char c = pos < text.Length ? text[pos] : EOF; char l = pos < text.Length - 1 ? text[pos + 1] : EOF; if (c == EOF) { if (allowInvalid) break; else throw ExceptionBuilder.ArgumentInvalidIdentifier("text", String.Format(CultureInfo.CurrentCulture, unterminatedMessage, text)); } else if (c == endChar) { if (l == endChar) pos++; else break; } sb.Append(c); pos++; } if (!allowInvalid && pos < text.Length - 1) throw ExceptionBuilder.ArgumentInvalidIdentifier("text", String.Format(CultureInfo.CurrentCulture, Resources.InvalidIdentifier, text)); return new Identifier(sb.ToString(), flags); } /// <summary> /// Creates a new identifier from a source-code representation. /// </summary> /// <remarks> /// This method also accepts malformed identifiers. This is crucial to allow lexer and parser to use this class /// even if the identifier is not correct. However, in this case the error has already been handled by the lexer. /// </remarks> /// <param name="text">The textual value including masking characters.</param> internal static Identifier InternalFromSource([SuppressMessage("Microsoft.Globalization", "CA1303")] string text) { return InternalFromSource(text, true); } /// <summary> /// Creates a new identifier from a source-code representation. /// </summary> /// <param name="text">The textual value including masking characters.</param> public static Identifier FromSource([SuppressMessage("Microsoft.Globalization", "CA1303")] string text) { return InternalFromSource(text, false); } /// <summary> /// Detects whether a given text would not form a valid identifier and therefore must be parenthesized. /// </summary> /// <param name="text">The text of the identifier</param> public static bool MustBeParenthesized(string text) { if (text == null) throw ExceptionBuilder.ArgumentNull("text"); if (text[0] != '_' && !Char.IsLetter(text[0])) return true; for (int i = 1; i < text.Length; i++) { if (!Char.IsLetterOrDigit(text[i]) && text[i] != '_' && text[i] != '$') return true; } TokenInfo tokenInfo = TokenInfo.FromText(text); if (tokenInfo.IsKeyword || tokenInfo.IsQueryKeyword) return true; return false; } /// <summary> /// Returns the source-code representation of this identifier. /// </summary> public string ToSource() { if (!Verbatim && !Parenthesized) return Text; char startChar = Parenthesized ? '[' : '"'; char endChar = Parenthesized ? ']' : '"'; StringBuilder sb = new StringBuilder(); sb.Append(startChar); for (int i = 0; i < _text.Length; i++) { if (_text[i] == endChar) sb.Append(endChar); sb.Append(_text[i]); } sb.Append(endChar); return sb.ToString(); } public override bool Equals(object obj) { Identifier identifier = obj as Identifier; if (identifier == null) return false; return this == identifier; } /// <summary> /// Compares this instance of an identifier to another instance. /// </summary> /// <param name="identifier">Other identfier to compare to.</param> public bool Equals(Identifier identifier) { if (identifier == null) return false; return this == identifier; } public override int GetHashCode() { return _text.GetHashCode() + 29 * _flags.GetHashCode(); } public static bool operator==(Identifier left, Identifier right) { if (ReferenceEquals(left, right)) return true; if (ReferenceEquals(left, null)) return false; if (ReferenceEquals(right, null)) return false; return left.Verbatim == right.Verbatim && left._text == right._text; } public static bool operator!=(Identifier left, Identifier right) { if (ReferenceEquals(left, right)) return false; if (ReferenceEquals(left, null)) return true; if (ReferenceEquals(right, null)) return true; return left.Verbatim != right.Verbatim || left._text != right._text; } /// <summary> /// Checks whether this identifier matches the given text. If <see cref="Verbatim"/> is <see langword="true"/> /// the comparison is done case-sensitive otherwise it is case-insensitive. /// </summary> /// <param name="text">The text to match against</param> public bool Matches([SuppressMessage("Microsoft.Globalization", "CA1303")] string text) { if (text == null) return false; if (Verbatim) { // Compare the string literally return _text == text; } // We are not verbatim, compare the names case insensitive. return String.Compare(_text, text, StringComparison.OrdinalIgnoreCase) == 0; } /// <summary> /// Checks whether this identifier matches the given identifier. /// To match <paramref name="identifier" /> the following must be true: /// <ul> /// <li>The value of <see cref="Verbatim"/> of this instance and <paramref name="identifier" /> must be equal.</li> /// <li>If <see cref="Verbatim"/> is <see langword="true"/> the value of <see cref="Text"/> of this instance and <paramref name="identifier" /> must be equal (compared case-sensitive).</li> /// <li>If <see cref="Verbatim"/> is <see langword="false"/> the value of <see cref="Text"/> of this instance and <paramref name="identifier" /> must be equal (compared case-insensitive).</li> /// </ul> /// </summary> /// <param name="identifier">The identifier to match against</param> public bool Matches(Identifier identifier) { // Identifier a1 = new Identifier("Name", true); // Identifier a2 = new Identifier("NAME", true); // // Identifier b1 = new Identifier("Name", false); // Identifier b2 = new Identifier("NAME", false); // // a1 and a2 are verbatim identifiers, b1 and b2 are a non-verbatim identifiers. // // -- Every identifier matches itself // // a1.Matches(a1) == true // a2.Matches(a2) == true // b1.Matches(b1) == true // b2.Matches(b2) == true // // -- Verbatim idenfiers are compared case sensitive // // a1.Matches(a2) == false // a2.Matches(a1) == false // // -- Non verbatim identifiers are compared case insensitive // // b1.Matches(b2) == true // b2.Matches(b1) == true // // -- A verbatim identifier compared with a non-verbatim identifier will never produce a match // // a1.Matches(b1) == false // a2.Matches(b2) == false // // -- A non-verbatim identifier and a verbatim identifier are compared case insensitive // // b1.Matches(a1) == true // b1.Matches(a2) == true // b2.Matches(a1) == true // b2.Matches(a2) == true if (identifier == null) return false; if (identifier == this) return true; if (Verbatim && !identifier.Verbatim) { // They will not match return false; } if (Verbatim && identifier.Verbatim) { // Both are verbatim, compare the string by chars. return Text == identifier.Text; } // The left identifier is not verbatim, compare the names case insensitive. return String.Compare(Text, identifier.Text, StringComparison.OrdinalIgnoreCase) == 0; } public override string ToString() { return ToSource(); } } }
using System; using Lucene.Net.Documents; namespace Lucene.Net.Search { using NUnit.Framework; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using Term = Lucene.Net.Index.Term; /// <summary> /// A basic 'positive' Unit test class for the FieldCacheRangeFilter class. /// /// <p> /// NOTE: at the moment, this class only tests for 'positive' results, /// it does not verify the results to ensure there are no 'false positives', /// nor does it adequately test 'negative' results. It also does not test /// that garbage in results in an Exception. /// </summary> [TestFixture] public class TestFieldCacheRangeFilter : BaseTestRangeFilter { [Test] public virtual void TestRangeFilterId() { IndexReader reader = SignedIndexReader; IndexSearcher search = NewSearcher(reader); int medId = ((MaxId - MinId) / 2); string minIP = Pad(MinId); string maxIP = Pad(MaxId); string medIP = Pad(medId); int numDocs = reader.NumDocs; Assert.AreEqual(numDocs, 1 + MaxId - MinId, "num of docs"); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); // test id, bounded on both ends result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, maxIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, maxIP, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but last"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, maxIP, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but first"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, maxIP, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 2, result.Length, "all but ends"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", medIP, maxIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + MaxId - medId, result.Length, "med and up"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, medIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + medId - MinId, result.Length, "up to med"); // unbounded id result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "min and up"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", null, maxIP, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "max and down"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not min, but up"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", null, maxIP, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not max, but down"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", medIP, maxIP, T, F), numDocs).ScoreDocs; Assert.AreEqual(MaxId - medId, result.Length, "med and up, not max"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, medIP, F, T), numDocs).ScoreDocs; Assert.AreEqual(medId - MinId, result.Length, "not min, up to med"); // very small sets result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, minIP, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "min,min,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", medIP, medIP, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "med,med,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", maxIP, maxIP, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "max,max,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", minIP, minIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "min,min,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", null, minIP, F, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "nul,min,F,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", maxIP, maxIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,max,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", maxIP, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,nul,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("id", medIP, medIP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "med,med,T,T"); } [Test] public virtual void TestFieldCacheRangeFilterRand() { IndexReader reader = SignedIndexReader; IndexSearcher search = NewSearcher(reader); string minRP = Pad(SignedIndexDir.MinR); string maxRP = Pad(SignedIndexDir.MaxR); int numDocs = reader.NumDocs; Assert.AreEqual(numDocs, 1 + MaxId - MinId, "num of docs"); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); // test extremes, bounded on both ends result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, maxRP, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, maxRP, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but biggest"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, maxRP, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but smallest"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, maxRP, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 2, result.Length, "all but extremes"); // unbounded result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "smallest and up"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", null, maxRP, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "biggest and down"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not smallest, but up"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", null, maxRP, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not biggest, but down"); // very small sets result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, minRP, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "min,min,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", maxRP, maxRP, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "max,max,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", minRP, minRP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "min,min,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", null, minRP, F, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "nul,min,F,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", maxRP, maxRP, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,max,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewStringRange("rand", maxRP, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,nul,T,T"); } // byte-ranges cannot be tested, because all ranges are too big for bytes, need an extra range for that [Test] public virtual void TestFieldCacheRangeFilterShorts() { IndexReader reader = SignedIndexReader; IndexSearcher search = NewSearcher(reader); int numDocs = reader.NumDocs; int medId = ((MaxId - MinId) / 2); short? minIdO = Convert.ToInt16((short)MinId); short? maxIdO = Convert.ToInt16((short)MaxId); short? medIdO = Convert.ToInt16((short)medId); Assert.AreEqual(numDocs, 1 + MaxId - MinId, "num of docs"); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); // test id, bounded on both ends result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but last"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but first"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 2, result.Length, "all but ends"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", medIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + MaxId - medId, result.Length, "med and up"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + medId - MinId, result.Length, "up to med"); // unbounded id result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "min and up"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", null, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "max and down"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not min, but up"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", null, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not max, but down"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", medIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(MaxId - medId, result.Length, "med and up, not max"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, medIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(medId - MinId, result.Length, "not min, up to med"); // very small sets result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, minIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "min,min,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", medIdO, medIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "med,med,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", maxIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "max,max,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", minIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "min,min,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", null, minIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "nul,min,F,T"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", maxIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,max,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", maxIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,nul,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", medIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "med,med,T,T"); // special cases result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", Convert.ToInt16(short.MaxValue), null, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", null, Convert.ToInt16(short.MinValue), F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); result = search.Search(q, FieldCacheRangeFilter.NewShortRange("id", maxIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "inverse range"); } [Test] public virtual void TestFieldCacheRangeFilterInts() { IndexReader reader = SignedIndexReader; IndexSearcher search = NewSearcher(reader); int numDocs = reader.NumDocs; int medId = ((MaxId - MinId) / 2); int? minIdO = Convert.ToInt32(MinId); int? maxIdO = Convert.ToInt32(MaxId); int? medIdO = Convert.ToInt32(medId); Assert.AreEqual(numDocs, 1 + MaxId - MinId, "num of docs"); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); // test id, bounded on both ends result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but last"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but first"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 2, result.Length, "all but ends"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", medIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + MaxId - medId, result.Length, "med and up"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + medId - MinId, result.Length, "up to med"); // unbounded id result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "min and up"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", null, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "max and down"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not min, but up"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", null, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not max, but down"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", medIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(MaxId - medId, result.Length, "med and up, not max"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, medIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(medId - MinId, result.Length, "not min, up to med"); // very small sets result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, minIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "min,min,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", medIdO, medIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "med,med,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", maxIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "max,max,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", minIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "min,min,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", null, minIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "nul,min,F,T"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", maxIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,max,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", maxIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,nul,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", medIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "med,med,T,T"); // special cases result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", Convert.ToInt32(int.MaxValue), null, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", null, Convert.ToInt32(int.MinValue), F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); result = search.Search(q, FieldCacheRangeFilter.NewIntRange("id", maxIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "inverse range"); } [Test] public virtual void TestFieldCacheRangeFilterLongs() { IndexReader reader = SignedIndexReader; IndexSearcher search = NewSearcher(reader); int numDocs = reader.NumDocs; int medId = ((MaxId - MinId) / 2); long? minIdO = Convert.ToInt64(MinId); long? maxIdO = Convert.ToInt64(MaxId); long? medIdO = Convert.ToInt64(medId); Assert.AreEqual(numDocs, 1 + MaxId - MinId, "num of docs"); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); // test id, bounded on both ends result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but last"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "all but first"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 2, result.Length, "all but ends"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", medIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + MaxId - medId, result.Length, "med and up"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1 + medId - MinId, result.Length, "up to med"); // unbounded id result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "min and up"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", null, maxIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "max and down"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, null, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not min, but up"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", null, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(numDocs - 1, result.Length, "not max, but down"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", medIdO, maxIdO, T, F), numDocs).ScoreDocs; Assert.AreEqual(MaxId - medId, result.Length, "med and up, not max"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, medIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(medId - MinId, result.Length, "not min, up to med"); // very small sets result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, minIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "min,min,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", medIdO, medIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "med,med,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", maxIdO, maxIdO, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "max,max,F,F"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", minIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "min,min,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", null, minIdO, F, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "nul,min,F,T"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", maxIdO, maxIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,max,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", maxIdO, null, T, F), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "max,nul,T,T"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", medIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(1, result.Length, "med,med,T,T"); // special cases result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", Convert.ToInt64(long.MaxValue), null, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", null, Convert.ToInt64(long.MinValue), F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "overflow special case"); result = search.Search(q, FieldCacheRangeFilter.NewLongRange("id", maxIdO, minIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "inverse range"); } // float and double tests are a bit minimalistic, but its complicated, because missing precision [Test] public virtual void TestFieldCacheRangeFilterFloats() { IndexReader reader = SignedIndexReader; IndexSearcher search = NewSearcher(reader); int numDocs = reader.NumDocs; float? minIdO = Convert.ToSingle(MinId + .5f); float? medIdO = Convert.ToSingle((float)minIdO + ((MaxId - MinId)) / 2.0f); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", minIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs / 2, result.Length, "find all"); int count = 0; result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", null, medIdO, F, T), numDocs).ScoreDocs; count += result.Length; result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", medIdO, null, F, F), numDocs).ScoreDocs; count += result.Length; Assert.AreEqual(numDocs, count, "sum of two concenatted ranges"); result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", Convert.ToSingle(float.PositiveInfinity), null, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "infinity special case"); result = search.Search(q, FieldCacheRangeFilter.NewFloatRange("id", null, Convert.ToSingle(float.NegativeInfinity), F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "infinity special case"); } [Test] public virtual void TestFieldCacheRangeFilterDoubles() { IndexReader reader = SignedIndexReader; IndexSearcher search = NewSearcher(reader); int numDocs = reader.NumDocs; double? minIdO = Convert.ToDouble(MinId + .5); double? medIdO = Convert.ToDouble((float)minIdO + ((MaxId - MinId)) / 2.0); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", minIdO, medIdO, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs / 2, result.Length, "find all"); int count = 0; result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", null, medIdO, F, T), numDocs).ScoreDocs; count += result.Length; result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", medIdO, null, F, F), numDocs).ScoreDocs; count += result.Length; Assert.AreEqual(numDocs, count, "sum of two concenatted ranges"); result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", null, null, T, T), numDocs).ScoreDocs; Assert.AreEqual(numDocs, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", Convert.ToDouble(double.PositiveInfinity), null, F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "infinity special case"); result = search.Search(q, FieldCacheRangeFilter.NewDoubleRange("id", null, Convert.ToDouble(double.NegativeInfinity), F, F), numDocs).ScoreDocs; Assert.AreEqual(0, result.Length, "infinity special case"); } // test using a sparse index (with deleted docs). [Test] public virtual void TestSparseIndex() { Directory dir = NewDirectory(); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); for (int d = -20; d <= 20; d++) { Document doc = new Document(); doc.Add(NewStringField("id", Convert.ToString(d), Field.Store.NO)); doc.Add(NewStringField("body", "body", Field.Store.NO)); writer.AddDocument(doc); } writer.ForceMerge(1); writer.DeleteDocuments(new Term("id", "0")); writer.Dispose(); IndexReader reader = DirectoryReader.Open(dir); IndexSearcher search = NewSearcher(reader); Assert.IsTrue(reader.HasDeletions); ScoreDoc[] result; Query q = new TermQuery(new Term("body", "body")); result = search.Search(q, FieldCacheRangeFilter.NewByteRange("id", (sbyte?)-20, (sbyte?)20, T, T), 100).ScoreDocs; Assert.AreEqual(40, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewByteRange("id", (sbyte?)0, (sbyte?)20, T, T), 100).ScoreDocs; Assert.AreEqual(20, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewByteRange("id", (sbyte?)-20, (sbyte?)0, T, T), 100).ScoreDocs; Assert.AreEqual(20, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewByteRange("id", (sbyte?)10, (sbyte?)20, T, T), 100).ScoreDocs; Assert.AreEqual(11, result.Length, "find all"); result = search.Search(q, FieldCacheRangeFilter.NewByteRange("id", (sbyte?)-20, (sbyte?)-10, T, T), 100).ScoreDocs; Assert.AreEqual(11, result.Length, "find all"); reader.Dispose(); dir.Dispose(); } } }