context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System.Drawing; using System.Windows.Forms; using BorderSkin.BorderSkinning.Skin; using LayeredForms; using LayeredForms.Utilities; using WinApiWrappers; using Padding = System.Windows.Forms.Padding; namespace BorderSkin.BorderSkinning.Forms { public enum ResizingClickPosition { LeftCorner, RightCorner, TopSizing, None } public delegate void SizingMouseMoveEventHandler(ResizingClickPosition Type, MouseEventArgs e); public delegate void SizingMouseDownEventHandler(ResizingClickPosition Type, MouseEventArgs e); partial class SkinBorder : LayeredForm { private SkinableWindowBorder _SkinWindow; public Cursor TopCursor { get; set; } public Cursor LeftCornerCursor { get; set; } public Cursor RightCornerCursor { get; set; } private Cursor _normalCursor = Cursors.Default; public event SizingMouseMoveEventHandler SizingMouseMove; public event SizingMouseDownEventHandler SizingMouseDown; public SkinBorder(SkinableWindowBorder SkinWindow) { _SkinWindow = SkinWindow; Parent = SkinWindow.Parent; Width = 100; Height = 100; InitMouseHandlers(); ExcludeWindowBehindBlur = Parent.Handle; } private void DrawColorSchemeOverlay(ImageWithDeviceContext destImage) { // ImageRenderer.StretchImage(destImage, BackgroundColorImageOverlay, Width, Height, ContentRect, !Settings.Settings.Transparency); using (var g = Graphics.FromHdc(destImage.GetHdc())) { Rectangle bounds = new Rectangle(Point.Empty, Size); bounds.X = ContentPadding.Left; bounds.Y = ContentPadding.Top; bounds.Width -= ContentPadding.Right + ContentPadding.Left; bounds.Height -= ContentPadding.Bottom + ContentPadding.Top; g.FillRectangle(BackgroundColorBrushOverlay, bounds); } } private void MaskOut(ImageWithDeviceContext destImage) { ImageRenderer.MaskOutCorners(destImage, Width, SkinElement.FrameSize, SkinElement.MaskOutBitmap, SkinElement.StretchPadding, SkinElement.MaskOutColor, SkinElement.GetStateYPosition(Activated)); } private SkinElement _skinElement; public SkinElement SkinElement { get { return _skinElement; } set { _skinElement = value; } } protected override void DrawBackground(ImageWithDeviceContext destImage) { DrawColorSchemeOverlay(destImage); MaskOut(destImage); base.DrawBackground(destImage); DrawReflection(BackgroundReflectionImage, destImage, Bounds, Activated, 150, Settings.Settings.ReflectionSpeed); } public ImageWithDeviceContext BackgroundReflectionImage { get { return _SkinWindow.Skin.ReflectionImage == null ? null : _SkinWindow.Skin.ReflectionImage.Frames[0]; } set { } } public Brush BackgroundColorBrushOverlay { get { return _SkinWindow.Skin.ColorScheme.GetBrush(Activated); } set { } } public bool Activated { get { return _SkinWindow.Activated; } set { } } public bool Maximized { get { return _SkinWindow.Maximized; } } public new TopLevelWindow Parent { get { return NativeWindow.Parent; } set { NativeWindow.Parent = value; } } public new bool TopMost { get { return NativeWindow.TopMost; } set { NativeWindow.TopMost = value; } } public new TopLevelWindow NativeWindow { get { return TopLevelWindow.FromHandle(Handle); } } private WindowBorderSkin Skin { get { return _SkinWindow.Skin; } } public bool AllowSizing { get { return !Maximized && Parent.SizeBox; } } public Cursor NormalCursor { get { return _normalCursor; } set { _normalCursor = value; Cursor = value; } } private void CornerCheck_MouseMove(object sender, MouseEventArgs e) { if (AllowSizing) { var sizingRect = Skin.SizingPadding; if (LeftCornerCursor == null) sizingRect.Left = 0; if (RightCornerCursor == null) sizingRect.Right = 0; if (TopCursor == null) sizingRect.Top = 0; ResizingClickPosition SizeTest = TestResizingClickPosition(e.Location, Size.Width, sizingRect); if (e.Clicks == 1 && e.Button == MouseButtons.Left) { if (SizingMouseDown != null) { SizingMouseDown(SizeTest, e); } } else { if (SizingMouseMove != null) { SizingMouseMove(SizeTest, e); } } } } private void InitMouseHandlers() { SizingMouseMove += CornerCursorHandler; MouseDown += CornerCheck_MouseMove; MouseMove += CornerCheck_MouseMove; } private void CornerCursorHandler(ResizingClickPosition Type, MouseEventArgs e) { switch (Type) { case ResizingClickPosition.LeftCorner: Cursor = LeftCornerCursor; break; case ResizingClickPosition.RightCorner: Cursor = RightCornerCursor; break; case ResizingClickPosition.TopSizing: Cursor = TopCursor; break; case ResizingClickPosition.None: if (Cursor == RightCornerCursor || Cursor == LeftCornerCursor || Cursor == TopCursor) { Cursor = NormalCursor; } break; } } private static ResizingClickPosition TestResizingClickPosition(Point MousePos, int BlockWidth, Padding sizingPadding) { if (MousePos.X < sizingPadding.Left) { return ResizingClickPosition.LeftCorner; } if (MousePos.X > (BlockWidth - sizingPadding.Right)) { return ResizingClickPosition.RightCorner; } if (MousePos.Y < sizingPadding.Top) { return ResizingClickPosition.TopSizing; } return ResizingClickPosition.None; } private void DrawReflection(ImageWithDeviceContext ReflectionImage, ImageWithDeviceContext destImage, Rectangle WindowBounds, bool Active, byte InActiveReflection, double RefSpeed) { if (ReflectionImage == null) return; Point srcLocation = new Point(ContentPadding.Left + (int)(WindowBounds.X / RefSpeed), ContentPadding.Top + (int)(WindowBounds.Y / RefSpeed)); Point destLocation = new Point(ContentPadding.Left, ContentPadding.Top); if (srcLocation.X < 0) { destLocation.X = (srcLocation.X * -1) + ContentPadding.Left; srcLocation.X = 0; } if (srcLocation.Y < 0) { destLocation.Y = (srcLocation.Y * -1) + ContentPadding.Top; srcLocation.Y = 0; } //>> 1 change the size of the reflection image to the max window track size //LeftPositionOnScreen >>>>>>>> WindowScreen //LeftPositionOnImage >>>>>>>> MaxWindowTrackWidth Size reflectionSize = WindowBounds.Size; reflectionSize.Width -= (ContentPadding.Right + destLocation.X); reflectionSize.Height -= (ContentPadding.Bottom + destLocation.Y); //BitBlt(ReflectionImage.Buffer.Image.DC, 0, 0, _ // ReflectionSize.Width, ReflectionSize.Height, _ // ReflectionImage.Image.DC, SrcLocation.X, SrcLocation.Y, _ // CopyPixelOperation.SourceCopy) //ReflectionImage.MaskOut(ReflectionImage.Buffer.Image, Active, WindowBounds.Width) //AlphaBlend(BorderImage.Buffer.Image.DC, DestLocation.X, DestLocation.Y, _ // ReflectionSize.Width, ReflectionSize.Height, _ // ReflectionImage.Buffer.Image.DC, 0, 0, _ // ReflectionSize.Width, ReflectionSize.Height, Blend) destImage.AlphaBlendImage(ReflectionImage, srcLocation, destLocation, reflectionSize, Active ? (byte)255 : InActiveReflection); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace Microsoft.Protocols.TestTools.StackSdk.Networking.Rpce { /// <summary> /// RpceStub is a base class for RpceStubEncoder and RpceStubDecoder. /// Do not create an instance of this class directly. /// </summary> public abstract class RpceStub : IDisposable { /// <summary> /// Ranged NDR correlation check extension size. /// </summary> protected const byte RANGED_NDR_CORR_EXTENSION_SIZE = 12; /// <summary> /// Regular NDR correlation check extension size. /// </summary> protected const byte NDR_CORR_EXTENSION_SIZE = 2; /// <summary> /// Simple type bitmask of format char. /// </summary> protected const int FORMAT_CHAR_SIMPLE_TYPE_BITMASK = 0x0F; /// <summary> /// BufferSize, Marshall and Unmarshall routine bitmask of format char. /// </summary> protected const int FORMAT_CHAR_ROUTINE_BITMASK = 0x3F; /// <summary> /// Size of context handle transferred on wire. /// </summary> protected const int CONTEXT_HANDLE_WIRE_SIZE = 20; /// <summary> /// Context handle alignment. /// </summary> protected const int CONTEXT_HANDLE_ALIGNMENT = 4; // RPC stub descriptor and stub message. internal NativeMethods.MIDL_STUB_DESC stubDesc; internal IntPtr pStubMsg; private List<NativeMethods.EXPR_EVAL> exprEvalList; // Keep reference to allocated memory, release them at Dispose. private List<IntPtr> allocatedMemoryList; #region IDisposable Members /// <summary> /// Dispose method. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose method. /// </summary> /// <param name="disposing"> /// True to release both managed and unmanaged resources.<para/> /// False to release unmanaged resources only. /// </param> protected virtual void Dispose(bool disposing) { if (disposing) { // Release managed resources. } // Release unmanaged resources. if (allocatedMemoryList != null) { for (int i = 0; i < allocatedMemoryList.Count; i++) { Marshal.FreeHGlobal(allocatedMemoryList[i]); } allocatedMemoryList = null; } if (stubDesc.RpcInterfaceInformation != IntPtr.Zero) { Marshal.FreeHGlobal(stubDesc.RpcInterfaceInformation); stubDesc.RpcInterfaceInformation = IntPtr.Zero; } if (stubDesc.apfnExprEval != IntPtr.Zero) { Marshal.FreeHGlobal(stubDesc.apfnExprEval); stubDesc.apfnExprEval = IntPtr.Zero; } if (stubDesc.pFormatTypes != IntPtr.Zero) { Marshal.FreeHGlobal(stubDesc.pFormatTypes); stubDesc.pFormatTypes = IntPtr.Zero; } } /// <summary> /// finalizer /// </summary> ~RpceStub() { Dispose(false); } #endregion /// <summary> /// constructor. /// </summary> /// <param name="runtimeTargetPlatform">Runtime platform, x86 or amd64.</param> /// <param name="typeFormatString">Type format string generated by MIDL.</param> /// <param name="exprEvalRoutines">ExprEvalRoutines generated by MIDL if exists.</param> /// <exception cref="ArgumentNullException"> /// Thrown when typeFormatString is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when runtimeTargetPlatform doesn't match current platform at runtime. /// </exception> protected RpceStub( RpceStubTargetPlatform runtimeTargetPlatform, byte[] typeFormatString, RpceStubExprEval[] exprEvalRoutines) { if (typeFormatString == null) { throw new ArgumentNullException("typeFormatString"); } if ((IntPtr.Size == sizeof(Int32) && (runtimeTargetPlatform & RpceStubTargetPlatform.X86) != RpceStubTargetPlatform.X86) || (IntPtr.Size == sizeof(Int64) && (runtimeTargetPlatform & RpceStubTargetPlatform.Amd64) != RpceStubTargetPlatform.Amd64)) { throw new InvalidOperationException("Invalid target platform."); } allocatedMemoryList = new List<IntPtr>(); #region RPC_CLIENT_INTERFACE rpcClientInterface NativeMethods.RPC_CLIENT_INTERFACE rpcClientInterface = new NativeMethods.RPC_CLIENT_INTERFACE(); rpcClientInterface.Length = (uint)Marshal.SizeOf(typeof(NativeMethods.RPC_CLIENT_INTERFACE)); rpcClientInterface.InterfaceId.SyntaxGUID = RpceStubEncoder.RPCE_BIND_ONLY_SERVER.IF_ID; rpcClientInterface.InterfaceId.SyntaxVersion.MajorVersion = RpceStubEncoder.RPCE_BIND_ONLY_SERVER.IF_VERS_MAJOR; rpcClientInterface.InterfaceId.SyntaxVersion.MinorVersion = RpceStubEncoder.RPCE_BIND_ONLY_SERVER.IF_VERS_MINOR; rpcClientInterface.TransferSyntax.SyntaxGUID = RpceUtility.NDR_INTERFACE_UUID; rpcClientInterface.TransferSyntax.SyntaxVersion.MajorVersion = RpceUtility.NDR_INTERFACE_MAJOR_VERSION; rpcClientInterface.TransferSyntax.SyntaxVersion.MinorVersion = RpceUtility.NDR_INTERFACE_MINOR_VERSION; rpcClientInterface.DispatchTable = IntPtr.Zero; rpcClientInterface.RpcProtseqEndpointCount = 0; rpcClientInterface.RpcProtseqEndpoint = IntPtr.Zero; rpcClientInterface.Reserved = 0; rpcClientInterface.InterpreterInfo = IntPtr.Zero; rpcClientInterface.Flags = 0x00000000; #endregion #region MIDL_STUB_DESC stubDesc stubDesc = new NativeMethods.MIDL_STUB_DESC(); stubDesc.RpcInterfaceInformation = Marshal.AllocHGlobal(Marshal.SizeOf(rpcClientInterface)); Marshal.StructureToPtr(rpcClientInterface, stubDesc.RpcInterfaceInformation, false); stubDesc.pfnAllocate = new NativeMethods.PfnAllocate(MIDL_user_allocate); stubDesc.pfnFree = new NativeMethods.PfnFree(MIDL_user_free); stubDesc.apfnNdrRundownRoutines = IntPtr.Zero; stubDesc.aGenericBindingRoutinePairs = IntPtr.Zero; if (exprEvalRoutines == null || exprEvalRoutines.Length == 0) { stubDesc.apfnExprEval = IntPtr.Zero; } else { exprEvalList = new List<NativeMethods.EXPR_EVAL>(exprEvalRoutines.Length); stubDesc.apfnExprEval = Marshal.AllocHGlobal(IntPtr.Size * exprEvalRoutines.Length); for (int i = 0; i < exprEvalRoutines.Length; i++) { RpceStubExprEvalCallback callback = new RpceStubExprEvalCallback(this, exprEvalRoutines[i]); NativeMethods.EXPR_EVAL exprEval = new NativeMethods.EXPR_EVAL(callback.EXPR_EVAL); IntPtr funcPtr = Marshal.GetFunctionPointerForDelegate(exprEval); Marshal.WriteIntPtr(stubDesc.apfnExprEval, IntPtr.Size * i, funcPtr); //http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.getfunctionpointerfordelegate.aspx //Caller must manually keep the delegate from being collected by // the garbage collector from managed code. exprEvalList.Add(exprEval); } } stubDesc.aXmitQuintuple = IntPtr.Zero; stubDesc.pFormatTypes = Marshal.AllocHGlobal(typeFormatString.Length); Marshal.Copy(typeFormatString, 0, stubDesc.pFormatTypes, typeFormatString.Length); stubDesc.fCheckBounds = 0; /* -error bounds_check flag : "midl /error none" */ stubDesc.Version = 0x50000; /* Ndr library version */ stubDesc.pMallocFreeStruct = IntPtr.Zero; stubDesc.MIDLVersion = 0x70001e6; /* MIDL Version 7.0.486 */ stubDesc.CommFaultOffsets = IntPtr.Zero; stubDesc.aUserMarshalQuadruple = IntPtr.Zero; stubDesc.NotifyRoutineTable = IntPtr.Zero; /* notify & notify_flag routine table */ stubDesc.mFlags = 0x1; /* MIDL flag */ stubDesc.CsRoutineTables = IntPtr.Zero; /* cs routines */ stubDesc.ProxyServerInfo = IntPtr.Zero; /* proxy/server native */ stubDesc.pExprInfo = IntPtr.Zero; /* Reserved5 */ #endregion } /// <summary> /// Callback function to allocate memory, used by NDR engine.<para/> /// Copied from midl.exe generated stub code. /// </summary> /// <param name="s">Buffer size.</param> /// <returns>Pointer to allocated memory.</returns> private IntPtr MIDL_user_allocate(uint s) { IntPtr p = Marshal.AllocHGlobal((int)s); //Save the pointer, release it at MIDL_user_free or Dispose(). allocatedMemoryList.Add(p); return p; } /// <summary> /// Callback function to free allocated memory , used by NDR engine.<para/> /// Copied from midl.exe generated stub code. /// </summary> /// <param name="p">Pointer to allocated memory.</param> private void MIDL_user_free(IntPtr p) { allocatedMemoryList.Remove(p); Marshal.FreeHGlobal(p); } #region Get/Set MIDL_STUB_MESSAGE fields /// <summary> /// Get BufferLength field of MIDL_STUB_MESSAGE. /// </summary> /// <returns>The value of BufferLength field.</returns> //We want to use a method to get BufferLength, suppress fxcop CA1024. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public uint GetBufferLength() { IntPtr offset = Marshal.OffsetOf(typeof(NativeMethods.MIDL_STUB_MESSAGE), "BufferLength"); return (uint)Marshal.ReadInt32(pStubMsg, offset.ToInt32()); } /// <summary> /// Set BufferLength field of MIDL_STUB_MESSAGE. /// </summary> /// <param name="length">The value of BufferLength field.</param> public void SetBufferLength(uint length) { IntPtr offset = Marshal.OffsetOf(typeof(NativeMethods.MIDL_STUB_MESSAGE), "BufferLength"); Marshal.WriteInt32(pStubMsg, offset.ToInt32(), (int)length); } /// <summary> /// Get StackTop field of MIDL_STUB_MESSAGE. /// </summary> /// <returns>The value of StackTop field.</returns> //We want to use a method to get StackTop, suppress fxcop CA1024. [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public IntPtr GetStackTop() { IntPtr offset = Marshal.OffsetOf(typeof(NativeMethods.MIDL_STUB_MESSAGE), "StackTop"); return Marshal.ReadIntPtr(pStubMsg, offset.ToInt32()); } /// <summary> /// Set StackTop field of MIDL_STUB_MESSAGE. /// </summary> /// <param name="stackTop">The value of StackTop field.</param> public void SetStackTop(IntPtr stackTop) { IntPtr offset = Marshal.OffsetOf(typeof(NativeMethods.MIDL_STUB_MESSAGE), "StackTop"); Marshal.WriteIntPtr(pStubMsg, offset.ToInt32(), stackTop); } /// <summary> /// Get MaxCount field of MIDL_STUB_MESSAGE. /// </summary> /// <param name="maxCount">The value of MaxCount field.</param> public void SetMaxCount(uint maxCount) { IntPtr offset = Marshal.OffsetOf(typeof(NativeMethods.MIDL_STUB_MESSAGE), "MaxCount"); Marshal.WriteIntPtr(pStubMsg, offset.ToInt32(), new IntPtr(maxCount)); } /// <summary> /// Get Offset field of MIDL_STUB_MESSAGE. /// </summary> /// <param name="offset">The value of Offset field.</param> public void SetOffset(uint offset) { IntPtr ofs = Marshal.OffsetOf(typeof(NativeMethods.MIDL_STUB_MESSAGE), "Offset"); Marshal.WriteInt32(pStubMsg, ofs.ToInt32(), (int)offset); } /// <summary> /// Get CorrDespIncrement field of MIDL_STUB_MESSAGE. /// </summary> /// <param name="corrDespIncrement">The value of CorrDespIncrement field.</param> public void SetCorrDespIncrement(byte corrDespIncrement) { IntPtr ofs = Marshal.OffsetOf(typeof(NativeMethods.MIDL_STUB_MESSAGE), "fBufferValid"); Marshal.WriteInt32(pStubMsg, ofs.ToInt32(), (int)corrDespIncrement); } #endregion /// <summary> /// Save parameters into StackTop of MIDL_STUB_MESSAGE. /// </summary> /// <param name="procFormatString">ProcFormatString generated by MIDL.</param> /// <param name="offset">Offset of a procedure in procFormatString.</param> /// <param name="stackSize">Stack size of all parameters.</param> /// <param name="parameters">Parameters</param> [SuppressMessage("Microsoft.Usage", "CA2233:OperationsShouldNotOverflow")] protected void SaveParametersIntoStack(byte[] procFormatString, int offset, int stackSize, Int3264[] parameters) { // ensure the stack is large enough, because we may write the last parameter over size. byte[] stack = new byte[stackSize + sizeof(long)]; for (int i = 0; i < parameters.Length; i++) { offset += sizeof(RpceParameterAttributes); // skip flags ushort stackOffset = BitConverter.ToUInt16(procFormatString, offset); offset += sizeof(ushort); offset += sizeof(ushort); //skip typeFormaString offset, move to next parameter. Buffer.BlockCopy( BitConverter.GetBytes(parameters[i].ToInt64()), 0, stack, stackOffset, sizeof(ulong)); } IntPtr ptr = Marshal.AllocHGlobal(stack.Length); Marshal.Copy(stack, 0, ptr, stack.Length); SetStackTop(ptr); FreeMemoryAtDispose(ptr); } /// <summary> /// Free specified memory at Dispose. /// </summary> /// <param name="ptr">Pointer to the memory.</param> protected void FreeMemoryAtDispose(IntPtr ptr) { allocatedMemoryList.Add(ptr); } /// <summary> /// The NdrConvert function converts the network buffer from the data representation of /// the sender to the data representation of the receiver if they are different. /// </summary> /// <param name="formatStringOffset">Offset of a parameter in typeFormatString.</param> public void NdrConvertIfNecessary(int formatStringOffset) { IntPtr offset; offset = Marshal.OffsetOf(typeof(NativeMethods.MIDL_STUB_MESSAGE), "RpcMsg"); IntPtr pRpcMsg = Marshal.ReadIntPtr(pStubMsg, offset.ToInt32()); offset = Marshal.OffsetOf(typeof(NativeMethods.RPC_MESSAGE), "DataRepresentation"); uint dataRepresentation = (uint)Marshal.ReadInt32(pRpcMsg, offset.ToInt32()); if ((dataRepresentation & 0x0000FFFFU) != NativeMethods.NDR_LOCAL_DATA_REPRESENTATION) { IntPtr fmt = IntPtrUtility.Add(stubDesc.pFormatTypes, formatStringOffset); NativeMethods.NdrConvert(pStubMsg, fmt); } } /// <summary> /// Performs an RpcFreeBuffer. /// </summary> public void NdrFreeBuffer() { NativeMethods.NdrFreeBuffer(pStubMsg); } } }
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen //Copyright 2006-2011 Jeroen van Menen // // 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 Copyright using System; using System.Diagnostics; using System.Threading; using Microsoft.Win32; using SHDocVw; using WatiN.Core.Constraints; using WatiN.Core.DialogHandlers; using WatiN.Core.Exceptions; using WatiN.Core.Interfaces; using WatiN.Core.Native.InternetExplorer; using WatiN.Core.Logging; using WatiN.Core.Native; using WatiN.Core.Properties; using WatiN.Core.UtilityClasses; namespace WatiN.Core { /// <summary> /// This is the main class to access a webpage in Internet Explorer to /// get to all the elements and (i)frames on the page. /// /// </summary> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// IE ie = new IE("http://watin.sourceforge.net"); /// ie.Link(Find.ByText("RSS Feeds")).Click; /// ie.Close; /// } /// } /// } /// </code> /// </example> public class IE : Browser { private bool autoClose = true; private bool isDisposed; private IEBrowser _ieBrowser; /// <summary> /// Creates a collection of new IE instances associated with open Internet Explorer windows. /// </summary> /// <returns>An IE instance which is complete loaded.</returns> /// <example> /// This code snippet illustrates the use of this method to found out the number of open /// Internet Explorer windows. /// <code>int IECount = IE.InternetExplorers.Length;</code> /// </example> public static IECollection InternetExplorers() { return new IECollection(); } /// <summary> /// Creates a collection of new IE instances associated with open Internet Explorer windows. Use this /// method if you don't want WatiN to wait until a document is fully loaded before returning it. /// This might be handy in situations where you encounter Internet Explorer instances which are always /// busy loading and that way blocks itteration through the collection. /// </summary> /// <returns>An IE instance which might not have been complete loaded yet.</returns> /// <example> /// This code snippet illustrates the use of this method to itterate through all internet explorer instances. /// <code> /// foreach (IE ie in IE.InternetExplorersNoWait) /// { /// // do something but be aware that the page might not be completely loaded yet. /// } /// </code> /// </example> public static IECollection InternetExplorersNoWait() { return new IECollection(false); } /// <summary> /// Opens a new Internet Explorer with a blank page. /// <note> /// When the <see cref="WatiN.Core.IE" /> /// instance is destroyed the created Internet Explorer window will also be closed. /// </note> /// </summary> /// <remarks> /// You could also use one of the overloaded constructors. /// </remarks> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// IE ie = new IE(); /// ie.GoTo("http://watin.sourceforge.net"); /// } /// } /// } /// </code> /// </example> public IE() { CreateNewIEAndGoToUri(new Uri("about:blank"), null, false); } /// <summary> /// Opens a new Internet Explorer with a blank page. /// <note> /// When the <see cref="WatiN.Core.IE" /> /// instance is destroyed the created Internet Explorer window will also be closed. /// </note> /// </summary> /// <param name="createInNewProcess">if set to <c>true</c> the IE instance is created in a new process.</param> /// <remarks> /// You could also use one of the overloaded constructors. /// </remarks> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// IE ie = new IE(); /// ie.GoTo("http://watin.sourceforge.net"); /// } /// } /// } /// </code> /// </example> public IE(bool createInNewProcess) { CreateNewIEAndGoToUri(new Uri("about:blank"), null, createInNewProcess); } /// <summary> /// Opens a new Internet Explorer and navigates to the given <paramref name="url"/>. /// <note> /// When the <see cref="WatiN.Core.IE" /> /// instance is destroyed the created Internet Explorer window will also be closed. /// </note> /// </summary> /// <param name="url">The URL to open</param> /// <remarks> /// You could also use one of the overloaded constructors. /// </remarks> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public OpenWatiNWebsite() /// { /// IE ie = new IE("http://watin.sourceforge.net"); /// } /// } /// } /// </code> /// </example> public IE(string url) { CreateNewIEAndGoToUri(UtilityClass.CreateUri(url), null, false); } /// <summary> /// Opens a new Internet Explorer and navigates to the given <paramref name="url"/>. /// <note> /// When the <see cref="WatiN.Core.IE" /> /// instance is destroyed the created Internet Explorer window will also be closed. /// </note> /// </summary> /// <param name="url">The URL to open</param> /// <param name="createInNewProcess">if set to <c>true</c> the IE instance is created in a new process.</param> /// <remarks> /// You could also use one of the overloaded constructors. /// </remarks> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public OpenWatiNWebsite() /// { /// IE ie = new IE("http://watin.sourceforge.net"); /// } /// } /// } /// </code> /// </example> public IE(string url, bool createInNewProcess) { CreateNewIEAndGoToUri(UtilityClass.CreateUri(url), null, createInNewProcess); } /// <summary> /// Opens a new Internet Explorer and navigates to the given <paramref name="uri"/>. /// <note> /// When the <see cref="WatiN.Core.IE" /> /// instance is destroyed the created Internet Explorer window will also be closed. /// </note> /// </summary> /// <param name="uri">The Uri to open</param> /// <remarks> /// You could also use one of the overloaded constructors. /// </remarks> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using System; /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public OpenWatiNWebsite() /// { /// IE ie = new IE(new Uri("http://watin.sourceforge.net")); /// } /// } /// } /// </code> /// </example> public IE(Uri uri) { CreateNewIEAndGoToUri(uri, null, false); } /// <summary> /// Opens a new Internet Explorer and navigates to the given <paramref name="uri"/>. /// <note> /// When the <see cref="WatiN.Core.IE" /> /// instance is destroyed the created Internet Explorer window will also be closed. /// </note> /// </summary> /// <param name="uri">The Uri to open</param> /// <param name="createInNewProcess">if set to <c>true</c> the IE instance is created in a new process.</param> /// <remarks> /// You could also use one of the overloaded constructors. /// </remarks> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using System; /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public OpenWatiNWebsite() /// { /// IE ie = new IE(new Uri("http://watin.sourceforge.net")); /// } /// } /// } /// </code> /// </example> public IE(Uri uri, bool createInNewProcess) { CreateNewIEAndGoToUri(uri, null, createInNewProcess); } /// <summary> /// Opens a new Internet Explorer and navigates to the given <paramref name="url"/>. /// </summary> /// <param name="url">The Url to open</param> /// <param name="logonDialogHandler">A <see cref="LogonDialogHandler"/> class instanciated with the logon credentials.</param> /// <remarks> /// You could also use one of the overloaded constructors. /// </remarks> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge leaving the created Internet Explorer open. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// LogonDialogHandler logon = new LogonDialogHandler("username", "password"); /// IE ie = new IE("http://watin.sourceforge.net", logon); /// } /// } /// } /// </code> /// </example> public IE(string url, LogonDialogHandler logonDialogHandler) { CreateNewIEAndGoToUri(UtilityClass.CreateUri(url), logonDialogHandler, false); } /// <summary> /// Opens a new Internet Explorer and navigates to the given <paramref name="url"/>. /// </summary> /// <param name="url">The Url to open</param> /// <param name="logonDialogHandler">A <see cref="LogonDialogHandler"/> class instanciated with the logon credentials.</param> /// <param name="createInNewProcess">if set to <c>true</c> the IE instance is created in a new process.</param> /// <remarks> /// You could also use one of the overloaded constructors. /// </remarks> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge leaving the created Internet Explorer open. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// LogonDialogHandler logon = new LogonDialogHandler("username", "password"); /// IE ie = new IE("http://watin.sourceforge.net", logon); /// } /// } /// } /// </code> /// </example> public IE(string url, LogonDialogHandler logonDialogHandler, bool createInNewProcess) { CreateNewIEAndGoToUri(UtilityClass.CreateUri(url), logonDialogHandler, createInNewProcess); } /// <summary> /// Opens a new Internet Explorer and navigates to the given <paramref name="uri"/>. /// </summary> /// <param name="uri">The Uri to open</param> /// <param name="logonDialogHandler">A <see cref="LogonDialogHandler"/> class instanciated with the logon credentials.</param> /// <remarks> /// You could also use one of the overloaded constructors. /// </remarks> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge leaving the created Internet Explorer open. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// LogonDialogHandler logon = new LogonDialogHandler("username", "password"); /// IE ie = new IE(new Uri("http://watin.sourceforge.net"), logon); /// } /// } /// } /// </code> /// </example> public IE(Uri uri, LogonDialogHandler logonDialogHandler) { CreateNewIEAndGoToUri(uri, logonDialogHandler, false); } /// <summary> /// Opens a new Internet Explorer and navigates to the given <paramref name="uri"/>. /// </summary> /// <param name="uri">The Uri to open</param> /// <param name="logonDialogHandler">A <see cref="LogonDialogHandler"/> class instanciated with the logon credentials.</param> /// <param name="createInNewProcess">if set to <c>true</c> the IE instance is created in a new process.</param> /// <remarks> /// You could also use one of the overloaded constructors. /// </remarks> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge leaving the created Internet Explorer open. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// LogonDialogHandler logon = new LogonDialogHandler("username", "password"); /// IE ie = new IE(new Uri("http://watin.sourceforge.net"), logon); /// } /// } /// } /// </code> /// </example> public IE(Uri uri, LogonDialogHandler logonDialogHandler, bool createInNewProcess) { CreateNewIEAndGoToUri(uri, logonDialogHandler, createInNewProcess); } /// <summary> /// (Re)Use existing <see cref="IEBrowser"/> object. /// </summary> /// <param name="ieBrowser">An object implementing <see cref="IEBrowser"/>.</param> public IE(IEBrowser ieBrowser) { _ieBrowser = ieBrowser; } /// <summary> /// Use existing InternetExplorer object. The param is of type /// object because otherwise all projects using WatiN should also /// reference the Interop.SHDocVw assembly. /// </summary> /// <param name="iwebBrowser2">An object implementing IWebBrowser2 (like Interop.SHDocVw.InternetExplorer object)</param> public IE(object iwebBrowser2) : this(iwebBrowser2, true) { } protected internal IE(object iwebBrowser2, bool finishInitialization) { CheckThreadApartmentStateIsSTA(); var internetExplorer = iwebBrowser2 as IWebBrowser2; if (internetExplorer == null) { throw new ArgumentException("iwebBrowser2 needs to implement shdocvw.IWebBrowser2"); } _ieBrowser = CreateIEBrowser(internetExplorer); if (finishInitialization) FinishInitialization(null); } private IEBrowser CreateIEBrowser(IWebBrowser2 IWebBrowser2Instance) { return new IEBrowser(IWebBrowser2Instance); } private void CreateNewIEAndGoToUri(Uri uri, IDialogHandler logonDialogHandler, bool createInNewProcess) { CheckThreadApartmentStateIsSTA(); UtilityClass.MoveMousePoinerToTopLeft(Settings.AutoMoveMousePointerToTopLeft); if (createInNewProcess) { Logger.LogAction("Creating IE instance in a new process"); _ieBrowser = CreateIEPartiallyInitializedInNewProcess(); } else { Logger.LogAction("Creating IE instance"); _ieBrowser = CreateIEBrowser(new InternetExplorerClass()); } StartDialogWatcher(); if (logonDialogHandler != null) { // remove other logon dialog handlers since only one handler // can effectively handle the logon dialog. DialogWatcher.RemoveAll(new LogonDialogHandler("a", "b")); // Add the (new) logonHandler DialogWatcher.Add(logonDialogHandler); } FinishInitialization(uri); } private static IEBrowser CreateIEPartiallyInitializedInNewProcess() { var m_Proc = CreateIExploreInNewProcess(); var helper = new AttachToIeHelper(); var action = new TryFuncUntilTimeOut(TimeSpan.FromSeconds(Settings.AttachToBrowserTimeOut)) { SleepTime = TimeSpan.FromMilliseconds(500) }; var ie = action.Try(() => { m_Proc.Refresh(); var mainWindowHandle = m_Proc.MainWindowHandle; return mainWindowHandle != IntPtr.Zero ? helper.FindIEPartiallyInitialized(new AttributeConstraint("hwnd", mainWindowHandle.ToString())) : null; }); if (ie != null) return ie._ieBrowser; throw new BrowserNotFoundException("IE", "Timeout while waiting to attach to newly created instance of IE.", Settings.AttachToBrowserTimeOut); } private static Process CreateIExploreInNewProcess() { var arguments = "about:blank"; if (GetMajorIEVersion() >= 8 && Settings.MakeNewIe8InstanceNoMerge) arguments = "-nomerge " + arguments; var m_Proc = Process.Start("IExplore.exe", arguments); if (m_Proc == null) throw new WatiNException("Could not start IExplore.exe process"); return m_Proc; } internal static int GetMajorIEVersion() { var ieKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer"); if (ieKey == null) return 0; var version = (string) ieKey.GetValue("Version"); return int.Parse(version.Substring(0, version.IndexOf('.'))); } private static void CheckThreadApartmentStateIsSTA() { var isSTA = (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA); if (!isSTA) { throw new ThreadStateException("The CurrentThread needs to have it's ApartmentState set to ApartmentState.STA to be able to automate Internet Explorer."); } } internal void FinishInitialization(Uri uri) { // Due to UAC in Vista the navigate has to be done // before showing the new Internet Explorer instance if (uri != null) { GoTo(uri); } _ieBrowser.Visible = Settings.MakeNewIeInstanceVisible; base.FinishInitialization(); } /// <summary> /// Use this method to gain access to the IWebBrowser2 interface of Internet Explorer. /// Do this by referencing the Interop.SHDocVw assembly (supplied in the WatiN distribution) /// and cast the return value of this method to type SHDocVw.IWebBrowser2. /// </summary> public object InternetExplorer { get { return _ieBrowser.WebBrowser; } } /// <summary> /// Closes the referenced Internet Explorer. Almost /// all other functionality in this class and the element classes will give /// exceptions when used after closing the browser. /// </summary> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge. /// <code> /// using WatiN.Core; /// using System.Diagnostics; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// IE ie = new IE("http://watin.sourceforge.net"); /// Debug.WriteLine(ie.Html); /// ie.Close; /// } /// } /// } /// </code> /// </example> public override void Close() { if (isDisposed) return; if (IsInternetExplorerStillAvailable()) { Logger.LogAction((LogFunction log) => { log("Closing browser '{0}'", Title); }); } DisposeAndCloseIE(true); } /// <summary> /// Closes then reopens Internet Explorer and navigates to the given <paramref name="uri"/>. /// </summary> /// <param name="uri">The Uri to open</param> /// <param name="logonDialogHandler">A <see cref="LogonDialogHandler"/> class instanciated with the logon credentials.</param> /// <param name="createInNewProcess">if set to <c>true</c> the IE instance is created in a new process.</param> /// <remarks> /// You could also use one of the overloaded methods. /// </remarks> /// <example> /// The following example creates a new Internet Explorer instances and navigates to /// the WatiN Project website on SourceForge leaving the created Internet Explorer open. /// <code> /// using WatiN.Core; /// /// namespace NewIEExample /// { /// public class WatiNWebsite /// { /// public WatiNWebsite() /// { /// LogonDialogHandler logon = new LogonDialogHandler("username", "password"); /// IE ie = new IE(new Uri("http://watin.sourceforge.net"), logon); /// ie.Reopen(); /// } /// } /// } /// </code> /// </example> public void Reopen(Uri uri, LogonDialogHandler logonDialogHandler, bool createInNewProcess) { Close(); Recycle(); CreateNewIEAndGoToUri(uri, logonDialogHandler, createInNewProcess); } // TODO: This should be dealt with in the IEBrowser as should ReOpen(uri, logon...) public override void Reopen() { Reopen(new Uri("about:blank"), null, true); } protected override void Recycle() { base.Recycle(); isDisposed = false; } private void DisposeAndCloseIE(bool closeIE) { if (isDisposed) return; Logger.LogDebug(Resources.IE_Dispose); if (closeIE && IsInternetExplorerStillAvailable()) { // Close all open HTMLDialogs HtmlDialogs.CloseAll(); } base.Dispose(true); if (closeIE && IsInternetExplorerStillAvailable()) { // Ask IE to close _ieBrowser.Quit(); } _ieBrowser = null; if (closeIE) { // Wait for IE to close to prevent RPC errors when creating // a new WatiN.Core.IE instance. Thread.Sleep(1000); } isDisposed = true; } /// <summary> /// Closes <i>all</i> running instances of Internet Explorer by killing the /// process these instances run in. /// </summary> public virtual void ForceClose() { if (isDisposed) { throw new ObjectDisposedException("Internet Explorer", "The Internet Explorer instance is already disposed. ForceClose can't be performed."); } Logger.LogAction("Force closing all IE instances"); var iePid = ProcessID; DisposeAndCloseIE(true); try { // Force Internet Explorer instances to close Process.GetProcessById(iePid).Kill(); } catch (ArgumentException) { // ignore: IE is no longer running } } /// <summary> /// Clears all browser cookies. /// </summary> /// <remarks> /// Internet Explorer maintains an internal cookie cache that does not immediately /// expire when cookies are cleared. This is the case even when the cookies are /// cleared using the Internet Options dialog. If cookies have been used by /// the current browser session it may be necessary to <see cref="Browser.Reopen()" /> the /// browser to ensure the internal cookie cache is flushed. Therefore it is /// recommended to clear cookies at the beginning of the test before navigating /// to any pages (other than "about:blank") to avoid having to reopen the browser. /// </remarks> /// <example> /// <code> /// // Clear cookies first. /// IE ie = new IE(); /// ie.ClearCookies(); /// /// // Then go to the site and sign in. /// ie.GoTo("http://www.example.com/"); /// ie.Link(Find.ByText("Sign In")).Click(); /// </code> /// </example> /// <seealso cref="Browser.Reopen()"/> public void ClearCookies() { Logger.LogAction("Clearing cookies for all sites."); WinInet.ClearCookies(null); } /// <summary> /// Clears the browser cookies associated with a particular site and to /// any of the site's subdomains. /// </summary> /// <remarks> /// Internet Explorer maintains an internal cookie cache that does not immediately /// expire when cookies are cleared. This is the case even when the cookies are /// cleared using the Internet Options dialog. If cookies have been used by /// the current browser session it may be necessary to <see cref="Browser.Reopen()" /> the /// browser to ensure the internal cookie cache is flushed. Therefore it is /// recommended to clear cookies at the beginning of the test before navigating /// to any pages (other than "about:blank") to avoid having to reopen the browser. /// </remarks> /// <param name="url">The site url associated with the cookie.</param> /// <example> /// <code> /// // Clear cookies first. /// IE ie = new IE(); /// ie.ClearCookies("http://www.example.com/"); /// /// // Then go to the site and sign in. /// ie.GoTo("http://www.example.com/"); /// ie.Link(Find.ByText("Sign In")).Click(); /// </code> /// </example> /// <seealso cref="Browser.Reopen()"/> public void ClearCookies(string url) { if (url == null) throw new ArgumentNullException("url"); Logger.LogAction("Clearing cookies for site '{0}'.", url); WinInet.ClearCookies(url); } /// <summary> /// Clears the browser cache but leaves cookies alone. /// </summary> /// <example> /// <code> /// // Clear the cache and cookies. /// IE ie = new IE(); /// ie.ClearCache(); /// ie.ClearCookies(); /// /// // Then go to the site and sign in. /// ie.GoTo("http://www.example.com/"); /// ie.Link(Find.ByText("Sign In")).Click(); /// </code> /// </example> /// <seealso cref="Browser.Reopen()"/> public void ClearCache() { Logger.LogAction("Clearing browser cache."); WinInet.ClearCache(); } /// <summary> /// Gets the value of a cookie. /// </summary> /// <remarks> /// This method cannot retrieve the value of cookies protected by the <c>httponly</c> security option. /// </remarks> /// <param name="url">The site url associated with the cookie.</param> /// <param name="cookieName">The cookie name.</param> /// <returns>The cookie data of the form: /// &lt;name&gt;=&lt;value&gt;[; &lt;name&gt;=&lt;value&gt;]... /// [; expires=&lt;date:DAY, DD-MMM-YYYY HH:MM:SS GMT&gt;][; domain=&lt;domain_name&gt;] /// [; path=&lt;some_path&gt;][; secure][; httponly]. Returns null if there are no associated cookies.</returns> /// <seealso cref="ClearCookies()"/> /// <seealso cref="SetCookie(string,string)"/> public string GetCookie(string url, string cookieName) { return WinInet.GetCookie(url, cookieName); } public System.Net.CookieContainer GetCookieContainerForUrl(Uri url) { return WinInet.GetCookieContainerForUrl(url); } public System.Net.CookieCollection GetCookiesForUrl(Uri url) { return WinInet.GetCookiesForUrl(url); } /// <summary> /// Sets the value of a cookie. /// </summary> /// <remarks> /// If no expiration date is specified, the cookie expires when the session ends. /// </remarks> /// <param name="url">The site url associated with the cookie.</param> /// <param name="cookieData">The cookie data of the form: /// &lt;name&gt;=&lt;value&gt;[; &lt;name&gt;=&lt;value&gt;]... /// [; expires=&lt;date:DAY, DD-MMM-YYYY HH:MM:SS GMT&gt;][; domain=&lt;domain_name&gt;] /// [; path=&lt;some_path&gt;][; secure][; httponly].</param> /// <seealso cref="ClearCookies()"/> /// <seealso cref="GetCookie(string,string)"/> public void SetCookie(string url, string cookieData) { WinInet.SetCookie(url, cookieData); } private bool IsInternetExplorerStillAvailable() { // Call a property of the // ie instance to see of it isn't disposed by // another IE instance. return UtilityClass.TryFuncIgnoreException(() => hWnd != IntPtr.Zero); } /// <summary> /// Waits till the webpage, it's frames and all it's elements are loaded. This /// function is called by WatiN after each action (like clicking a link) so you /// should have to use this function on rare occasions. /// </summary> /// <param name="waitForCompleteTimeOut">The number of seconds to wait before timing out</param> public override void WaitForComplete(int waitForCompleteTimeOut) { WaitForComplete(new IEWaitForComplete((IEBrowser) NativeBrowser, waitForCompleteTimeOut)); } #region IDisposable Members /// <summary> /// This method must be called by its inheritor to dispose references /// to internal resources. /// </summary> protected override void Dispose(bool disposing) { DisposeAndCloseIE(AutoClose); } #endregion /// <summary> /// Gets or sets a value indicating whether to auto close IE after destroying /// a reference to the corresponding IE instance. /// </summary> /// <value><c>true</c> when to auto close IE (this is the default); otherwise, <c>false</c>.</value> public bool AutoClose { get { return autoClose; } set { autoClose = value; } } /// <summary> /// Returns a collection of open HTML dialogs (modal as well as modeless). /// </summary> /// <value>The HTML dialogs.</value> public HtmlDialogCollection HtmlDialogs { get { return GetHtmlDialogs(true); } } /// <summary> /// Returns a collection of open HTML dialogs (modal as well as modeless). /// When itterating through this collection WaitForComplete will not be /// called on a HTML dialog before returning it from the collection. /// </summary> /// <value>The HTML dialogs.</value> public HtmlDialogCollection HtmlDialogsNoWait { get { return GetHtmlDialogs(false); } } private HtmlDialogCollection GetHtmlDialogs(bool waitForComplete) { return new HtmlDialogCollection(hWnd, waitForComplete); } public override INativeBrowser NativeBrowser { get { return _ieBrowser; } } /// <summary> /// Find a HtmlDialog by an attribute. Currently /// Find.ByUrl and Find.ByTitle are supported. /// </summary> /// <param name="findBy">The url of the html page shown in the dialog</param> public HtmlDialog HtmlDialog(Constraint findBy) { return FindHtmlDialog(findBy, Settings.AttachToBrowserTimeOut); } /// <summary> /// Find a HtmlDialog by an attribute within the given <paramref name="timeout" /> period. /// Currently Find.ByUrl and Find.ByTitle are supported. /// </summary> /// <param name="findBy">The url of the html page shown in the dialog</param> /// <param name="timeout">Number of seconds before the search times out.</param> public HtmlDialog HtmlDialog(Constraint findBy, int timeout) { return FindHtmlDialog(findBy, timeout); } public bool Visible { get { return _ieBrowser.Visible; } set { _ieBrowser.Visible = value; } } private HtmlDialog FindHtmlDialog(Constraint findBy, int timeout) { Logger.LogAction((LogFunction log) => { log("Busy finding HTMLDialog matching criteria: {0}", findBy); }); var action = new TryFuncUntilTimeOut(TimeSpan.FromSeconds(timeout)) { SleepTime = TimeSpan.FromMilliseconds(500) }; var result = action.Try(() => HtmlDialogs.First(findBy)); if (result == null) { throw new HtmlDialogNotFoundException(findBy.ToString(), timeout); } return result; } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface ICarrierServiceApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Get a carrierService by id /// </summary> /// <remarks> /// Returns the carrierService identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierServiceId">Id of carrierService to be returned.</param> /// <returns>CarrierService</returns> CarrierService GetCarrierServiceById (string carrierServiceId); /// <summary> /// Get a carrierService by id /// </summary> /// <remarks> /// Returns the carrierService identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierServiceId">Id of carrierService to be returned.</param> /// <returns>ApiResponse of CarrierService</returns> ApiResponse<CarrierService> GetCarrierServiceByIdWithHttpInfo (string carrierServiceId); /// <summary> /// Search carrierServices /// </summary> /// <remarks> /// Returns the list of carrierServices that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>List&lt;CarrierService&gt;</returns> List<CarrierService> GetCarrierServiceBySearchText (string searchText = null, int? page = null, int? limit = null); /// <summary> /// Search carrierServices /// </summary> /// <remarks> /// Returns the list of carrierServices that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>ApiResponse of List&lt;CarrierService&gt;</returns> ApiResponse<List<CarrierService>> GetCarrierServiceBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Get a carrierService by id /// </summary> /// <remarks> /// Returns the carrierService identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierServiceId">Id of carrierService to be returned.</param> /// <returns>Task of CarrierService</returns> System.Threading.Tasks.Task<CarrierService> GetCarrierServiceByIdAsync (string carrierServiceId); /// <summary> /// Get a carrierService by id /// </summary> /// <remarks> /// Returns the carrierService identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierServiceId">Id of carrierService to be returned.</param> /// <returns>Task of ApiResponse (CarrierService)</returns> System.Threading.Tasks.Task<ApiResponse<CarrierService>> GetCarrierServiceByIdAsyncWithHttpInfo (string carrierServiceId); /// <summary> /// Search carrierServices /// </summary> /// <remarks> /// Returns the list of carrierServices that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of List&lt;CarrierService&gt;</returns> System.Threading.Tasks.Task<List<CarrierService>> GetCarrierServiceBySearchTextAsync (string searchText = null, int? page = null, int? limit = null); /// <summary> /// Search carrierServices /// </summary> /// <remarks> /// Returns the list of carrierServices that match the given searchText. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of ApiResponse (List&lt;CarrierService&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<CarrierService>>> GetCarrierServiceBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class CarrierServiceApi : ICarrierServiceApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="CarrierServiceApi"/> class. /// </summary> /// <returns></returns> public CarrierServiceApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="CarrierServiceApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public CarrierServiceApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Get a carrierService by id Returns the carrierService identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierServiceId">Id of carrierService to be returned.</param> /// <returns>CarrierService</returns> public CarrierService GetCarrierServiceById (string carrierServiceId) { ApiResponse<CarrierService> localVarResponse = GetCarrierServiceByIdWithHttpInfo(carrierServiceId); return localVarResponse.Data; } /// <summary> /// Get a carrierService by id Returns the carrierService identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierServiceId">Id of carrierService to be returned.</param> /// <returns>ApiResponse of CarrierService</returns> public ApiResponse< CarrierService > GetCarrierServiceByIdWithHttpInfo (string carrierServiceId) { // verify the required parameter 'carrierServiceId' is set if (carrierServiceId == null) throw new ApiException(400, "Missing required parameter 'carrierServiceId' when calling CarrierServiceApi->GetCarrierServiceById"); var localVarPath = "/v1.0/carrierService/{carrierServiceId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (carrierServiceId != null) localVarPathParams.Add("carrierServiceId", Configuration.ApiClient.ParameterToString(carrierServiceId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetCarrierServiceById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<CarrierService>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (CarrierService) Configuration.ApiClient.Deserialize(localVarResponse, typeof(CarrierService))); } /// <summary> /// Get a carrierService by id Returns the carrierService identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierServiceId">Id of carrierService to be returned.</param> /// <returns>Task of CarrierService</returns> public async System.Threading.Tasks.Task<CarrierService> GetCarrierServiceByIdAsync (string carrierServiceId) { ApiResponse<CarrierService> localVarResponse = await GetCarrierServiceByIdAsyncWithHttpInfo(carrierServiceId); return localVarResponse.Data; } /// <summary> /// Get a carrierService by id Returns the carrierService identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="carrierServiceId">Id of carrierService to be returned.</param> /// <returns>Task of ApiResponse (CarrierService)</returns> public async System.Threading.Tasks.Task<ApiResponse<CarrierService>> GetCarrierServiceByIdAsyncWithHttpInfo (string carrierServiceId) { // verify the required parameter 'carrierServiceId' is set if (carrierServiceId == null) throw new ApiException(400, "Missing required parameter 'carrierServiceId' when calling CarrierServiceApi->GetCarrierServiceById"); var localVarPath = "/v1.0/carrierService/{carrierServiceId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (carrierServiceId != null) localVarPathParams.Add("carrierServiceId", Configuration.ApiClient.ParameterToString(carrierServiceId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetCarrierServiceById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<CarrierService>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (CarrierService) Configuration.ApiClient.Deserialize(localVarResponse, typeof(CarrierService))); } /// <summary> /// Search carrierServices Returns the list of carrierServices that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>List&lt;CarrierService&gt;</returns> public List<CarrierService> GetCarrierServiceBySearchText (string searchText = null, int? page = null, int? limit = null) { ApiResponse<List<CarrierService>> localVarResponse = GetCarrierServiceBySearchTextWithHttpInfo(searchText, page, limit); return localVarResponse.Data; } /// <summary> /// Search carrierServices Returns the list of carrierServices that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>ApiResponse of List&lt;CarrierService&gt;</returns> public ApiResponse< List<CarrierService> > GetCarrierServiceBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null) { var localVarPath = "/v1.0/carrierService/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetCarrierServiceBySearchText", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<CarrierService>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<CarrierService>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<CarrierService>))); } /// <summary> /// Search carrierServices Returns the list of carrierServices that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of List&lt;CarrierService&gt;</returns> public async System.Threading.Tasks.Task<List<CarrierService>> GetCarrierServiceBySearchTextAsync (string searchText = null, int? page = null, int? limit = null) { ApiResponse<List<CarrierService>> localVarResponse = await GetCarrierServiceBySearchTextAsyncWithHttpInfo(searchText, page, limit); return localVarResponse.Data; } /// <summary> /// Search carrierServices Returns the list of carrierServices that match the given searchText. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="searchText">Search text, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <returns>Task of ApiResponse (List&lt;CarrierService&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<CarrierService>>> GetCarrierServiceBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null) { var localVarPath = "/v1.0/carrierService/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetCarrierServiceBySearchText", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<CarrierService>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<CarrierService>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<CarrierService>))); } } }
using System; using System.Diagnostics; namespace Microsoft.Msagl.Core.Geometry { internal struct CompassVector { /// <summary> /// Override op== /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static bool operator ==(CompassVector a, CompassVector b) { return a.Dir == b.Dir; } /// <summary> /// Return the hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return (int)Dir; } /// <summary> /// Override op!= /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static bool operator !=(CompassVector a, CompassVector b) { return a.Dir != b.Dir; } internal CompassVector(Directions direction) : this() { Dir = direction; } // Warning: do not use for VisibilityGraph generation. See VectorDirection(a) comments. internal CompassVector(Point a) : this() { Dir = VectorDirection(a); } internal CompassVector(Point a, Point b) : this() { Dir = VectorDirection(a, b); } internal Directions Dir { get; set; } internal CompassVector Left { get { return new CompassVector(RotateLeft(Dir)); } } internal CompassVector Right { get { return new CompassVector(RotateRight(Dir)); } } internal CompassVector Opposite { get { return new CompassVector(OppositeDir(Dir)); } } internal static Directions RotateRight(Directions direction) { switch (direction) { case Directions.North: return Directions.East; case Directions.East: return Directions.South; case Directions.South: return Directions.West; case Directions.West: return Directions.North; default: throw new InvalidOperationException(); } } internal static Directions RotateLeft(Directions direction) { switch (direction) { case Directions.North: return Directions.West; case Directions.West: return Directions.South; case Directions.South: return Directions.East; case Directions.East: return Directions.North; default: throw new InvalidOperationException(); } } internal static int ToIndex(Directions direction) { switch (direction) { case Directions.North: return 0; case Directions.East: return 1; case Directions.South: return 2; case Directions.West: return 3; default: throw new InvalidOperationException(); } } internal static Directions VectorDirection(Point d){ Directions r = Directions.None; if(d.X > ApproximateComparer.DistanceEpsilon) r = Directions.East; else if(d.X < -ApproximateComparer.DistanceEpsilon) r = Directions.West; if(d.Y > ApproximateComparer.DistanceEpsilon) r |= Directions.North; else if(d.Y < -ApproximateComparer.DistanceEpsilon) r |= Directions.South; return r; } internal static Directions VectorDirection(Point a, Point b) { Directions r = Directions.None; // This method is called a lot as part of rectilinear layout. // Try to keep it quick. double horizontalDiff = b.X - a.X; double verticalDiff = b.Y - a.Y; double halfEpsilon = ApproximateComparer.DistanceEpsilon / 2; if (horizontalDiff > halfEpsilon) r = Directions.East; else if (-horizontalDiff > halfEpsilon) r = Directions.West; if (verticalDiff > halfEpsilon) r |= Directions.North; else if (-verticalDiff > halfEpsilon) r |= Directions.South; return r; } internal static Directions DirectionsFromPointToPoint(Point a, Point b) { return VectorDirection(a, b); } internal static Directions PureDirectionFromPointToPoint(Point a, Point b) { Directions dir = VectorDirection(a, b); Debug.Assert(IsPureDirection(dir), "Impure direction found"); return dir; } internal static Directions OppositeDir(Directions direction) { switch (direction) { case Directions.North: return Directions.South; case Directions.West: return Directions.East; case Directions.South: return Directions.North; case Directions.East: return Directions.West; default: return Directions.None; } } internal static bool IsPureDirection(Directions direction) { switch (direction) { case Directions.North: return true; case Directions.East: return true; case Directions.South: return true; case Directions.West: return true; default: return false; } } internal static bool IsPureDirection(Point a, Point b) { return IsPureDirection(DirectionsFromPointToPoint(a, b)); } /// <summary> /// /// </summary> /// <param name="other"></param> /// <returns></returns> public bool Equals(CompassVector other) { return Equals(other.Dir, Dir); } internal static bool DirectionsAreParallel(Directions a, Directions b){ return a == b || a == OppositeDir(b); } /// <summary> /// /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (obj.GetType() != typeof(CompassVector)) return false; return Equals((CompassVector)obj); } /// <summary> /// Returns a string representing the direction. /// </summary> /// <returns></returns> public override string ToString() { return Dir.ToString(); } /// <summary> /// Translates the CompassVector's direction into a new Point. /// </summary> /// <returns></returns> public Point ToPoint() { var p = new Point(); if ((Dir & Directions.East) == Directions.East) p.X += 1; if ((Dir & Directions.North) == Directions.North) p.Y += 1; if ((Dir & Directions.West) == Directions.West) p.X -= 1; if ((Dir & Directions.South) == Directions.South) p.Y -= 1; return p; } /// <summary> /// Translates a direction into a Point. /// </summary> /// <returns></returns> public static Point ToPoint(Directions dir) { return (new CompassVector(dir)).ToPoint(); } /// <summary> /// the negation operator /// </summary> /// <param name="directionVector"></param> /// <returns></returns> public static CompassVector operator -(CompassVector directionVector) { return new CompassVector(OppositeDir(directionVector.Dir)); } /// <summary> /// the negation operator /// </summary> /// <returns></returns> public CompassVector Negate() { return -this; } } }
/* 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 java.lang; using org.junit; namespace cnatural.compiler.test { public class LibraryTest : ExecutionTest { protected override String ResourcesPath { get { return "LibraryTest"; } } [Test] public void count() { doTest("Count", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void count2() { doTest("Count2", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void any() { doTest("Any", new Class<?>[] {}, new Object[] {}, true); } [Test] public void range() { doTest("Range", new Class<?>[] {}, new Object[] {}, 3628800); } [Test] public void asIterable() { doTest("AsIterable", new Class<?>[] {}, new Object[] {}, 3628800); } [Test] public void asIterable2() { doTest("AsIterable2", new Class<?>[] {}, new Object[] {}, "abc"); } [Test] public void empty() { doTest("Empty", new Class<?>[] {}, new Object[] {}, true); } [Test] public void countInt() { doTest("CountInt", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void select() { doTest("Select", new Class<?>[] {}, new Object[] {}, "ABC"); } [Test] public void selectInt() { doTest("SelectInt", new Class<?>[] {}, new Object[] {}, 6); } [Test] public void selectInt2() { doTest("SelectInt2", new Class<?>[] {}, new Object[] {}, "abc"); } [Test] public void selectInt3() { doTest("SelectInt3", new Class<?>[] {}, new Object[] {}, "246"); } [Test] public void where() { doTest("Where", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void where2() { doTest("Where2", new Class<?>[] {}, new Object[] {}, 5); } [Test] public void distinct() { doTest("Distinct", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void sequenceEqual() { doTest("SequenceEqual", new Class<?>[] {}, new Object[] {}, true); } [Test] public void sequenceEqual2() { doTest("SequenceEqual2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void orderBy() { doTest("OrderBy", new Class<?>[] {}, new Object[] {}, "abbccc"); } [Test] public void thenBy() { doTest("ThenBy", new Class<?>[] {}, new Object[] {}, "abcaabbccaaabbbccc"); } [Test] public void thenBy2() { doTest("ThenBy2", new Class<?>[] {}, new Object[] {}, "abcaabbccaaabbbccc"); } [Test] public void selectMany() { doTest("SelectMany", new Class<?>[] {}, new Object[] {}, "a1b1c1a2b2c2"); } [Test] public void whereSequenceEqual() { doTest("WhereSequenceEqual", new Class<?>[] {}, new Object[] {}, "obj2"); } [Test] public void cast() { doTest("Cast", new Class<?>[] {}, new Object[] {}, "abcdef"); } [Test] public void castToInt() { doTest("CastToInt", new Class<?>[] {}, new Object[] {}, 10); } [Test] public void castToInt2() { doTest("CastToInt2", new Class<?>[] {}, new Object[] {}, 10); } [Test] public void groupBy() { doTest("GroupBy", new Class<?>[] {}, new Object[] {}, "(a)bc(d)efg"); } [Test] public void ofType() { doTest("OfType", new Class<?>[] {}, new Object[] {}, "abcdef"); } [Test] public void groupBy2() { doTest("GroupBy2", new Class<?>[] {}, new Object[] {}, "(a)BC(d)EFG"); } [Test] public void join() { doTest("Join", new Class<?>[] {}, new Object[] {}, "|A1: B1|A2: B2|A2: B3|A3: B4"); } [Test] public void groupJoin() { doTest("GroupJoin", new Class<?>[] {}, new Object[] {}, "|A1: B1 |A2: B2 B3 |A3: B4 "); } [Test] public void selectLINQ() { doTest("SelectLINQ", new Class<?>[] {}, new Object[] {}, "ABC"); } [Test] public void castLINQ() { doTest("CastLINQ", new Class<?>[] {}, new Object[] {}, "abcdef"); } [Test] public void groupByLINQ() { doTest("GroupByLINQ", new Class<?>[] {}, new Object[] {}, "(a)bc(d)efg"); } [Test] public void groupBy2LINQ() { doTest("GroupBy2LINQ", new Class<?>[] {}, new Object[] {}, "(a)BC(d)EFG"); } [Test] public void groupJoinLINQ() { doTest("GroupJoinLINQ", new Class<?>[] {}, new Object[] {}, "|A1: B1 |A2: B2 B3 |A3: B4 "); } [Test] public void orderByLINQ() { doTest("OrderByLINQ", new Class<?>[] {}, new Object[] {}, "abbccc"); } [Test] public void thenByLINQ() { doTest("ThenByLINQ", new Class<?>[] {}, new Object[] {}, "abcaabbccaaabbbccc"); } [Test] public void thenBy2LINQ() { doTest("ThenBy2LINQ", new Class<?>[] {}, new Object[] {}, "abcaabbccaaabbbccc"); } [Test] public void whereLINQ() { doTest("WhereLINQ", new Class<?>[] {}, new Object[] {}, 2); } [Test] public void where2LINQ() { doTest("Where2LINQ", new Class<?>[] {}, new Object[] {}, 5); } [Test] public void conditionalTest() { doTest(new String[]{ "ConditionalTest", "ConditionalAux" }, new Class<?>[] {}, new Object[] {}, true); } [Test] public void conditionalTest2() { doTest(new String[]{ "ConditionalTest2", "ConditionalAux" }, new Class<?>[] {}, new Object[] {}, true); } [Test] public void allAny() { doTest("AllAny", new Class<?>[] {}, new Object[] {}, true); } [Test] public void allContains() { doTest("AllContains", new Class<?>[] {}, new Object[] {}, true); } [Test] public void linqWhere() { doTest("LinqWhere", new Class<?>[] {}, new Object[] {}, true); } [Test] public void linqExecution() { doTest("LinqExecution", new Class<?>[] {}, new Object[] {}, true); } [Test] public void expressionTreeParameter() { doTest("ExpressionTreeParameter", new Class<?>[] {}, new Object[] {}, "p"); } [Test] public void expressionTreeConstant() { doTest("ExpressionTreeConstant", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void expressionTreeVariable() { doTest("ExpressionTreeVariable", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void expressionTreeMethodCall() { doTest("ExpressionTreeMethodCall", new Class<?>[] {}, new Object[] {}, "method"); } [Test] public void expressionTreeInvoke() { doTest("ExpressionTreeInvoke", new Class<?>[] {}, new Object[] {}, "ExpressionTreeInvoke$D"); } [Test] public void expressionTreeField() { doTest("ExpressionTreeField", new Class<?>[] {}, new Object[] {}, "field"); } [Test] public void expressionTreeProperty() { doTest("ExpressionTreeProperty", new Class<?>[] {}, new Object[] {}, "getProperty"); } [Test] public void expressionTreeIncrement() { doTest("ExpressionTreeIncrement", new Class<?>[] {}, new Object[] {}, "PreIncrement"); } [Test] public void expressionTreeAdd() { doTest("ExpressionTreeAdd", new Class<?>[] {}, new Object[] {}, "Add"); } [Test] public void expressionTreeField2() { doTest("ExpressionTreeField2", new Class<?>[] {}, new Object[] {}, "field"); } [Test] public void expressionTreeTypeof() { doTest("ExpressionTreeTypeof", new Class<?>[] {}, new Object[] {}, "ExpressionTreeTypeof"); } [Test] public void expressionTreeIndexer() { doTest("ExpressionTreeIndexer", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void expressionTreeAddAssign() { doTest("ExpressionTreeAddAssign", new Class<?>[] {}, new Object[] {}, "AddAssign"); } [Test] public void expressionTreeCast() { doTest("ExpressionTreeCast", new Class<?>[] {}, new Object[] {}, "Cast"); } [Test] public void expressionTreeObjectCreation() { doTest("ExpressionTreeObjectCreation", new Class<?>[] {}, new Object[] {}, "java.lang.Object"); } [Test] public void expressionTreeObjectCreation2() { doTest("ExpressionTreeObjectCreation2", new Class<?>[] {}, new Object[] {}, "field"); } [Test] public void expressionTreeObjectCreation3() { doTest("ExpressionTreeObjectCreation3", new Class<?>[] {}, new Object[] {}, "setProperty"); } [Test] public void expressionTreeObjectCreation4() { doTest("ExpressionTreeObjectCreation4", new Class<?>[] {}, new Object[] {}, "add"); } [Test] public void expressionTreeAnonymousObjectCreation() { doTest("ExpressionTreeAnonymousObjectCreation", new Class<?>[] {}, new Object[] {}, "p"); } [Test] public void expressionTreeArrayCreation() { doTest("ExpressionTreeArrayCreation", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void expressionTreeArrayCreation2() { doTest("ExpressionTreeArrayCreation2", new Class<?>[] {}, new Object[] {}, 3); } [Test] public void expressionTreeReturn() { doTest("ExpressionTreeReturn", new Class<?>[] {}, new Object[] {}, 1); } [Test] public void intList1() { doTest("IntList1", new Class<?>[] {}, new Object[] {}, true); } [Test] public void intIterable1() { doTest("IntIterable1", new Class<?>[] {}, new Object[] {}, true); } [Test] public void intIterable2() { doTest("IntIterable2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void intList2() { doTest("IntList2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void intList3() { doTest("IntList3", new Class<?>[] {}, new Object[] {}, true); } [Test] public void intList4() { doTest("IntList4", new Class<?>[] {}, new Object[] {}, true); } [Test] public void intList5() { doTest("IntList5", new Class<?>[] {}, new Object[] {}, true); } [Test] public void doubleList1() { doTest("DoubleList1", new Class<?>[] {}, new Object[] {}, true); } [Test] public void aggregate() { doTest("Aggregate", new Class<?>[] {}, new Object[] {}, "S12345"); } [Test] public void average() { doTest("Average", new Class<?>[] {}, new Object[] {}, 2d); } [Test] public void average2() { doTest("Average2", new Class<?>[] {}, new Object[] {}, 2d); } [Test] public void reverse() { doTest("Reverse", new Class<?>[] {}, new Object[] {}, "FEDCBA"); } [Test] public void skip() { doTest("Skip", new Class<?>[] {}, new Object[] {}, "DEF"); } [Test] public void sum() { doTest("Sum", new Class<?>[] {}, new Object[] {}, 10); } [Test] public void sum2() { doTest("Sum2", new Class<?>[] {}, new Object[] {}, 10); } [Test] public void max() { doTest("Max", new Class<?>[] {}, new Object[] {}, 4d); } [Test] public void intSet1() { doTest("IntSet1", new Class<?>[] {}, new Object[] {}, true); } [Test] public void intSet2() { doTest("IntSet2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void intSet3() { doTest("IntSet3", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toMap() { doTest("ToMap", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toMap2() { doTest("ToMap2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toMap3() { doTest("ToMap3", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toMap4() { doTest("ToMap4", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toMap5() { doTest("ToMap5", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toMap6() { doTest("ToMap6", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toLongTMap() { doTest("ToLongTMap", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toLongTMap2() { doTest("ToLongTMap2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toLongTMap3() { doTest("ToLongTMap3", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toLongTMap4() { doTest("ToLongTMap4", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toLongTMap5() { doTest("ToLongTMap5", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTLongMap() { doTest("ToTLongMap", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTLongMap2() { doTest("ToTLongMap2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTLongMap3() { doTest("ToTLongMap3", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toTLongMap4() { doTest("ToTLongMap4", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toTLongMap5() { doTest("ToTLongMap5", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTIntMap() { doTest("ToTIntMap", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTIntMap2() { doTest("ToTIntMap2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTIntMap3() { doTest("ToTIntMap3", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toTIntMap4() { doTest("ToTIntMap4", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toTIntMap5() { doTest("ToTIntMap5", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTFloatMap() { doTest("ToTFloatMap", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTFloatMap2() { doTest("ToTFloatMap2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTFloatMap3() { doTest("ToTFloatMap3", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toTFloatMap4() { doTest("ToTFloatMap4", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toTFloatMap5() { doTest("ToTFloatMap5", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTDoubleMap() { doTest("ToTDoubleMap", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTDoubleMap2() { doTest("ToTDoubleMap2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toTDoubleMap3() { doTest("ToTDoubleMap3", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toTDoubleMap4() { doTest("ToTDoubleMap4", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toTDoubleMap5() { doTest("ToTDoubleMap5", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toIntTMap() { doTest("ToIntTMap", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toIntTMap2() { doTest("ToIntTMap2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toIntTMap3() { doTest("ToIntTMap3", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toIntTMap4() { doTest("ToIntTMap4", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toIntTMap5() { doTest("ToIntTMap5", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toFloatTMap() { doTest("ToFloatTMap", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toFloatTMap2() { doTest("ToFloatTMap2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toFloatTMap3() { doTest("ToFloatTMap3", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toFloatTMap4() { doTest("ToFloatTMap4", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toFloatTMap5() { doTest("ToFloatTMap5", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toDoubleTMap() { doTest("ToDoubleTMap", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toDoubleTMap2() { doTest("ToDoubleTMap2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void toDoubleTMap3() { doTest("ToDoubleTMap3", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toDoubleTMap4() { doTest("ToDoubleTMap4", new Class<?>[] {}, new Object[] {}, 0); } [Test] public void toDoubleTMap5() { doTest("ToDoubleTMap5", new Class<?>[] {}, new Object[] {}, true); } [Test] public void union() { doTest("Union", new Class<?>[] {}, new Object[] {}, true); } [Test] public void union2() { doTest("Union2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void intersect() { doTest("Intersect", new Class<?>[] {}, new Object[] {}, true); } [Test] public void intersect2() { doTest("Intersect2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void skipWhile() { doTest("SkipWhile", new Class<?>[] {}, new Object[] {}, true); } [Test] public void skipWhile2() { doTest("SkipWhile2", new Class<?>[] {}, new Object[] {}, true); } [Test] public void indexedSelect() { doTest("IndexedSelect", new Class<?>[] {}, new Object[] {}, "A0B1C2"); } } }
// 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.Linq; using osuTK.Graphics; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.Sprites; using osuTK; namespace osu.Game.Graphics.UserInterface { public class OsuDropdown<T> : Dropdown<T>, IHasAccentColour { private Color4 accentColour; public Color4 AccentColour { get => accentColour; set { accentColour = value; updateAccentColour(); } } [BackgroundDependencyLoader] private void load(OsuColour colours) { if (accentColour == default) accentColour = colours.PinkDarker; updateAccentColour(); } private void updateAccentColour() { if (Header is IHasAccentColour header) header.AccentColour = accentColour; if (Menu is IHasAccentColour menu) menu.AccentColour = accentColour; } protected override DropdownHeader CreateHeader() => new OsuDropdownHeader(); protected override DropdownMenu CreateMenu() => new OsuDropdownMenu(); #region OsuDropdownMenu protected class OsuDropdownMenu : DropdownMenu, IHasAccentColour { public override bool HandleNonPositionalInput => State == MenuState.Open; // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring public OsuDropdownMenu() { CornerRadius = 4; BackgroundColour = Color4.Black.Opacity(0.5f); // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring ItemsContainer.Padding = new MarginPadding(5); } // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring protected override void AnimateOpen() => this.FadeIn(300, Easing.OutQuint); protected override void AnimateClose() => this.FadeOut(300, Easing.OutQuint); // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring protected override void UpdateSize(Vector2 newSize) { if (Direction == Direction.Vertical) { Width = newSize.X; this.ResizeHeightTo(newSize.Y, 300, Easing.OutQuint); } else { Height = newSize.Y; this.ResizeWidthTo(newSize.X, 300, Easing.OutQuint); } } private Color4 accentColour; public Color4 AccentColour { get => accentColour; set { accentColour = value; foreach (var c in Children.OfType<IHasAccentColour>()) c.AccentColour = value; } } protected override DrawableMenuItem CreateDrawableMenuItem(MenuItem item) => new DrawableOsuDropdownMenuItem(item) { AccentColour = accentColour }; #region DrawableOsuDropdownMenuItem public class DrawableOsuDropdownMenuItem : DrawableDropdownMenuItem, IHasAccentColour { // IsHovered is used public override bool HandlePositionalInput => true; private Color4? accentColour; public Color4 AccentColour { get => accentColour ?? nonAccentSelectedColour; set { accentColour = value; updateColours(); } } private void updateColours() { BackgroundColourHover = accentColour ?? nonAccentHoverColour; BackgroundColourSelected = accentColour ?? nonAccentSelectedColour; UpdateBackgroundColour(); UpdateForegroundColour(); } private Color4 nonAccentHoverColour; private Color4 nonAccentSelectedColour; public DrawableOsuDropdownMenuItem(MenuItem item) : base(item) { Foreground.Padding = new MarginPadding(2); Masking = true; CornerRadius = 6; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = Color4.Transparent; nonAccentHoverColour = colours.PinkDarker; nonAccentSelectedColour = Color4.Black.Opacity(0.5f); updateColours(); AddInternal(new HoverClickSounds(HoverSampleSet.Soft)); } protected override void UpdateForegroundColour() { base.UpdateForegroundColour(); if (Foreground.Children.FirstOrDefault() is Content content) content.Chevron.Alpha = IsHovered ? 1 : 0; } protected override Drawable CreateContent() => new Content(); protected new class Content : FillFlowContainer, IHasText { public string Text { get => Label.Text; set => Label.Text = value; } public readonly OsuSpriteText Label; public readonly SpriteIcon Chevron; public Content() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Direction = FillDirection.Horizontal; Children = new Drawable[] { Chevron = new SpriteIcon { AlwaysPresent = true, Icon = FontAwesome.ChevronRight, Colour = Color4.Black, Alpha = 0.5f, Size = new Vector2(8), Margin = new MarginPadding { Left = 3, Right = 3 }, Origin = Anchor.CentreLeft, Anchor = Anchor.CentreLeft, }, Label = new OsuSpriteText { Origin = Anchor.CentreLeft, Anchor = Anchor.CentreLeft, }, }; } } } #endregion } #endregion public class OsuDropdownHeader : DropdownHeader, IHasAccentColour { protected readonly SpriteText Text; protected override string Label { get => Text.Text; set => Text.Text = value; } protected readonly SpriteIcon Icon; private Color4 accentColour; public virtual Color4 AccentColour { get => accentColour; set { accentColour = value; BackgroundColourHover = accentColour; } } public OsuDropdownHeader() { Foreground.Padding = new MarginPadding(4); AutoSizeAxes = Axes.None; Margin = new MarginPadding { Bottom = 4 }; CornerRadius = 4; Height = 40; Foreground.Children = new Drawable[] { Text = new OsuSpriteText { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, }, Icon = new SpriteIcon { Icon = FontAwesome.ChevronDown, Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Margin = new MarginPadding { Right = 4 }, Size = new Vector2(20), }, }; AddInternal(new HoverClickSounds()); } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = Color4.Black.Opacity(0.5f); BackgroundColourHover = colours.PinkDarker; } } } }
// 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.ComponentModel.Composition.Primitives; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.Internal; namespace System.ComponentModel.Composition.Hosting { /// <summary> /// A mutable collection of <see cref="ComposablePartCatalog"/>s. /// </summary> /// <remarks> /// This type is thread safe. /// </remarks> public class AggregateCatalog : ComposablePartCatalog, INotifyComposablePartCatalogChanged { private ComposablePartCatalogCollection _catalogs = null; private volatile int _isDisposed = 0; /// <summary> /// Initializes a new instance of the <see cref="AggregateCatalog"/> class. /// </summary> public AggregateCatalog() : this((IEnumerable<ComposablePartCatalog>)null) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateCatalog"/> class /// with the specified catalogs. /// </summary> /// <param name="catalogs"> /// An <see cref="Array"/> of <see cref="ComposablePartCatalog"/> objects to add to the /// <see cref="AggregateCatalog"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="catalogs"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="catalogs"/> contains an element that is <see langword="null"/>. /// </exception> public AggregateCatalog(params ComposablePartCatalog[] catalogs) : this((IEnumerable<ComposablePartCatalog>)catalogs) { } /// <summary> /// Initializes a new instance of the <see cref="AggregateCatalog"/> class /// with the specified catalogs. /// </summary> /// <param name="catalogs"> /// An <see cref="IEnumerable{T}"/> of <see cref="ComposablePartCatalog"/> objects to add /// to the <see cref="AggregateCatalog"/>; or <see langword="null"/> to /// create an <see cref="AggregateCatalog"/> that is empty. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="catalogs"/> contains an element that is <see langword="null"/>. /// </exception> public AggregateCatalog(IEnumerable<ComposablePartCatalog> catalogs) { Requires.NullOrNotNullElements(catalogs, nameof(catalogs)); _catalogs = new ComposablePartCatalogCollection(catalogs, OnChanged, OnChanging); } /// <summary> /// Notify when the contents of the Catalog has changed. /// </summary> public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed { add { _catalogs.Changed += value; } remove { _catalogs.Changed -= value; } } /// <summary> /// Notify when the contents of the Catalog has changing. /// </summary> public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing { add { _catalogs.Changing += value; } remove { _catalogs.Changing -= value; } } /// <summary> /// Returns the export definitions that match the constraint defined by the specified definition. /// </summary> /// <param name="definition"> /// The <see cref="ImportDefinition"/> that defines the conditions of the /// <see cref="ExportDefinition"/> objects to return. /// </param> /// <returns> /// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the /// <see cref="ExportDefinition"/> objects and their associated /// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined /// by <paramref name="definition"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="definition"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="AggregateCatalog"/> has been disposed of. /// </exception> public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition) { ThrowIfDisposed(); Requires.NotNull(definition, nameof(definition)); // We optimize for the case where the result is comparible with the requested cardinality, though we do remain correct in all cases. // We do so to avoid any unnecessary allocations IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> result = null; List<Tuple<ComposablePartDefinition, ExportDefinition>> aggregateResult = null; foreach (var catalog in _catalogs) { var catalogExports = catalog.GetExports(definition); if (catalogExports != ComposablePartCatalog._EmptyExportsList) { // ideally this is the case we will always hit if (result == null) { result = catalogExports; } else { // sadly the result has already been assigned, which means we are in the aggregate case if (aggregateResult == null) { aggregateResult = new List<Tuple<ComposablePartDefinition, ExportDefinition>>(result); result = aggregateResult; } aggregateResult.AddRange(catalogExports); } } } return result ?? ComposablePartCatalog._EmptyExportsList; } /// <summary> /// Gets the underlying catalogs of the catalog. /// </summary> /// <value> /// An <see cref="ICollection{T}"/> of underlying <see cref="ComposablePartCatalog"/> objects /// of the <see cref="AggregateCatalog"/>. /// </value> /// <exception cref="ObjectDisposedException"> /// The <see cref="AggregateCatalog"/> has been disposed of. /// </exception> public ICollection<ComposablePartCatalog> Catalogs { get { ThrowIfDisposed(); Debug.Assert(_catalogs != null); return _catalogs; } } protected override void Dispose(bool disposing) { try { if (disposing) { if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0) { _catalogs.Dispose(); } } } finally { base.Dispose(disposing); } } public override IEnumerator<ComposablePartDefinition> GetEnumerator() { return _catalogs.SelectMany(catalog => catalog).GetEnumerator(); } /// <summary> /// Raises the <see cref="INotifyComposablePartCatalogChanged.Changed"/> event. /// </summary> /// <param name="e"> /// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event. /// </param> protected virtual void OnChanged(ComposablePartCatalogChangeEventArgs e) { _catalogs.OnChanged(this, e); } /// <summary> /// Raises the <see cref="INotifyComposablePartCatalogChanged.Changing"/> event. /// </summary> /// <param name="e"> /// An <see cref="ComposablePartCatalogChangeEventArgs"/> containing the data for the event. /// </param> protected virtual void OnChanging(ComposablePartCatalogChangeEventArgs e) { _catalogs.OnChanging(this, e); } [DebuggerStepThrough] private void ThrowIfDisposed() { if (_isDisposed == 1) { throw ExceptionBuilder.CreateObjectDisposed(this); } } } }
using System; using NUnit.Framework; using Seterlund.CodeGuard.Validators; namespace Seterlund.CodeGuard.UnitTests.Validators { [TestFixture] public class StringValidatorTests : BaseTests { #region ----- Fixture setup ----- /// <summary> /// Called once before first test is executed /// </summary> [TestFixtureSetUp] public void Init() { // Init tests } /// <summary> /// Called once after last test is executed /// </summary> [TestFixtureTearDown] public void Cleanup() { // Cleanup tests } #endregion #region ------ Test setup ----- /// <summary> /// Called before each test /// </summary> [SetUp] public void Setup() { // Setup test } /// <summary> /// Called before each test /// </summary> [TearDown] public void TearDown() { // Cleanup after test } #endregion [Test] public void NotNull_WhenStringArgumentIsNull_Throws() { // Arrange string arg = null; // Act ArgumentNullException exception = GetException<ArgumentNullException>(() => Guard.That(() => arg).IsNotNull()); // Assert AssertArgumentNullException(exception, "arg", "Value cannot be null.\r\nParameter name: arg"); } [Test] public void NotNull_WhenArgumentIsNotNull_DoesNotThrow() { // Arrange string text = string.Empty; // Act/Assert Assert.DoesNotThrow(() => Guard.That(() => text).IsNotNull()); } [Test] public void NotEmpty_WhenArgumentIsEmpty_Throws() { // Arrange string arg = string.Empty; // Act ArgumentException exception = GetException<ArgumentException>(() => Guard.That(() => arg).IsNotEmpty()); // Assert AssertArgumentException(exception, "arg", "String is empty\r\nParameter name: arg"); } [Test] public void NotEmpty_WhenArgumentIsNotEmpty_DoesNotThrow() { // Arrange string text = "hello"; // Act/Assert Assert.DoesNotThrow(() => { Guard.That(() => text).IsNotEmpty(); }); } [Test] public void NotEmpty_WhenArgumentIsNull_DoesNotThrow() { // Arrange string text = "hello"; // Act/Assert Assert.DoesNotThrow(() => { Guard.That(() => text).IsNotEmpty(); }); } [Test] public void NotNullOrEmpty_WhenArgumentIsValid_DoesNotThrow() { // Arrange string text = "hello"; // Act/Assert Assert.DoesNotThrow(() => { Guard.That(() => text).IsNotNullOrEmpty(); }); } [Test] public void NotNullOrEmpty_WhenArgumentIsNull_Throws() { // Arrange string text = null; // Act/Assert Assert.Throws<ArgumentException>(() => Guard.That(() => text).IsNotNullOrEmpty()); } [Test] public void NotNullOrEmpty_WhenArgumentIsEmpty_Throws() { // Arrange string text = string.Empty; // Act/Assert Assert.Throws<ArgumentException>(() => Guard.That(() => text).IsNotNullOrEmpty()); } [Test] public void Contains_ArgumentContainsValue_DoesNotThrow() { // Arrange var text = "big brown car"; // Act/Assert Assert.DoesNotThrow(() => Guard.That(() => text).Contains("brown")); } [Test] public void Contains_ArgumentContainsValueWrongCase_Throws() { // Arrange var text = "BIG BROWN CAR"; // Act/Assert Assert.Throws<ArgumentException>(() => Guard.That(() => text).Contains("brown")); } [Test] public void Contains_ArgumentDoesNotContainValue_Throws() { // Arrange var text = "Yellow Submarine"; // Act/Assert Assert.Throws<ArgumentException>(() => Guard.That(() => text).Contains("brown")); } [Test] public void Length_ArgumentHasSameLength_DoesNotThrow() { // Arrange var text = "0123456789"; // Act/Assert Assert.DoesNotThrow(() => Guard.That(() => text).Length(10)); } [Test] public void Length_ArgumentHasDifferentLength_Throws() { // Arrange var text = "0123"; // Act/Assert Assert.Throws<ArgumentException>(() => Guard.That(() => text).Length(10)); } [Test] public void StartsWith_ArgumentStartsWithValue_DoesNotThrow() { // Arrange var text = "Start of string"; // Act/Assert Assert.DoesNotThrow(() => Guard.That(() => text).StartsWith("Start")); } [Test] public void StartsWith_ArgumentDoesNotStartWithValue_Throws() { // Arrange var text = "Some string"; // Act/Assert Assert.Throws<ArgumentException>(() => Guard.That(() => text).StartsWith("Start")); } [Test] public void EndsWith_ArgumentEndsWithValue_DoesNotThrow() { // Arrange var text = "The end is near"; // Act/Assert Assert.DoesNotThrow(() => Guard.That(() => text).EndsWith("near")); } [Test] public void EndsWith_ArgumentDoesNotEndWithValue_Throws() { // Arrange var text = "The end is near"; // Act/Assert Assert.Throws<ArgumentException>(() => Guard.That(() => text).EndsWith("Start")); } [TestCase("NOMATCH", @"\d")] [TestCase("perij@online", @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*")] public void IsMatch_ArgumentDoesNotMatch_Throws(string value, string pattern) { // Arrange var text = value; // Act/Assert Assert.Throws<ArgumentException>(() => Guard.That(() => text).IsMatch(pattern)); } [TestCase("1234", @"\d")] [TestCase("perij@online.no", @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*")] public void IsMatch_ArgumentNotMatches_Throws(string value, string pattern) { // Arrange var text = value; // Act/Assert Assert.DoesNotThrow(() => Guard.That(() => text).IsMatch(pattern)); } [Test] public void NotNullOrWhiteSpace_WhenStringArgumentIsNull_Throws() { // Arrange string arg = null; // Assert Assert.Throws<ArgumentException>(() => Guard.That(() => arg).IsNotNullOrWhiteSpace()); } [Test] public void NotNullOrWhiteSpace_WhenStringArgumentIsWhiteSpace_Throws() { // Arrange string arg = " "; // Assert Assert.Throws<ArgumentException>(() => Guard.That(() => arg).IsNotNullOrWhiteSpace()); } [Test] public void NotNullOrWhiteSpace_WhenStringArgumentIsNotNullOrWhitespace_DoesNotThrow() { // Arrange string arg = "Test"; // Assert Assert.DoesNotThrow(() => Guard.That(() => arg).IsNotNullOrWhiteSpace()); } } }
using System; using System.Drawing; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Windows.Forms; using DevExpress.CodeRush.PlugInCore; namespace CR_XkeysEngine { public class NewFolderName : DXCoreForm { #region private consts private const string STR_ParentLblFormat = "(folder will be created inside \"{0}\")"; private const string STR_NULLLENGTH_ERROR = "(Please type the name)"; private const string STR_EXISTINGNAME_ERROR = "(This folder name already exists.)"; #endregion #region private Fields ... private StringCollection _ExistingFolders; private CommandKeyFolder _ParentFolder; private CommandKeyFolder _RootFolder; #endregion #region private fields ... private System.ComponentModel.Container components = null; private System.Windows.Forms.Label label2; private DevExpress.DXCore.Controls.XtraEditors.SimpleButton btnApply; private DevExpress.DXCore.Controls.XtraEditors.SimpleButton btnCancel; private DevExpress.DXCore.Controls.XtraEditors.TextEdit edFolderName; private System.Windows.Forms.Label lblParent; private System.Windows.Forms.Label lblInfo; private System.Windows.Forms.CheckBox chkRoot; #endregion //--------------------------- #region NewFolderName public NewFolderName() { InitializeComponent(); } #endregion #region Dispose /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.edFolderName = new DevExpress.DXCore.Controls.XtraEditors.TextEdit(); this.label2 = new System.Windows.Forms.Label(); this.btnApply = new DevExpress.DXCore.Controls.XtraEditors.SimpleButton(); this.btnCancel = new DevExpress.DXCore.Controls.XtraEditors.SimpleButton(); this.lblInfo = new System.Windows.Forms.Label(); this.lblParent = new System.Windows.Forms.Label(); this.chkRoot = new System.Windows.Forms.CheckBox(); ((System.ComponentModel.ISupportInitialize)(this.Images16x16)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.edFolderName.Properties)).BeginInit(); this.SuspendLayout(); // // edFolderName // this.edFolderName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.edFolderName.EditValue = ""; this.edFolderName.Location = new System.Drawing.Point(84, 11); this.edFolderName.Name = "edFolderName"; this.edFolderName.Size = new System.Drawing.Size(196, 20); this.edFolderName.TabIndex = 0; this.edFolderName.TextChanged += new System.EventHandler(this.edFolderName_TextChanged); // // label2 // this.label2.Location = new System.Drawing.Point(4, 9); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(152, 24); this.label2.TabIndex = 4; this.label2.Text = "Folder name:"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // btnApply // this.btnApply.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnApply.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnApply.Enabled = false; this.btnApply.Location = new System.Drawing.Point(124, 88); this.btnApply.Name = "btnApply"; this.btnApply.Size = new System.Drawing.Size(75, 25); this.btnApply.TabIndex = 1; this.btnApply.Text = "&OK"; // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(204, 88); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 25); this.btnCancel.TabIndex = 2; this.btnCancel.Text = "&Cancel"; // // lblInfo // this.lblInfo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblInfo.ForeColor = System.Drawing.SystemColors.ControlDarkDark; this.lblInfo.Location = new System.Drawing.Point(4, 39); this.lblInfo.Name = "lblInfo"; this.lblInfo.Size = new System.Drawing.Size(276, 21); this.lblInfo.TabIndex = 3; this.lblInfo.Text = "(Please type a name without \"_\")"; this.lblInfo.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.lblInfo.Visible = false; // // lblParent // this.lblParent.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblParent.ForeColor = System.Drawing.SystemColors.ControlDarkDark; this.lblParent.Location = new System.Drawing.Point(4, 39); this.lblParent.Name = "lblParent"; this.lblParent.Size = new System.Drawing.Size(276, 21); this.lblParent.TabIndex = 5; this.lblParent.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // chkRoot // this.chkRoot.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.chkRoot.Location = new System.Drawing.Point(4, 65); this.chkRoot.Name = "chkRoot"; this.chkRoot.Size = new System.Drawing.Size(276, 25); this.chkRoot.TabIndex = 6; this.chkRoot.Text = "Make this a top-level folder"; this.chkRoot.CheckedChanged += new System.EventHandler(this.chkRoot_CheckedChanged); // // NewFolderName // this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); this.ClientSize = new System.Drawing.Size(286, 117); this.Controls.Add(this.lblInfo); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnApply); this.Controls.Add(this.edFolderName); this.Controls.Add(this.label2); this.Controls.Add(this.chkRoot); this.Controls.Add(this.lblParent); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "NewFolderName"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.NewFolderName_KeyDown); ((System.ComponentModel.ISupportInitialize)(this.Images16x16)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.edFolderName.Properties)).EndInit(); this.ResumeLayout(false); } #endregion // private methods ... #region UpdateRootCheckedValue private void UpdateRootCheckedValue() { if (chkRoot.Checked) GetExistingFolders(RootFolder); else GetExistingFolders(ParentFolder); btnApply.Enabled = GetNameAccuracy(); ShowParentFolderInfo(); } #endregion #region ShowParentFolderInfo private void ShowParentFolderInfo() { if (FolderName.Length == 0) lblParent.Text = STR_NULLLENGTH_ERROR; else if (_ExistingFolders != null && _ExistingFolders.Contains(FolderName)) lblParent.Text = STR_EXISTINGNAME_ERROR; else if (chkRoot.Visible && !chkRoot.Checked && _ParentFolder != null) lblParent.Text = String.Format(STR_ParentLblFormat, _ParentFolder.Name); else lblParent.Text = ""; } #endregion #region GetRootFolder private CommandKeyFolder GetRootFolder(CommandKeyFolder folder) { if (folder == null) return null; if (folder.ParentFolder == null) return folder; return GetRootFolder(folder.ParentFolder); } #endregion #region GetExistingFolders private void GetExistingFolders(CommandKeyFolder folder) { if (_ExistingFolders == null) _ExistingFolders = new StringCollection(); else _ExistingFolders.Clear(); if (folder == null || folder.Folders == null) return; for (int i = 0; i < folder.Folders.Count; i++) { CommandKeyFolder lFolder = folder.Folders[i] as CommandKeyFolder; if (lFolder == null) continue; if (!lFolder.IsDeleted) _ExistingFolders.Add(lFolder.Name); } } #endregion #region GetNameAccuracy private bool GetNameAccuracy() { if (FolderName.Length == 0) return false; if (_ExistingFolders == null) return true; return !_ExistingFolders.Contains(FolderName); } #endregion // public methods ... #region CreateNewFolder public static bool CreateNewFolder(ref string value, ref bool inRoot) { return CreateNewFolder("Create Folder", null, ref value, ref inRoot); } #endregion #region CreateNewFolder public static bool CreateNewFolder(string caption, ref string value, ref bool inRoot) { return CreateNewFolder(caption, null, ref value, ref inRoot); } #endregion #region CreateNewFolder public static bool CreateNewFolder(string caption, CommandKeyFolder parentFolder, ref string value, ref bool inRoot) { NewFolderName newFolderName = new NewFolderName(); newFolderName.Text = caption; newFolderName.RootFolder = newFolderName.GetRootFolder(parentFolder); newFolderName.ParentFolder = parentFolder; newFolderName.CreateInRoot = (newFolderName.ParentFolder == null || newFolderName.ParentFolder == newFolderName.RootFolder); bool needToUpdateRootFlag = (newFolderName.chkRoot.Enabled == (newFolderName.ParentFolder != newFolderName.RootFolder)); newFolderName.chkRoot.Enabled = (newFolderName.ParentFolder != newFolderName.RootFolder); if (needToUpdateRootFlag) newFolderName.UpdateRootCheckedValue(); newFolderName.FolderName = value; if (newFolderName.ShowDialog() == DialogResult.OK) { value = newFolderName.FolderName; inRoot = newFolderName.CreateInRoot; return true; } else return false; } #endregion #region RenameFolder(string caption, ref string value) public static bool RenameFolder(string caption, ref string value) { return RenameFolder(caption, null, ref value); } #endregion #region RenameFolder(string caption, CommandKeyFolder parentFolder, ref string value) public static bool RenameFolder(string caption, CommandKeyFolder parentFolder, ref string value) { NewFolderName newFolderName = new NewFolderName(); newFolderName.Text = caption; newFolderName.chkRoot.Visible = false; newFolderName.RootFolder = null; newFolderName.ParentFolder = parentFolder; newFolderName.GetExistingFolders(newFolderName.ParentFolder); newFolderName.FolderName = value; if (newFolderName.ShowDialog() == DialogResult.OK) { value = newFolderName.FolderName; return true; } else return false; } #endregion // event handlers ... #region edFolderName_TextChanged private void edFolderName_TextChanged(object sender, System.EventArgs e) { btnApply.Enabled = GetNameAccuracy(); ShowParentFolderInfo(); } #endregion #region NewFolderName_KeyDown private void NewFolderName_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { switch (e.KeyData) { case Keys.Enter: if (btnApply.Enabled) DialogResult = DialogResult.OK; break; case Keys.Escape: DialogResult = DialogResult.Cancel; break; } } #endregion #region chkRoot_CheckedChanged private void chkRoot_CheckedChanged(object sender, System.EventArgs e) { UpdateRootCheckedValue(); } #endregion // public properties ... #region FolderName /// <summary> /// Gets folder name. /// </summary> public string FolderName { get { return edFolderName.Text; } set { if (edFolderName.Text == value) return; edFolderName.Text = value; } } #endregion #region RootFolder public CommandKeyFolder RootFolder { get { return _RootFolder; } set { if (_RootFolder == value) return; _RootFolder = value; } } #endregion #region ParentFolder public CommandKeyFolder ParentFolder { get { return _ParentFolder; } set { if (_ParentFolder == value) return; _ParentFolder = value; } } #endregion #region CreateInRoot public bool CreateInRoot { get { return chkRoot.Checked; } set { chkRoot.Checked = value; } } #endregion } }
using System; using System.Collections; namespace NBarCodes { class Code128Encoder : ISymbolEncoder { // consider using this on code 39!! private class SymbolWrap { private readonly BitArray symbol; private readonly int value; public SymbolWrap(BitArray s, int v) { symbol = s; value = v; } public SymbolWrap(string s, int v) { symbol = BitArrayHelper.ToBitArray(s); value = v; } public BitArray Symbol { get { return symbol; } } public int Value { get { return value; } } } private static readonly Hashtable codeA; private static readonly Hashtable codeB; private static readonly Hashtable codeC; static Code128Encoder() { codeA = new Hashtable(105); codeB = new Hashtable(105); codeC = new Hashtable(105); codeA[" "]=codeB[" "]=codeC["00"]=new SymbolWrap("11011001100",0); codeA["!"]=codeB["!"]=codeC["01"]=new SymbolWrap("11001101100",1); codeA["\""]=codeB["\""]=codeC["02"]=new SymbolWrap("11001100110",2); codeA["#"]=codeB["#"]=codeC["03"]=new SymbolWrap("10010011000",3); codeA["$"]=codeB["$"]=codeC["04"]=new SymbolWrap("10010001100",4); codeA["%"]=codeB["%"]=codeC["05"]=new SymbolWrap("10001001100",5); codeA["&"]=codeB["&"]=codeC["06"]=new SymbolWrap("10011001000",6); codeA["'"]=codeB["'"]=codeC["07"]=new SymbolWrap("10011000100",7); codeA["("]=codeB["("]=codeC["08"]=new SymbolWrap("10001100100",8); codeA[")"]=codeB[")"]=codeC["09"]=new SymbolWrap("11001001000",9); codeA["*"]=codeB["*"]=codeC["10"]=new SymbolWrap("11001000100",10); codeA["+"]=codeB["+"]=codeC["11"]=new SymbolWrap("11000100100",11); codeA[","]=codeB[","]=codeC["12"]=new SymbolWrap("10110011100",12); codeA["-"]=codeB["-"]=codeC["13"]=new SymbolWrap("10011011100",13); codeA["."]=codeB["."]=codeC["14"]=new SymbolWrap("10011001110",14); codeA["/"]=codeB["/"]=codeC["15"]=new SymbolWrap("10111001100",15); codeA["0"]=codeB["0"]=codeC["16"]=new SymbolWrap("10011101100",16); codeA["1"]=codeB["1"]=codeC["17"]=new SymbolWrap("10011100110",17); codeA["2"]=codeB["2"]=codeC["18"]=new SymbolWrap("11001110010",18); codeA["3"]=codeB["3"]=codeC["19"]=new SymbolWrap("11001011100",19); codeA["4"]=codeB["4"]=codeC["20"]=new SymbolWrap("11001001110",20); codeA["5"]=codeB["5"]=codeC["21"]=new SymbolWrap("11011100100",21); codeA["6"]=codeB["6"]=codeC["22"]=new SymbolWrap("11001110100",22); codeA["7"]=codeB["7"]=codeC["23"]=new SymbolWrap("11101101110",23); codeA["8"]=codeB["8"]=codeC["24"]=new SymbolWrap("11101001100",24); codeA["9"]=codeB["9"]=codeC["25"]=new SymbolWrap("11100101100",25); codeA[":"]=codeB[":"]=codeC["26"]=new SymbolWrap("11100100110",26); codeA[";"]=codeB[";"]=codeC["27"]=new SymbolWrap("11101100100",27); codeA["<"]=codeB["<"]=codeC["28"]=new SymbolWrap("11100110100",28); codeA["="]=codeB["="]=codeC["29"]=new SymbolWrap("11100110010",29); codeA[">"]=codeB[">"]=codeC["30"]=new SymbolWrap("11011011000",30); codeA["?"]=codeB["?"]=codeC["31"]=new SymbolWrap("11011000110",31); codeA["@"]=codeB["@"]=codeC["32"]=new SymbolWrap("11000110110",32); codeA["A"]=codeB["A"]=codeC["33"]=new SymbolWrap("10100011000",33); codeA["B"]=codeB["B"]=codeC["34"]=new SymbolWrap("10001011000",34); codeA["C"]=codeB["C"]=codeC["35"]=new SymbolWrap("10001000110",35); codeA["D"]=codeB["D"]=codeC["36"]=new SymbolWrap("10110001000",36); codeA["E"]=codeB["E"]=codeC["37"]=new SymbolWrap("10001101000",37); codeA["F"]=codeB["F"]=codeC["38"]=new SymbolWrap("10001100010",38); codeA["G"]=codeB["G"]=codeC["39"]=new SymbolWrap("11010001000",39); codeA["H"]=codeB["H"]=codeC["40"]=new SymbolWrap("11000101000",40); codeA["I"]=codeB["I"]=codeC["41"]=new SymbolWrap("11000100010",41); codeA["J"]=codeB["J"]=codeC["42"]=new SymbolWrap("10110111000",42); codeA["K"]=codeB["K"]=codeC["43"]=new SymbolWrap("10110001110",43); codeA["L"]=codeB["L"]=codeC["44"]=new SymbolWrap("10001101110",44); codeA["M"]=codeB["M"]=codeC["45"]=new SymbolWrap("10111011000",45); codeA["N"]=codeB["N"]=codeC["46"]=new SymbolWrap("10111000110",46); codeA["O"]=codeB["O"]=codeC["47"]=new SymbolWrap("10001110110",47); codeA["P"]=codeB["P"]=codeC["48"]=new SymbolWrap("11101110110",48); codeA["Q"]=codeB["Q"]=codeC["49"]=new SymbolWrap("11010001110",49); codeA["R"]=codeB["R"]=codeC["50"]=new SymbolWrap("11000101110",50); codeA["S"]=codeB["S"]=codeC["51"]=new SymbolWrap("11011101000",51); codeA["T"]=codeB["T"]=codeC["52"]=new SymbolWrap("11011100010",52); codeA["U"]=codeB["U"]=codeC["53"]=new SymbolWrap("11011101110",53); codeA["V"]=codeB["V"]=codeC["54"]=new SymbolWrap("11101011000",54); codeA["W"]=codeB["W"]=codeC["55"]=new SymbolWrap("11101000110",55); codeA["X"]=codeB["X"]=codeC["56"]=new SymbolWrap("11100010110",56); codeA["Y"]=codeB["Y"]=codeC["57"]=new SymbolWrap("11101101000",57); codeA["Z"]=codeB["Z"]=codeC["58"]=new SymbolWrap("11101100010",58); codeA["["]=codeB["["]=codeC["59"]=new SymbolWrap("11100011010",59); codeA["\\"]=codeB["\\"]=codeC["60"]=new SymbolWrap("11101111010",60); codeA["]"]=codeB["]"]=codeC["61"]=new SymbolWrap("11001000010",61); codeA["^"]=codeB["^"]=codeC["62"]=new SymbolWrap("11110001010",62); codeA["_"]=codeB["_"]=codeC["63"]=new SymbolWrap("10100110000",63); codeA[((char)0).ToString()]=codeB["`"]=codeC["64"]=new SymbolWrap("10100001100",64); codeA[((char)1).ToString()]=codeB["a"]=codeC["65"]=new SymbolWrap("10010110000",65); codeA[((char)2).ToString()]=codeB["b"]=codeC["66"]=new SymbolWrap("10010000110",66); codeA[((char)3).ToString()]=codeB["c"]=codeC["67"]=new SymbolWrap("10000101100",67); codeA[((char)4).ToString()]=codeB["d"]=codeC["68"]=new SymbolWrap("10000100110",68); codeA[((char)5).ToString()]=codeB["e"]=codeC["69"]=new SymbolWrap("10110010000",69); codeA[((char)6).ToString()]=codeB["f"]=codeC["70"]=new SymbolWrap("10110000100",70); codeA[((char)7).ToString()]=codeB["g"]=codeC["71"]=new SymbolWrap("10011010000",71); codeA[((char)8).ToString()]=codeB["h"]=codeC["72"]=new SymbolWrap("10011000010",72); codeA[((char)9).ToString()]=codeB["i"]=codeC["73"]=new SymbolWrap("10000110100",73); codeA[((char)10).ToString()]=codeB["j"]=codeC["74"]=new SymbolWrap("10000110010",74); codeA[((char)11).ToString()]=codeB["k"]=codeC["75"]=new SymbolWrap("11000010010",75); codeA[((char)12).ToString()]=codeB["l"]=codeC["76"]=new SymbolWrap("11001010000",76); codeA[((char)13).ToString()]=codeB["m"]=codeC["77"]=new SymbolWrap("11110111010",77); codeA[((char)14).ToString()]=codeB["n"]=codeC["78"]=new SymbolWrap("11000010100",78); codeA[((char)15).ToString()]=codeB["o"]=codeC["79"]=new SymbolWrap("10001111010",79); codeA[((char)16).ToString()]=codeB["p"]=codeC["80"]=new SymbolWrap("10100111100",80); codeA[((char)17).ToString()]=codeB["q"]=codeC["81"]=new SymbolWrap("10010111100",81); codeA[((char)18).ToString()]=codeB["r"]=codeC["82"]=new SymbolWrap("10010011110",82); codeA[((char)19).ToString()]=codeB["s"]=codeC["83"]=new SymbolWrap("10111100100",83); codeA[((char)20).ToString()]=codeB["t"]=codeC["84"]=new SymbolWrap("10011110100",84); codeA[((char)21).ToString()]=codeB["u"]=codeC["85"]=new SymbolWrap("10011110010",85); codeA[((char)22).ToString()]=codeB["v"]=codeC["86"]=new SymbolWrap("11110100100",86); codeA[((char)23).ToString()]=codeB["w"]=codeC["87"]=new SymbolWrap("11110010100",87); codeA[((char)24).ToString()]=codeB["x"]=codeC["88"]=new SymbolWrap("11110010010",88); codeA[((char)25).ToString()]=codeB["y"]=codeC["89"]=new SymbolWrap("11011011110",89); codeA[((char)26).ToString()]=codeB["z"]=codeC["90"]=new SymbolWrap("11011110110",90); codeA[((char)27).ToString()]=codeB["{"]=codeC["91"]=new SymbolWrap("11110110110",91); codeA[((char)28).ToString()]=codeB["|"]=codeC["92"]=new SymbolWrap("10101111000",92); codeA[((char)29).ToString()]=codeB["}"]=codeC["93"]=new SymbolWrap("10100011110",93); codeA[((char)30).ToString()]=codeB["~"]=codeC["94"]=new SymbolWrap("10001011110",94); codeA[((char)31).ToString()]=codeB[((char)127).ToString()]=codeC["95"]=new SymbolWrap("10111101000",95); codeA[FNC3.ToString()]=codeB[FNC3.ToString()]=codeC["96"]=new SymbolWrap("10111100010",96); codeA[FNC2.ToString()]=codeB[FNC2.ToString()]=codeC["97"]=new SymbolWrap("11110101000",97); codeA[SHIFT.ToString()]=codeB[SHIFT.ToString()]=codeC["98"]=new SymbolWrap("11110100010",98); codeA[CodeC.ToString()]=codeB[CodeC.ToString()]=codeC["99"]=new SymbolWrap("10111011110",99); codeA[CodeB.ToString()]=codeB[FNC4.ToString()]=codeC[CodeB.ToString()]=new SymbolWrap("10111101110",100); codeA[FNC4.ToString()]=codeB[CodeA.ToString()]=codeC[CodeA.ToString()]=new SymbolWrap("11101011110",101); codeA[FNC1.ToString()]=codeB[FNC1.ToString()]=codeC[FNC1.ToString()]=new SymbolWrap("11110101110",102); codeA[StartA.ToString()]=codeB[StartA.ToString()]=codeC[StartA.ToString()]=new SymbolWrap("11010000100",103); codeA[StartB.ToString()]=codeB[StartB.ToString()]=codeC[StartB.ToString()]=new SymbolWrap("11010010000",104); codeA[StartC.ToString()]=codeB[StartC.ToString()]=codeC[StartC.ToString()]=new SymbolWrap("11010011100",105); } // Code 128 Special characters // The last seven characters of Code Sets A and B (character values 96 - 102) // and the last three characters of Code Set C (character values 100 - 102) // are special non-data characters with no ASCII character equivalents, // which have particular significance to the barcode reading device. // We use high-order ascii codes for these special chars not to clash // with other chars. public const char StartA = (char)200; public const char StartB = (char)201; public const char StartC = (char)202; public const char CodeA = (char)203; public const char CodeB = (char)204; public const char CodeC = (char)205; public const char FNC1 = (char)206; public const char FNC2 = (char)207; public const char FNC3 = (char)208; public const char FNC4 = (char)209; public const char SHIFT = (char)210; internal static bool CanCode(string data, char code) { switch (code) { case CodeA: return codeA.ContainsKey(data); case CodeB: return codeB.ContainsKey(data); case CodeC: return codeC.ContainsKey(data); } throw new ArgumentException("Invalid data."); } internal static int SymbolValue(string data, char code) { switch (code) { case CodeA: return ((SymbolWrap)codeA[data]).Value; case CodeB: return ((SymbolWrap)codeB[data]).Value; case CodeC: return ((SymbolWrap)codeC[data]).Value; } throw new ArgumentException("Invalid coding."); } internal static string SymbolString(int value, char code) { Hashtable hash = null; switch (code) { case CodeA: hash = codeA; break; case CodeB: hash = codeB; break; case CodeC: hash = codeC; break; default: throw new ArgumentException("Invalid coding."); } // not optimized! foreach (string key in hash.Keys) { if (((SymbolWrap)hash[key]).Value == value) return key; } throw new ArgumentException("Invalid value."); } internal static char ResolveStartCode(char code) { switch (code) { case StartA: return CodeA; case StartB: return CodeB; case StartC: return CodeC; default: throw new ArgumentException("Invalid starting code."); } } public BitArray Encode(string data) { BitArray bits = new BitArray(11 * data.Length); // maximum number of elements int count = 0; // actual count of elements // first char should be the code to use char currCode = ResolveStartCode(data[0]); for (int i = 0; i < data.Length; ++i) { char currChr = data[i]; string curr = currChr.ToString(); if (i > 0 && (curr == StartA.ToString() || curr == StartB.ToString() || curr == StartC.ToString())) throw new ArgumentException("The data has invalid coding."); BitArray currArr = null; switch (currCode) { case CodeA: currArr = ((SymbolWrap)codeA[curr]).Symbol; break; case CodeB: currArr = ((SymbolWrap)codeB[curr]).Symbol; break; case CodeC: if (char.IsNumber(currChr)) currArr = ((SymbolWrap)codeC[curr+data[++i].ToString()]).Symbol; else currArr = ((SymbolWrap)codeC[curr]).Symbol; break; } for (int j = 0; j < currArr.Count; ++j) { bits[count+j] = currArr[j]; } count += currArr.Count; if (curr == CodeA.ToString() || curr == CodeB.ToString() || curr == CodeC.ToString()) currCode = curr[0]; } bits.Length = count; return bits; } BitArray ISymbolEncoder.Encode(char datum) { // can't encode single datum throw new InvalidOperationException("Can't encode single char datum."); } } }
// 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\General\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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementInt320() { var test = new VectorGetAndWithElement__GetAndWithElementInt320(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementInt320 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Int32>>() / sizeof(Int32); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Int32[] values = new Int32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt32(); } Vector64<Int32> value = Vector64.Create(values[0], values[1]); bool succeeded = !expectedOutOfRangeException; try { Int32 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int32.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Int32 insertedValue = TestLibrary.Generator.GetInt32(); try { Vector64<Int32> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int32.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Int32[] values = new Int32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetInt32(); } Vector64<Int32> value = Vector64.Create(values[0], values[1]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector64) .GetMethod(nameof(Vector64.GetElement)) .MakeGenericMethod(typeof(Int32)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Int32)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int32.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Int32 insertedValue = TestLibrary.Generator.GetInt32(); try { object result2 = typeof(Vector64) .GetMethod(nameof(Vector64.WithElement)) .MakeGenericMethod(typeof(Int32)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector64<Int32>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int32.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Int32 result, Int32[] values, [CallerMemberName] string method = "") { if (result != values[0]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector64<Int32.GetElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector64<Int32> result, Int32[] values, Int32 insertedValue, [CallerMemberName] string method = "") { Int32[] resultElements = new Int32[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Int32[] result, Int32[] values, Int32 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 0) && (result[i] != values[i])) { succeeded = false; break; } } if (result[0] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Int32.WithElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = 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.Text; using System.Diagnostics; namespace System { internal static class UriHelper { private static readonly char[] s_hexUpperChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; // http://host/Path/Path/File?Query is the base of // - http://host/Path/Path/File/ ... (those "File" words may be different in semantic but anyway) // - http://host/Path/Path/#Fragment // - http://host/Path/Path/?Query // - http://host/Path/Path/MoreDir/ ... // - http://host/Path/Path/OtherFile?Query // - http://host/Path/Path/Fl // - http://host/Path/Path/ // // It is not a base for // - http://host/Path/Path (that last "Path" is not considered as a directory) // - http://host/Path/Path?Query // - http://host/Path/Path#Fragment // - http://host/Path/Path2/ // - http://host/Path/Path2/MoreDir // - http://host/Path/File // // ASSUMES that strings like http://host/Path/Path/MoreDir/../../ have been canonicalized before going to this method. // ASSUMES that back slashes already have been converted if applicable. // internal static unsafe bool TestForSubPath(char* selfPtr, ushort selfLength, char* otherPtr, ushort otherLength, bool ignoreCase) { ushort i = 0; char chSelf; char chOther; bool AllSameBeforeSlash = true; for (; i < selfLength && i < otherLength; ++i) { chSelf = *(selfPtr + i); chOther = *(otherPtr + i); if (chSelf == '?' || chSelf == '#') { // survived so far and selfPtr does not have any more path segments return true; } // If selfPtr terminates a path segment, so must otherPtr if (chSelf == '/') { if (chOther != '/') { // comparison has failed return false; } // plus the segments must be the same if (!AllSameBeforeSlash) { // comparison has failed return false; } //so far so good AllSameBeforeSlash = true; continue; } // if otherPtr terminates then selfPtr must not have any more path segments if (chOther == '?' || chOther == '#') { break; } if (!ignoreCase) { if (chSelf != chOther) { AllSameBeforeSlash = false; } } else { if (char.ToLowerInvariant(chSelf) != char.ToLowerInvariant(chOther)) { AllSameBeforeSlash = false; } } } // If self is longer then it must not have any more path segments for (; i < selfLength; ++i) { if ((chSelf = *(selfPtr + i)) == '?' || chSelf == '#') { return true; } if (chSelf == '/') { return false; } } //survived by getting to the end of selfPtr return true; } // - forceX characters are always escaped if found // - rsvd character will remain unescaped // // start - starting offset from input // end - the exclusive ending offset in input // destPos - starting offset in dest for output, on return this will be an exclusive "end" in the output. // // In case "dest" has lack of space it will be reallocated by preserving the _whole_ content up to current destPos // // Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos // private const short c_MaxAsciiCharsReallocate = 40; private const short c_MaxUnicodeCharsReallocate = 40; private const short c_MaxUTF_8BytesPerUnicodeChar = 4; private const short c_EncodedCharsPerByte = 3; internal static unsafe char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos, bool isUriString, char force1, char force2, char rsvd) { if (end - start >= Uri.c_MaxUriBufferSize) throw new UriFormatException(SR.net_uri_SizeLimit); int i = start; int prevInputPos = start; byte* bytes = stackalloc byte[c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar]; // 40*4=160 fixed (char* pStr = input) { for (; i < end; ++i) { char ch = pStr[i]; // a Unicode ? if (ch > '\x7F') { short maxSize = (short)Math.Min(end - i, (int)c_MaxUnicodeCharsReallocate - 1); short count = 1; for (; count < maxSize && pStr[i + count] > '\x7f'; ++count) ; // Is the last a high surrogate? if (pStr[i + count - 1] >= 0xD800 && pStr[i + count - 1] <= 0xDBFF) { // Should be a rare case where the app tries to feed an invalid Unicode surrogates pair if (count == 1 || count == end - i) throw new UriFormatException(SR.net_uri_BadString); // need to grab one more char as a Surrogate except when it's a bogus input ++count; } dest = EnsureDestinationSize(pStr, dest, i, (short)(count * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte), c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte, ref destPos, prevInputPos); short numberOfBytes = (short)Encoding.UTF8.GetBytes(pStr + i, count, bytes, c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar); // This is the only exception that built in UriParser can throw after a Uri ctor. // Should not happen unless the app tries to feed an invalid Unicode String if (numberOfBytes == 0) throw new UriFormatException(SR.net_uri_BadString); i += (count - 1); for (count = 0; count < numberOfBytes; ++count) EscapeAsciiChar((char)bytes[count], dest, ref destPos); prevInputPos = i + 1; } else if (ch == '%' && rsvd == '%') { // Means we don't reEncode '%' but check for the possible escaped sequence dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); if (i + 2 < end && EscapedAscii(pStr[i + 1], pStr[i + 2]) != Uri.c_DummyChar) { // leave it escaped dest[destPos++] = '%'; dest[destPos++] = pStr[i + 1]; dest[destPos++] = pStr[i + 2]; i += 2; } else { EscapeAsciiChar('%', dest, ref destPos); } prevInputPos = i + 1; } else if (ch == force1 || ch == force2) { dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); EscapeAsciiChar(ch, dest, ref destPos); prevInputPos = i + 1; } else if (ch != rsvd && (isUriString ? !IsReservedUnreservedOrHash(ch) : !IsUnreserved(ch))) { dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); EscapeAsciiChar(ch, dest, ref destPos); prevInputPos = i + 1; } } if (prevInputPos != i) { // need to fill up the dest array ? if (prevInputPos != start || dest != null) dest = EnsureDestinationSize(pStr, dest, i, 0, 0, ref destPos, prevInputPos); } } return dest; } // // ensure destination array has enough space and contains all the needed input stuff // private static unsafe char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos, short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos) { if ((object)dest == null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd) { // allocating or reallocating array by ensuring enough space based on maxCharsToAdd. char[] newresult = new char[destPos + (currentInputPos - prevInputPos) + minReallocateChars]; if ((object)dest != null && destPos != 0) Buffer.BlockCopy(dest, 0, newresult, 0, destPos << 1); dest = newresult; } // ensuring we copied everything form the input string left before last escaping while (prevInputPos != currentInputPos) dest[destPos++] = pStr[prevInputPos++]; return dest; } // // This method will assume that any good Escaped Sequence will be unescaped in the output // - Assumes Dest.Length - detPosition >= end-start // - UnescapeLevel controls various modes of operation // - Any "bad" escape sequence will remain as is or '%' will be escaped. // - destPosition tells the starting index in dest for placing the result. // On return destPosition tells the last character + 1 position in the "dest" array. // - The control chars and chars passed in rsdvX parameters may be re-escaped depending on UnescapeLevel // - It is a RARE case when Unescape actually needs escaping some characters mentioned above. // For this reason it returns a char[] that is usually the same ref as the input "dest" value. // internal static unsafe char[] UnescapeString(string input, int start, int end, char[] dest, ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser syntax, bool isQuery) { fixed (char* pStr = input) { return UnescapeString(pStr, start, end, dest, ref destPosition, rsvd1, rsvd2, rsvd3, unescapeMode, syntax, isQuery); } } internal static unsafe char[] UnescapeString(char* pStr, int start, int end, char[] dest, ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser syntax, bool isQuery) { byte[] bytes = null; byte escapedReallocations = 0; bool escapeReserved = false; int next = start; bool iriParsing = Uri.IriParsingStatic(syntax) && ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.EscapeUnescape); while (true) { // we may need to re-pin dest[] fixed (char* pDest = dest) { if ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.CopyOnly) { while (start < end) pDest[destPosition++] = pStr[start++]; return dest; } while (true) { char ch = (char)0; for (; next < end; ++next) { if ((ch = pStr[next]) == '%') { if ((unescapeMode & UnescapeMode.Unescape) == 0) { // re-escape, don't check anything else escapeReserved = true; } else if (next + 2 < end) { ch = EscapedAscii(pStr[next + 1], pStr[next + 2]); // Unescape a good sequence if full unescape is requested if (unescapeMode >= UnescapeMode.UnescapeAll) { if (ch == Uri.c_DummyChar) { if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow) { // Should be a rare case where the app tries to feed an invalid escaped sequence throw new UriFormatException(SR.net_uri_BadString); } continue; } } // re-escape % from an invalid sequence else if (ch == Uri.c_DummyChar) { if ((unescapeMode & UnescapeMode.Escape) != 0) escapeReserved = true; else continue; // we should throw instead but since v1.0 would just print '%' } // Do not unescape '%' itself unless full unescape is requested else if (ch == '%') { next += 2; continue; } // Do not unescape a reserved char unless full unescape is requested else if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3) { next += 2; continue; } // Do not unescape a dangerous char unless it's V1ToStringFlags mode else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0 && IsNotSafeForUnescape(ch)) { next += 2; continue; } else if (iriParsing && ((ch <= '\x9F' && IsNotSafeForUnescape(ch)) || (ch > '\x9F' && !IriHelper.CheckIriUnicodeRange(ch, isQuery)))) { // check if unenscaping gives a char outside iri range // if it does then keep it escaped next += 2; continue; } // unescape escaped char or escape % break; } else if (unescapeMode >= UnescapeMode.UnescapeAll) { if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow) { // Should be a rare case where the app tries to feed an invalid escaped sequence throw new UriFormatException(SR.net_uri_BadString); } // keep a '%' as part of a bogus sequence continue; } else { escapeReserved = true; } // escape (escapeReserved==true) or otherwise unescape the sequence break; } else if ((unescapeMode & (UnescapeMode.Unescape | UnescapeMode.UnescapeAll)) == (UnescapeMode.Unescape | UnescapeMode.UnescapeAll)) { continue; } else if ((unescapeMode & UnescapeMode.Escape) != 0) { // Could actually escape some of the characters if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3) { // found an unescaped reserved character -> escape it escapeReserved = true; break; } else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0 && (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F'))) { // found an unescaped reserved character -> escape it escapeReserved = true; break; } } } //copy off previous characters from input while (start < next) pDest[destPosition++] = pStr[start++]; if (next != end) { if (escapeReserved) { //escape that char // Since this should be _really_ rare case, reallocate with constant size increase of 30 rsvd-type characters. if (escapedReallocations == 0) { escapedReallocations = 30; char[] newDest = new char[dest.Length + escapedReallocations * 3]; fixed (char* pNewDest = &newDest[0]) { for (int i = 0; i < destPosition; ++i) pNewDest[i] = pDest[i]; } dest = newDest; // re-pin new dest[] array goto dest_fixed_loop_break; } else { --escapedReallocations; EscapeAsciiChar(pStr[next], dest, ref destPosition); escapeReserved = false; start = ++next; continue; } } // unescaping either one Ascii or possibly multiple Unicode if (ch <= '\x7F') { //ASCII dest[destPosition++] = ch; next += 3; start = next; continue; } // Unicode int byteCount = 1; // lazy initialization of max size, will reuse the array for next sequences if ((object)bytes == null) bytes = new byte[end - next]; bytes[0] = (byte)ch; next += 3; while (next < end) { // Check on exit criterion if ((ch = pStr[next]) != '%' || next + 2 >= end) break; // already made sure we have 3 characters in str ch = EscapedAscii(pStr[next + 1], pStr[next + 2]); //invalid hex sequence ? if (ch == Uri.c_DummyChar) break; // character is not part of a UTF-8 sequence ? else if (ch < '\x80') break; else { //a UTF-8 sequence bytes[byteCount++] = (byte)ch; next += 3; } } Encoding noFallbackCharUTF8 = Encoding.GetEncoding( Encoding.UTF8.CodePage, new EncoderReplacementFallback(""), new DecoderReplacementFallback("")); char[] unescapedChars = new char[bytes.Length]; int charCount = noFallbackCharUTF8.GetChars(bytes, 0, byteCount, unescapedChars, 0); start = next; // match exact bytes // Do not unescape chars not allowed by Iri // need to check for invalid utf sequences that may not have given any chars MatchUTF8Sequence(pDest, dest, ref destPosition, unescapedChars, charCount, bytes, byteCount, isQuery, iriParsing); } if (next == end) goto done; } dest_fixed_loop_break:; } } done: return dest; } // // Need to check for invalid utf sequences that may not have given any chars. // We got the unescaped chars, we then re-encode them and match off the bytes // to get the invalid sequence bytes that we just copy off // internal static unsafe void MatchUTF8Sequence(char* pDest, char[] dest, ref int destOffset, char[] unescapedChars, int charCount, byte[] bytes, int byteCount, bool isQuery, bool iriParsing) { int count = 0; fixed (char* unescapedCharsPtr = unescapedChars) { for (int j = 0; j < charCount; ++j) { bool isHighSurr = char.IsHighSurrogate(unescapedCharsPtr[j]); byte[] encodedBytes = Encoding.UTF8.GetBytes(unescapedChars, j, isHighSurr ? 2 : 1); int encodedBytesLength = encodedBytes.Length; // we have to keep unicode chars outside Iri range escaped bool inIriRange = false; if (iriParsing) { if (!isHighSurr) inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], isQuery); else { bool surrPair = false; inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], unescapedChars[j + 1], ref surrPair, isQuery); } } while (true) { // Escape any invalid bytes that were before this character while (bytes[count] != encodedBytes[0]) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)bytes[count++], dest, ref destOffset); } // check if all bytes match bool allBytesMatch = true; int k = 0; for (; k < encodedBytesLength; ++k) { if (bytes[count + k] != encodedBytes[k]) { allBytesMatch = false; break; } } if (allBytesMatch) { count += encodedBytesLength; if (iriParsing) { if (!inIriRange) { // need to keep chars not allowed as escaped for (int l = 0; l < encodedBytes.Length; ++l) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)encodedBytes[l], dest, ref destOffset); } } else if (!UriHelper.IsBidiControlCharacter(unescapedCharsPtr[j])) { //copy chars Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j]; if (isHighSurr) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j + 1]; } } } else { //copy chars Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j]; if (isHighSurr) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j + 1]; } } break; // break out of while (true) since we've matched this char bytes } else { // copy bytes till place where bytes don't match for (int l = 0; l < k; ++l) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)bytes[count++], dest, ref destOffset); } } } if (isHighSurr) j++; } } // Include any trailing invalid sequences while (count < byteCount) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)bytes[count++], dest, ref destOffset); } } internal static void EscapeAsciiChar(char ch, char[] to, ref int pos) { to[pos++] = '%'; to[pos++] = s_hexUpperChars[(ch & 0xf0) >> 4]; to[pos++] = s_hexUpperChars[ch & 0xf]; } internal static char EscapedAscii(char digit, char next) { if (!(((digit >= '0') && (digit <= '9')) || ((digit >= 'A') && (digit <= 'F')) || ((digit >= 'a') && (digit <= 'f')))) { return Uri.c_DummyChar; } int res = (digit <= '9') ? ((int)digit - (int)'0') : (((digit <= 'F') ? ((int)digit - (int)'A') : ((int)digit - (int)'a')) + 10); if (!(((next >= '0') && (next <= '9')) || ((next >= 'A') && (next <= 'F')) || ((next >= 'a') && (next <= 'f')))) { return Uri.c_DummyChar; } return (char)((res << 4) + ((next <= '9') ? ((int)next - (int)'0') : (((next <= 'F') ? ((int)next - (int)'A') : ((int)next - (int)'a')) + 10))); } // Do not unescape these in safe mode: // 1) reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," // 2) excluded = control | "#" | "%" | "\" // // That will still give plenty characters unescaped by SafeUnesced mode such as // 1) Unicode characters // 2) Unreserved = alphanum | "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" // 3) DelimitersAndUnwise = "<" | ">" | <"> | "{" | "}" | "|" | "^" | "[" | "]" | "`" internal static bool IsNotSafeForUnescape(char ch) { if (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F')) return true; else if ((ch >= ';' && ch <= '@' && (ch | '\x2') != '>') || (ch >= '#' && ch <= '&') || ch == '+' || ch == ',' || ch == '/' || ch == '\\') return true; return false; } private const string RFC3986ReservedMarks = @":/?#[]@!$&'()*+,;="; private const string RFC3986UnreservedMarks = @"-._~"; private static unsafe bool IsReservedUnreservedOrHash(char c) { if (IsUnreserved(c)) { return true; } return (RFC3986ReservedMarks.IndexOf(c) >= 0); } internal static unsafe bool IsUnreserved(char c) { if (UriHelper.IsAsciiLetterOrDigit(c)) { return true; } return (RFC3986UnreservedMarks.IndexOf(c) >= 0); } internal static bool Is3986Unreserved(char c) { if (UriHelper.IsAsciiLetterOrDigit(c)) { return true; } return (RFC3986UnreservedMarks.IndexOf(c) >= 0); } // // Is this a gen delim char from RFC 3986 // internal static bool IsGenDelim(char ch) { return (ch == ':' || ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']' || ch == '@'); } // // IsHexDigit // // Determines whether a character is a valid hexadecimal digit in the range // [0..9] | [A..F] | [a..f] // // Inputs: // <argument> character // Character to test // // Returns: // true if <character> is a hexadecimal digit character // // Throws: // Nothing // internal static bool IsHexDigit(char character) { return ((character >= '0') && (character <= '9')) || ((character >= 'A') && (character <= 'F')) || ((character >= 'a') && (character <= 'f')); } // // Returns: // Number in the range 0..15 // // Throws: // ArgumentException // internal static int FromHex(char digit) { if (((digit >= '0') && (digit <= '9')) || ((digit >= 'A') && (digit <= 'F')) || ((digit >= 'a') && (digit <= 'f'))) { return (digit <= '9') ? ((int)digit - (int)'0') : (((digit <= 'F') ? ((int)digit - (int)'A') : ((int)digit - (int)'a')) + 10); } throw new ArgumentOutOfRangeException(nameof(digit)); } internal static readonly char[] s_WSchars = new char[] { ' ', '\n', '\r', '\t' }; internal static bool IsLWS(char ch) { return (ch <= ' ') && (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'); } //Only consider ASCII characters internal static bool IsAsciiLetter(char character) { return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'); } internal static bool IsAsciiLetterOrDigit(char character) { return IsAsciiLetter(character) || (character >= '0' && character <= '9'); } // // Is this a Bidirectional control char.. These get stripped // internal static bool IsBidiControlCharacter(char ch) { return (ch == '\u200E' /*LRM*/ || ch == '\u200F' /*RLM*/ || ch == '\u202A' /*LRE*/ || ch == '\u202B' /*RLE*/ || ch == '\u202C' /*PDF*/ || ch == '\u202D' /*LRO*/ || ch == '\u202E' /*RLO*/); } // // Strip Bidirectional control characters from this string // internal static unsafe string StripBidiControlCharacter(char* strToClean, int start, int length) { if (length <= 0) return ""; char[] cleanStr = new char[length]; int count = 0; for (int i = 0; i < length; ++i) { char c = strToClean[start + i]; if (c < '\u200E' || c > '\u202E' || !IsBidiControlCharacter(c)) { cleanStr[count++] = c; } } return new string(cleanStr, 0, count); } } }
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 Miruken.AspNet.TestWeb.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.Diagnostics; namespace YAF.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 YAF.Lucene.Net.Index; using YAF.Lucene.Net.Support; using Similarity = YAF.Lucene.Net.Search.Similarities.Similarity; internal sealed class ExactPhraseScorer : Scorer { private readonly int endMinus1; private const int CHUNK = 4096; private int gen; private readonly int[] counts = new int[CHUNK]; private readonly int[] gens = new int[CHUNK]; internal bool noDocs; private readonly long cost; private sealed class ChunkState { internal DocsAndPositionsEnum PosEnum { get; private set; } internal int Offset { get; private set; } internal bool UseAdvance { get; private set; } internal int PosUpto { get; set; } internal int PosLimit { get; set; } internal int Pos { get; set; } internal int LastPos { get; set; } public ChunkState(DocsAndPositionsEnum posEnum, int offset, bool useAdvance) { this.PosEnum = posEnum; this.Offset = offset; this.UseAdvance = useAdvance; } } private readonly ChunkState[] chunkStates; private int docID = -1; private int freq; private readonly Similarity.SimScorer docScorer; internal ExactPhraseScorer(Weight weight, PhraseQuery.PostingsAndFreq[] postings, Similarity.SimScorer docScorer) : base(weight) { this.docScorer = docScorer; chunkStates = new ChunkState[postings.Length]; endMinus1 = postings.Length - 1; // min(cost) cost = postings[0].postings.GetCost(); for (int i = 0; i < postings.Length; i++) { // Coarse optimization: advance(target) is fairly // costly, so, if the relative freq of the 2nd // rarest term is not that much (> 1/5th) rarer than // the first term, then we just use .nextDoc() when // ANDing. this buys ~15% gain for phrases where // freq of rarest 2 terms is close: bool useAdvance = postings[i].docFreq > 5 * postings[0].docFreq; chunkStates[i] = new ChunkState(postings[i].postings, -postings[i].position, useAdvance); if (i > 0 && postings[i].postings.NextDoc() == DocIdSetIterator.NO_MORE_DOCS) { noDocs = true; return; } } } public override int NextDoc() { while (true) { // first (rarest) term int doc = chunkStates[0].PosEnum.NextDoc(); if (doc == DocIdSetIterator.NO_MORE_DOCS) { docID = doc; return doc; } // not-first terms int i = 1; while (i < chunkStates.Length) { ChunkState cs = chunkStates[i]; int doc2 = cs.PosEnum.DocID; if (cs.UseAdvance) { if (doc2 < doc) { doc2 = cs.PosEnum.Advance(doc); } } else { int iter = 0; while (doc2 < doc) { // safety net -- fallback to .advance if we've // done too many .nextDocs if (++iter == 50) { doc2 = cs.PosEnum.Advance(doc); break; } else { doc2 = cs.PosEnum.NextDoc(); } } } if (doc2 > doc) { break; } i++; } if (i == chunkStates.Length) { // this doc has all the terms -- now test whether // phrase occurs docID = doc; freq = PhraseFreq(); if (freq != 0) { return docID; } } } } public override int Advance(int target) { // first term int doc = chunkStates[0].PosEnum.Advance(target); if (doc == DocIdSetIterator.NO_MORE_DOCS) { docID = DocIdSetIterator.NO_MORE_DOCS; return doc; } while (true) { // not-first terms int i = 1; while (i < chunkStates.Length) { int doc2 = chunkStates[i].PosEnum.DocID; if (doc2 < doc) { doc2 = chunkStates[i].PosEnum.Advance(doc); } if (doc2 > doc) { break; } i++; } if (i == chunkStates.Length) { // this doc has all the terms -- now test whether // phrase occurs docID = doc; freq = PhraseFreq(); if (freq != 0) { return docID; } } doc = chunkStates[0].PosEnum.NextDoc(); if (doc == DocIdSetIterator.NO_MORE_DOCS) { docID = doc; return doc; } } } public override string ToString() { return "ExactPhraseScorer(" + m_weight + ")"; } public override int Freq { get { return freq; } } public override int DocID { get { return docID; } } public override float GetScore() { return docScorer.Score(docID, freq); } private int PhraseFreq() { freq = 0; // init chunks for (int i = 0; i < chunkStates.Length; i++) { ChunkState cs = chunkStates[i]; cs.PosLimit = cs.PosEnum.Freq; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); cs.PosUpto = 1; cs.LastPos = -1; } int chunkStart = 0; int chunkEnd = CHUNK; // process chunk by chunk bool end = false; // TODO: we could fold in chunkStart into offset and // save one subtract per pos incr while (!end) { gen++; if (gen == 0) { // wraparound Arrays.Fill(gens, 0); gen++; } // first term { ChunkState cs = chunkStates[0]; while (cs.Pos < chunkEnd) { if (cs.Pos > cs.LastPos) { cs.LastPos = cs.Pos; int posIndex = cs.Pos - chunkStart; counts[posIndex] = 1; Debug.Assert(gens[posIndex] != gen); gens[posIndex] = gen; } if (cs.PosUpto == cs.PosLimit) { end = true; break; } cs.PosUpto++; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); } } // middle terms bool any = true; for (int t = 1; t < endMinus1; t++) { ChunkState cs = chunkStates[t]; any = false; while (cs.Pos < chunkEnd) { if (cs.Pos > cs.LastPos) { cs.LastPos = cs.Pos; int posIndex = cs.Pos - chunkStart; if (posIndex >= 0 && gens[posIndex] == gen && counts[posIndex] == t) { // viable counts[posIndex]++; any = true; } } if (cs.PosUpto == cs.PosLimit) { end = true; break; } cs.PosUpto++; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); } if (!any) { break; } } if (!any) { // petered out for this chunk chunkStart += CHUNK; chunkEnd += CHUNK; continue; } // last term { ChunkState cs = chunkStates[endMinus1]; while (cs.Pos < chunkEnd) { if (cs.Pos > cs.LastPos) { cs.LastPos = cs.Pos; int posIndex = cs.Pos - chunkStart; if (posIndex >= 0 && gens[posIndex] == gen && counts[posIndex] == endMinus1) { freq++; } } if (cs.PosUpto == cs.PosLimit) { end = true; break; } cs.PosUpto++; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); } } chunkStart += CHUNK; chunkEnd += CHUNK; } return freq; } public override long GetCost() { return cost; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Runtime.InteropServices; using Xunit; namespace System.IO.MemoryMappedFiles.Tests { /// <summary> /// Tests for MemoryMappedFile.CreateFromFile. /// </summary> public class MemoryMappedFileTests_CreateFromFile : MemoryMappedFilesTestBase { /// <summary> /// Tests invalid arguments to the CreateFromFile path parameter. /// </summary> [Fact] public void InvalidArguments_Path() { // null is an invalid path Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null)); Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open)); Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName())); Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096)); Assert.Throws<ArgumentNullException>("path", () => MemoryMappedFile.CreateFromFile(null, FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read)); } /// <summary> /// Tests invalid arguments to the CreateFromFile fileStream parameter. /// </summary> [Fact] public void InvalidArguments_FileStream() { // null is an invalid stream Assert.Throws<ArgumentNullException>("fileStream", () => MemoryMappedFile.CreateFromFile(null, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); } /// <summary> /// Tests invalid arguments to the CreateFromFile mode parameter. /// </summary> [Fact] public void InvalidArguments_Mode() { // FileMode out of range Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42)); Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null)); Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096)); Assert.Throws<ArgumentOutOfRangeException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), (FileMode)42, null, 4096, MemoryMappedFileAccess.ReadWrite)); // FileMode.Append never allowed Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append)); Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null)); Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096)); Assert.Throws<ArgumentException>("mode", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Append, null, 4096, MemoryMappedFileAccess.ReadWrite)); // FileMode.CreateNew/Create/OpenOrCreate can't be used with default capacity, as the file will be empty Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Create)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.OpenOrCreate)); // FileMode.Truncate can't be used with default capacity, as resulting file will be empty using (TempFile file = new TempFile(GetTestFilePath())) { Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Truncate)); } } /// <summary> /// Tests invalid arguments to the CreateFromFile access parameter. /// </summary> [Fact] public void InvalidArguments_Access() { // Out of range access values with a path Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2))); Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42))); // Write-only access is not allowed on maps (only on views) Assert.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.Open, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write)); // Test the same things, but with a FileStream instead of a path using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // Out of range values with a stream Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(-2), HandleInheritability.None, true)); Assert.Throws<ArgumentOutOfRangeException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, (MemoryMappedFileAccess)(42), HandleInheritability.None, true)); // Write-only access is not allowed Assert.Throws<ArgumentException>("access", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.Write, HandleInheritability.None, true)); } } /// <summary> /// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used /// to construct a map over that stream. The combinations should all be valid. /// </summary> [Theory] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)] public void FileAccessAndMapAccessCombinations_Valid(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true)) { ValidateMemoryMappedFile(mmf, Capacity, mmfAccess); } } /// <summary> /// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used /// to construct a map over that stream on Windows. The combinations should all be invalid, resulting in exception. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // On Windows, permission errors come from CreateFromFile [Theory] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)] // this and the next are explicitly left off of the Unix test due to differences in Unix permissions [InlineData(FileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)] public void FileAccessAndMapAccessCombinations_Invalid_Windows(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess) { // On Windows, creating the file mapping does the permissions checks, so the exception comes from CreateFromFile. const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess)) { Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true)); } } /// <summary> /// Tests various values of FileAccess used to construct a FileStream and MemoryMappedFileAccess used /// to construct a map over that stream on Unix. The combinations should all be invalid, resulting in exception. /// </summary> [PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, permission errors come from CreateView* [Theory] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.Read)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadExecute)] [InlineData(FileAccess.Write, MemoryMappedFileAccess.ReadWriteExecute)] public void FileAccessAndMapAccessCombinations_Invalid_Unix(FileAccess fileAccess, MemoryMappedFileAccess mmfAccess) { // On Unix we don't actually create the OS map until the view is created; this results in the permissions // error being thrown from CreateView* instead of from CreateFromFile. const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open, fileAccess)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, mmfAccess, HandleInheritability.None, true)) { Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewAccessor()); } } /// <summary> /// Tests invalid arguments to the CreateFromFile mapName parameter. /// </summary> [Fact] public void InvalidArguments_MapName() { using (TempFile file = new TempFile(GetTestFilePath())) { // Empty string is an invalid map name Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, string.Empty, 4096, MemoryMappedFileAccess.Read)); using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, string.Empty, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)); } } } /// <summary> /// Test to verify that map names are left unsupported on Unix. /// </summary> [PlatformSpecific(TestPlatforms.AnyUnix)] // Check map names are unsupported on Unix [Theory] [MemberData(nameof(CreateValidMapNames))] public void MapNamesNotSupported_Unix(string mapName) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) { Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, mapName, Capacity, MemoryMappedFileAccess.ReadWrite)); using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<PlatformNotSupportedException>(() => MemoryMappedFile.CreateFromFile(fs, mapName, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)); } } } /// <summary> /// Tests invalid arguments to the CreateFromFile capacity parameter. /// </summary> [Fact] public void InvalidArguments_Capacity() { using (TempFile file = new TempFile(GetTestFilePath())) { // Out of range values for capacity Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), -1, MemoryMappedFileAccess.Read)); // Positive capacity required when creating a map from an empty file Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 0, MemoryMappedFileAccess.Read)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read)); // With Read, the capacity can't be larger than the backing file's size. Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read)); // Now with a FileStream... using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // The subsequent tests are only valid we if we start with an empty FileStream, which we should have. // This also verifies the previous failed tests didn't change the length of the file. Assert.Equal(0, fs.Length); // Out of range values for capacity Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMappedFile.CreateFromFile(fs, null, -1, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); // Default (0) capacity with an empty file Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); // Larger capacity than the underlying file, but read-only such that we can't expand the file fs.SetLength(4096); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, null, 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); Assert.Throws<ArgumentException>(() => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 8192, MemoryMappedFileAccess.Read, HandleInheritability.None, true)); // Capacity can't be less than the file size (for such cases a view can be created with the smaller size) Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(fs, null, 1, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)); } // Capacity can't be less than the file size Assert.Throws<ArgumentOutOfRangeException>("capacity", () => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, CreateUniqueMapName(), 1, MemoryMappedFileAccess.Read)); } } /// <summary> /// Tests invalid arguments to the CreateFromFile inheritability parameter. /// </summary> [Theory] [InlineData((HandleInheritability)(-1))] [InlineData((HandleInheritability)(42))] public void InvalidArguments_Inheritability(HandleInheritability inheritability) { // Out of range values for inheritability using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<ArgumentOutOfRangeException>("inheritability", () => MemoryMappedFile.CreateFromFile(fs, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite, inheritability, true)); } } /// <summary> /// Test various combinations of arguments to CreateFromFile, focusing on the Open and OpenOrCreate modes, /// and validating the creating maps each time they're created. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath), new FileMode[] { FileMode.Open, FileMode.OpenOrCreate }, new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })] public void ValidArgumentCombinationsWithPath_ModesOpenOrCreate( FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access) { // Test each of the four path-based CreateFromFile overloads using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } // Finally, re-test the last overload, this time with an empty file to start using (TempFile file = new TempFile(GetTestFilePath())) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } } /// <summary> /// Test various combinations of arguments to CreateFromFile, focusing on the CreateNew mode, /// and validating the creating maps each time they're created. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath), new FileMode[] { FileMode.CreateNew }, new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })] public void ValidArgumentCombinationsWithPath_ModeCreateNew( FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access) { // For FileMode.CreateNew, the file will be created new and thus be empty, so we can only use the overloads // that take a capacity, since the default capacity doesn't work with an empty file. using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } } /// <summary> /// Test various combinations of arguments to CreateFromFile, focusing on the Create and Truncate modes, /// and validating the creating maps each time they're created. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinationsWithPath), new FileMode[] { FileMode.Create, FileMode.Truncate }, new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite })] public void ValidArgumentCombinationsWithPath_ModesCreateOrTruncate( FileMode mode, string mapName, long capacity, MemoryMappedFileAccess access) { // For FileMode.Create/Truncate, try existing files. Only the overloads that take a capacity are valid because // both of these modes will cause the input file to be made empty, and an empty file doesn't work with the default capacity. using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, mode, mapName, capacity, access)) { ValidateMemoryMappedFile(mmf, capacity, access); } // For FileMode.Create, also try letting it create a new file (Truncate needs the file to have existed) if (mode == FileMode.Create) { using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, mapName, capacity)) { ValidateMemoryMappedFile(mmf, capacity); } } } /// <summary> /// Provides input data to the ValidArgumentCombinationsWithPath tests, yielding the full matrix /// of combinations of input values provided, except for those that are known to be unsupported /// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders /// listed in the MemberData attribute (e.g. actual system page size instead of -1). /// </summary> /// <param name="modes">The modes to yield.</param> /// <param name="mapNames"> /// The names to yield. /// non-null may be excluded based on platform. /// "CreateUniqueMapName()" will be translated to an invocation of that method. /// </param> /// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param> /// <param name="accesses"> /// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it. /// </param> public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithPath( FileMode[] modes, string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses) { foreach (FileMode mode in modes) { foreach (string tmpMapName in mapNames) { if (tmpMapName != null && !MapNamesSupported) { continue; } foreach (long tmpCapacity in capacities) { long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity; foreach (MemoryMappedFileAccess access in accesses) { if ((mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate) && !IsWritable(access)) { continue; } string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName; yield return new object[] { mode, mapName, capacity, access }; } } } } } /// <summary> /// Test various combinations of arguments to CreateFromFile that accepts a FileStream. /// </summary> [Theory] [MemberData(nameof(MemberData_ValidArgumentCombinationsWithStream), new string[] { null, "CreateUniqueMapName()" }, new long[] { 1, 256, -1 /*pagesize*/, 10000 }, new MemoryMappedFileAccess[] { MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite }, new HandleInheritability[] { HandleInheritability.None, HandleInheritability.Inheritable }, new bool[] { false, true })] public void ValidArgumentCombinationsWithStream( string mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen) { // Create a file of the right size, then create the map for it. using (TempFile file = new TempFile(GetTestFilePath(), capacity)) using (FileStream fs = File.Open(file.Path, FileMode.Open)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } // Start with an empty file and let the map grow it to the right size. This requires write access. if (IsWritable(access)) { using (FileStream fs = File.Create(GetTestFilePath())) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, mapName, capacity, access, inheritability, leaveOpen)) { ValidateMemoryMappedFile(mmf, capacity, access, inheritability); } } } /// <summary> /// Provides input data to the ValidArgumentCombinationsWithStream tests, yielding the full matrix /// of combinations of input values provided, except for those that are known to be unsupported /// (e.g. non-null map names on Unix), and with appropriate values substituted in for placeholders /// listed in the MemberData attribute (e.g. actual system page size instead of -1). /// </summary> /// <param name="mapNames"> /// The names to yield. /// non-null may be excluded based on platform. /// "CreateUniqueMapName()" will be translated to an invocation of that method. /// </param> /// <param name="capacities">The capacities to yield. -1 will be translated to system page size.</param> /// <param name="accesses"> /// The accesses to yield. Non-writable accesses will be skipped if the current mode doesn't support it. /// </param> /// <param name="inheritabilities">The inheritabilities to yield.</param> /// <param name="inheritabilities">The leaveOpen values to yield.</param> public static IEnumerable<object[]> MemberData_ValidArgumentCombinationsWithStream( string[] mapNames, long[] capacities, MemoryMappedFileAccess[] accesses, HandleInheritability[] inheritabilities, bool[] leaveOpens) { foreach (string tmpMapName in mapNames) { if (tmpMapName != null && !MapNamesSupported) { continue; } foreach (long tmpCapacity in capacities) { long capacity = tmpCapacity == -1 ? s_pageSize.Value : tmpCapacity; foreach (MemoryMappedFileAccess access in accesses) { foreach (HandleInheritability inheritability in inheritabilities) { foreach (bool leaveOpen in leaveOpens) { string mapName = tmpMapName == "CreateUniqueMapName()" ? CreateUniqueMapName() : tmpMapName; yield return new object[] { mapName, capacity, access, inheritability, leaveOpen }; } } } } } } /// <summary> /// Test that a map using the default capacity (0) grows to the size of the underlying file. /// </summary> [Fact] public void DefaultCapacityIsFileLength() { const int DesiredCapacity = 8192; const int DefaultCapacity = 0; // With path using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, DefaultCapacity)) { ValidateMemoryMappedFile(mmf, DesiredCapacity); } // With stream using (TempFile file = new TempFile(GetTestFilePath(), DesiredCapacity)) using (FileStream fs = File.Open(file.Path, FileMode.Open)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, DefaultCapacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)) { ValidateMemoryMappedFile(mmf, DesiredCapacity); } } /// <summary> /// Test that appropriate exceptions are thrown creating a map with a non-existent file and a mode /// that requires the file to exist. /// </summary> [Theory] [InlineData(FileMode.Truncate)] [InlineData(FileMode.Open)] public void FileDoesNotExist(FileMode mode) { Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath())); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode)); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, null)); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, null, 4096)); Assert.Throws<FileNotFoundException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), mode, null, 4096, MemoryMappedFileAccess.ReadWrite)); } /// <summary> /// Test that appropriate exceptions are thrown creating a map with an existing file and a mode /// that requires the file to not exist. /// </summary> [Fact] public void FileAlreadyExists() { using (TempFile file = new TempFile(GetTestFilePath())) { // FileMode.CreateNew invalid when the file already exists Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew)); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName())); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096)); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.CreateNew, CreateUniqueMapName(), 4096, MemoryMappedFileAccess.ReadWrite)); } } /// <summary> /// Test exceptional behavior when trying to create a map for a read-write file that's currently in use. /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent public void FileInUse_CreateFromFile_FailsWithExistingReadWriteFile() { // Already opened with a FileStream using (TempFile file = new TempFile(GetTestFilePath(), 4096)) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path)); } } /// <summary> /// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use. /// </summary> [Fact] [PlatformSpecific(TestPlatforms.Windows)] // FileShare is limited on Unix, with None == exclusive, everything else == concurrent public void FileInUse_CreateFromFile_FailsWithExistingReadWriteMap() { // Already opened with another read-write map using (TempFile file = new TempFile(GetTestFilePath(), 4096)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path)) { Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path)); } } /// <summary> /// Test exceptional behavior when trying to create a map for a non-shared file that's currently in use. /// </summary> [Fact] public void FileInUse_CreateFromFile_FailsWithExistingNoShareFile() { // Already opened with a FileStream using (TempFile file = new TempFile(GetTestFilePath(), 4096)) using (FileStream fs = File.Open(file.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(file.Path)); } } /// <summary> /// Test to validate we can create multiple concurrent read-only maps from the same file path. /// </summary> [Fact] public void FileInUse_CreateFromFile_SucceedsWithReadOnly() { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, MemoryMappedFileAccess.Read)) using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read)) using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor(0, Capacity, MemoryMappedFileAccess.Read)) { Assert.Equal(acc1.Capacity, acc2.Capacity); } } /// <summary> /// Test the exceptional behavior of *Execute access levels. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Unix model for executable differs from Windows [Theory] [InlineData(MemoryMappedFileAccess.ReadExecute)] [InlineData(MemoryMappedFileAccess.ReadWriteExecute)] public void FileNotOpenedForExecute(MemoryMappedFileAccess access) { using (TempFile file = new TempFile(GetTestFilePath(), 4096)) { // The FileStream created by the map doesn't have GENERIC_EXECUTE set Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, 4096, access)); // The FileStream opened explicitly doesn't have GENERIC_EXECUTE set using (FileStream fs = File.Open(file.Path, FileMode.Open)) { Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(fs, null, 4096, access, HandleInheritability.None, true)); } } } /// <summary> /// On Unix, modifying a file that is ReadOnly will fail under normal permissions. /// If the test is being run under the superuser, however, modification of a ReadOnly /// file is allowed. /// </summary> [Theory] [InlineData(MemoryMappedFileAccess.Read)] [InlineData(MemoryMappedFileAccess.ReadWrite)] [InlineData(MemoryMappedFileAccess.CopyOnWrite)] public void WriteToReadOnlyFile(MemoryMappedFileAccess access) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) { FileAttributes original = File.GetAttributes(file.Path); File.SetAttributes(file.Path, FileAttributes.ReadOnly); try { if (access == MemoryMappedFileAccess.Read || (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && geteuid() == 0)) using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access)) ValidateMemoryMappedFile(mmf, Capacity, MemoryMappedFileAccess.Read); else Assert.Throws<UnauthorizedAccessException>(() => MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, Capacity, access)); } finally { File.SetAttributes(file.Path, original); } } } [DllImport("libc", SetLastError = true)] private static extern int geteuid(); /// <summary> /// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open /// or closing it on disposal. /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void LeaveOpenRespected_Basic(bool leaveOpen) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // Handle should still be open SafeFileHandle handle = fs.SafeFileHandle; Assert.False(handle.IsClosed); // Create and close the map MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen).Dispose(); // The handle should now be open iff leaveOpen Assert.NotEqual(leaveOpen, handle.IsClosed); } } /// <summary> /// Test to ensure that leaveOpen is appropriately respected, either leaving the FileStream open /// or closing it on disposal. /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void LeaveOpenRespected_OutstandingViews(bool leaveOpen) { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath())) using (FileStream fs = File.Open(file.Path, FileMode.Open)) { // Handle should still be open SafeFileHandle handle = fs.SafeFileHandle; Assert.False(handle.IsClosed); // Create the map, create each of the views, then close the map using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen)) using (MemoryMappedViewAccessor acc = mmf.CreateViewAccessor(0, Capacity)) using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity)) { // Explicitly close the map. The handle should now be open iff leaveOpen. mmf.Dispose(); Assert.NotEqual(leaveOpen, handle.IsClosed); // But the views should still be usable. ValidateMemoryMappedViewAccessor(acc, Capacity, MemoryMappedFileAccess.ReadWrite); ValidateMemoryMappedViewStream(s, Capacity, MemoryMappedFileAccess.ReadWrite); } } } /// <summary> /// Test to validate we can create multiple maps from the same FileStream. /// </summary> [Fact] public void MultipleMapsForTheSameFileStream() { const int Capacity = 4096; using (TempFile file = new TempFile(GetTestFilePath(), Capacity)) using (FileStream fs = new FileStream(file.Path, FileMode.Open)) using (MemoryMappedFile mmf1 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)) using (MemoryMappedFile mmf2 = MemoryMappedFile.CreateFromFile(fs, null, Capacity, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true)) using (MemoryMappedViewAccessor acc1 = mmf1.CreateViewAccessor()) using (MemoryMappedViewAccessor acc2 = mmf2.CreateViewAccessor()) { // The capacity of the two maps should be equal Assert.Equal(acc1.Capacity, acc2.Capacity); var rand = new Random(); for (int i = 1; i <= 10; i++) { // Write a value to one map, then read it from the other, // ping-ponging between the two. int pos = rand.Next((int)acc1.Capacity - 1); MemoryMappedViewAccessor reader = acc1, writer = acc2; if (i % 2 == 0) { reader = acc2; writer = acc1; } writer.Write(pos, (byte)i); writer.Flush(); Assert.Equal(i, reader.ReadByte(pos)); } } } /// <summary> /// Test to verify that the map's size increases the underlying file size if the map's capacity is larger. /// </summary> [Fact] public void FileSizeExpandsToCapacity() { const int InitialCapacity = 256; using (TempFile file = new TempFile(GetTestFilePath(), InitialCapacity)) { // Create a map with a larger capacity, and verify the file has expanded. MemoryMappedFile.CreateFromFile(file.Path, FileMode.Open, null, InitialCapacity * 2).Dispose(); using (FileStream fs = File.OpenRead(file.Path)) { Assert.Equal(InitialCapacity * 2, fs.Length); } // Do the same thing again but with a FileStream. using (FileStream fs = File.Open(file.Path, FileMode.Open)) { MemoryMappedFile.CreateFromFile(fs, null, InitialCapacity * 4, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose(); Assert.Equal(InitialCapacity * 4, fs.Length); } } } /// <summary> /// Test the exceptional behavior when attempting to create a map so large it's not supported. /// </summary> [PlatformSpecific(~TestPlatforms.OSX)] // Because of the file-based backing, OS X pops up a warning dialog about being out-of-space (even though we clean up immediately) [Fact] public void TooLargeCapacity() { using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.CreateNew)) { try { long length = long.MaxValue; MemoryMappedFile.CreateFromFile(fs, null, length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true).Dispose(); Assert.Equal(length, fs.Length); // if it didn't fail to create the file, the length should be what was requested. } catch (IOException) { // Expected exception for too large a capacity } } } /// <summary> /// Test to verify map names are handled appropriately, causing a conflict when they're active but /// reusable in a sequential manner. /// </summary> [PlatformSpecific(TestPlatforms.Windows)] // Tests reusability of map names on Windows [Theory] [MemberData(nameof(CreateValidMapNames))] public void ReusingNames_Windows(string name) { const int Capacity = 4096; using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity)) { ValidateMemoryMappedFile(mmf, Capacity); Assert.Throws<IOException>(() => MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity)); } using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(GetTestFilePath(), FileMode.CreateNew, name, Capacity)) { ValidateMemoryMappedFile(mmf, Capacity); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Resource; using Apache.Ignite.Core.Tests.Cache; using NUnit.Framework; /// <summary> /// <see cref="IMessaging"/> tests. /// </summary> public sealed class MessagingTest { /** */ private IIgnite _grid1; /** */ private IIgnite _grid2; /** */ private IIgnite _grid3; /** */ private static int _messageId; /** Objects to test against. */ private static readonly object[] Objects = { // Primitives. null, "string topic", Guid.NewGuid(), DateTime.Now, byte.MinValue, short.MaxValue, // Enums. CacheMode.Local, GCCollectionMode.Forced, // Objects. new CacheTestKey(25), new IgniteGuid(Guid.NewGuid(), 123), }; /// <summary> /// Executes before each test. /// </summary> [SetUp] public void SetUp() { _grid1 = Ignition.Start(GetConfiguration("grid-1")); _grid2 = Ignition.Start(GetConfiguration("grid-2")); _grid3 = Ignition.Start(GetConfiguration("grid-3")); Assert.AreEqual(3, _grid1.GetCluster().GetNodes().Count); } /// <summary> /// Executes after each test. /// </summary> [TearDown] public void TearDown() { try { TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3); MessagingTestHelper.AssertFailures(); } finally { // Stop all grids between tests to drop any hanging messages Ignition.StopAll(true); } } /// <summary> /// Tests that any data type can be used as a message. /// </summary> [Test] public void TestMessageDataTypes() { object lastMsg = null; var evt = new AutoResetEvent(false); var messaging1 = _grid1.GetMessaging(); var messaging2 = _grid2.GetMessaging(); var listener = new MessageListener<object>((nodeId, msg) => { lastMsg = msg; evt.Set(); return true; }); foreach (var msg in Objects.Where(x => x != null)) { var topic = "dataTypes" + Guid.NewGuid(); messaging1.LocalListen(listener, topic); messaging2.Send(msg, topic); evt.WaitOne(500); Assert.AreEqual(msg, lastMsg); messaging1.StopLocalListen(listener, topic); } } /// <summary> /// Tests LocalListen. /// </summary> [Test] public void TestLocalListen() { TestLocalListen(NextId()); foreach (var topic in Objects) { TestLocalListen(topic); } } /// <summary> /// Tests LocalListen. /// </summary> [SuppressMessage("ReSharper", "AccessToModifiedClosure")] private void TestLocalListen(object topic) { var messaging = _grid1.GetMessaging(); var listener = MessagingTestHelper.GetListener(); messaging.LocalListen(listener, topic); // Test sending CheckSend(topic); CheckSend(topic, _grid2); CheckSend(topic, _grid3); // Test different topic CheckNoMessage(NextId()); CheckNoMessage(NextId(), _grid2); // Test multiple subscriptions for the same filter messaging.LocalListen(listener, topic); messaging.LocalListen(listener, topic); CheckSend(topic, repeatMultiplier: 3); // expect all messages repeated 3 times messaging.StopLocalListen(listener, topic); CheckSend(topic, repeatMultiplier: 2); // expect all messages repeated 2 times messaging.StopLocalListen(listener, topic); CheckSend(topic); // back to 1 listener // Test message type mismatch var ex = Assert.Throws<IgniteException>(() => messaging.Send(1.1, topic)); Assert.AreEqual("Unable to cast object of type 'System.Double' to type 'System.String'.", ex.Message); // Test end listen MessagingTestHelper.ListenResult = false; CheckSend(topic, single: true); // we'll receive one more and then unsubscribe because of delegate result. CheckNoMessage(topic); // Start again MessagingTestHelper.ListenResult = true; messaging.LocalListen(listener, topic); CheckSend(topic); // Stop messaging.StopLocalListen(listener, topic); CheckNoMessage(topic); } /// <summary> /// Tests LocalListen with projection. /// </summary> [Test] public void TestLocalListenProjection() { TestLocalListenProjection(NextId()); TestLocalListenProjection("prj"); foreach (var topic in Objects) { TestLocalListenProjection(topic); } } /// <summary> /// Tests LocalListen with projection. /// </summary> private void TestLocalListenProjection(object topic) { var grid3GotMessage = false; var grid3Listener = new MessageListener<string>((id, x) => { grid3GotMessage = true; return true; }); _grid3.GetMessaging().LocalListen(grid3Listener, topic); var clusterMessaging = _grid1.GetCluster().ForNodes(_grid1.GetCluster().GetLocalNode(), _grid2.GetCluster().GetLocalNode()).GetMessaging(); var clusterListener = MessagingTestHelper.GetListener(); clusterMessaging.LocalListen(clusterListener, topic); CheckSend(msg: clusterMessaging, topic: topic); Assert.IsFalse(grid3GotMessage, "Grid3 should not get messages"); CheckSend(grid: _grid2, msg: clusterMessaging, topic: topic); Assert.IsFalse(grid3GotMessage, "Grid3 should not get messages"); clusterMessaging.StopLocalListen(clusterListener, topic); _grid3.GetMessaging().StopLocalListen(grid3Listener, topic); } /// <summary> /// Tests LocalListen in multithreaded mode. /// </summary> [Test] [SuppressMessage("ReSharper", "AccessToModifiedClosure")] [Category(TestUtils.CategoryIntensive)] public void TestLocalListenMultithreaded() { const int threadCnt = 20; const int runSeconds = 20; var messaging = _grid1.GetMessaging(); var senders = TaskRunner.Run(() => TestUtils.RunMultiThreaded(() => { messaging.Send(NextMessage()); Thread.Sleep(50); }, threadCnt, runSeconds)); var sharedReceived = 0; var sharedListener = new MessageListener<string>((id, x) => { Interlocked.Increment(ref sharedReceived); Thread.MemoryBarrier(); return true; }); TestUtils.RunMultiThreaded(() => { // Check that listen/stop work concurrently messaging.LocalListen(sharedListener); for (int i = 0; i < 100; i++) { messaging.LocalListen(sharedListener); messaging.StopLocalListen(sharedListener); } var localReceived = 0; var stopLocal = 0; var localListener = new MessageListener<string>((id, x) => { Interlocked.Increment(ref localReceived); Thread.MemoryBarrier(); return Thread.VolatileRead(ref stopLocal) == 0; }); messaging.LocalListen(localListener); Thread.Sleep(100); Thread.VolatileWrite(ref stopLocal, 1); Thread.Sleep(1000); var result = Thread.VolatileRead(ref localReceived); Thread.Sleep(100); // Check that unsubscription worked properly Assert.AreEqual(result, Thread.VolatileRead(ref localReceived)); messaging.StopLocalListen(sharedListener); }, threadCnt, runSeconds); senders.Wait(); Thread.Sleep(100); var sharedResult = Thread.VolatileRead(ref sharedReceived); messaging.Send(NextMessage()); Thread.Sleep(MessagingTestHelper.SleepTimeout); // Check that unsubscription worked properly Assert.AreEqual(sharedResult, Thread.VolatileRead(ref sharedReceived)); } /// <summary> /// Tests RemoteListen. /// </summary> [Test] public void TestRemoteListen([Values(true, false)] bool async) { TestRemoteListen(NextId(), async); foreach (var topic in Objects) { TestRemoteListen(topic, async); } } /// <summary> /// Tests that <see cref="IMessaging.StopRemoteListen"/> guarantees that all handlers are removed /// upon method exit. /// </summary> [Test] [Ignore("IGNITE-14032")] public void TestStopRemoteListenRemovesAllCallbacksUponExit() { const string topic = "topic"; var messaging =_grid1.GetMessaging(); var listenId = messaging.RemoteListen(MessagingTestHelper.GetListener("first"), topic); TestUtils.AssertHandleRegistryHasItems(-1, 1, _grid1, _grid2, _grid3); messaging.Send(1, topic); messaging.StopRemoteListen(listenId); TestUtils.AssertHandleRegistryHasItems(-1, 0, _grid1, _grid2, _grid3); } /// <summary> /// Tests RemoteListen. /// </summary> private void TestRemoteListen(object topic, bool async = false) { var messaging =_grid1.GetMessaging(); var listener = MessagingTestHelper.GetListener("first"); var listenId = async ? messaging.RemoteListenAsync(listener, topic).Result : messaging.RemoteListen(listener, topic); // Test sending CheckSend(topic, msg: messaging, remoteListen: true); // Test different topic CheckNoMessage(NextId()); // Test multiple subscriptions for the same filter var listener2 = MessagingTestHelper.GetListener("second"); var listenId2 = async ? messaging.RemoteListenAsync(listener2, topic).Result : messaging.RemoteListen(listener2, topic); CheckSend(topic, msg: messaging, remoteListen: true, repeatMultiplier: 2); // expect twice the messages if (async) messaging.StopRemoteListenAsync(listenId2).Wait(); else messaging.StopRemoteListen(listenId2); // Wait for all to unsubscribe: StopRemoteListen (both sync and async) does not remove remote listeners // upon exit. Remote listeners are removed with disco messages after some delay - // see TestStopRemoteListenRemovesAllCallbacksUponExit. TestUtils.AssertHandleRegistryHasItems( (int)MessagingTestHelper.SleepTimeout.TotalMilliseconds, 1, _grid1, _grid2, _grid3); CheckSend(topic, msg: messaging, remoteListen: true); // back to normal after unsubscription // Test message type mismatch var ex = Assert.Throws<IgniteException>(() => messaging.Send(1.1, topic)); Assert.AreEqual("Unable to cast object of type 'System.Double' to type 'System.String'.", ex.Message); // Test end listen if (async) messaging.StopRemoteListenAsync(listenId).Wait(); else messaging.StopRemoteListen(listenId); CheckNoMessage(topic); } /// <summary> /// Tests RemoteListen with a projection. /// </summary> [Test] public void TestRemoteListenProjection() { TestRemoteListenProjection(NextId()); foreach (var topic in Objects) { TestRemoteListenProjection(topic); } } /// <summary> /// Tests RemoteListen with a projection. /// </summary> private void TestRemoteListenProjection(object topic) { var clusterMessaging = _grid1.GetCluster().ForNodes(_grid1.GetCluster().GetLocalNode(), _grid2.GetCluster().GetLocalNode()).GetMessaging(); var clusterListener = MessagingTestHelper.GetListener(); var listenId = clusterMessaging.RemoteListen(clusterListener, topic); CheckSend(msg: clusterMessaging, topic: topic, remoteListen: true); clusterMessaging.StopRemoteListen(listenId); CheckNoMessage(topic); } /// <summary> /// Tests LocalListen in multithreaded mode. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestRemoteListenMultithreaded() { const int threadCnt = 20; const int runSeconds = 20; var messaging = _grid1.GetMessaging(); var senders = TaskRunner.Run(() => TestUtils.RunMultiThreaded(() => { MessagingTestHelper.ClearReceived(int.MaxValue); messaging.Send(NextMessage()); Thread.Sleep(50); }, threadCnt, runSeconds)); var sharedListener = MessagingTestHelper.GetListener(); for (int i = 0; i < 100; i++) messaging.RemoteListen(sharedListener); // add some listeners to be stopped by filter result TestUtils.RunMultiThreaded(() => { // Check that listen/stop work concurrently messaging.StopRemoteListen(messaging.RemoteListen(sharedListener)); }, threadCnt, runSeconds / 2); MessagingTestHelper.ListenResult = false; messaging.Send(NextMessage()); // send a message to make filters return false Thread.Sleep(MessagingTestHelper.SleepTimeout); // wait for all to unsubscribe MessagingTestHelper.ListenResult = true; senders.Wait(); // wait for senders to stop MessagingTestHelper.ClearReceived(int.MaxValue); var lastMsg = NextMessage(); messaging.Send(lastMsg); Thread.Sleep(MessagingTestHelper.SleepTimeout); // Check that unsubscription worked properly var sharedResult = MessagingTestHelper.ReceivedMessages.ToArray(); if (sharedResult.Length != 0) { Assert.Fail("Unexpected messages ({0}): {1}; last sent message: {2}", sharedResult.Length, string.Join(",", sharedResult.Select(x => x.ToString())), lastMsg); } } /// <summary> /// Sends messages in various ways and verefies correct receival. /// </summary> /// <param name="topic">Topic.</param> /// <param name="grid">The grid to use.</param> /// <param name="msg">Messaging to use.</param> /// <param name="remoteListen">Whether to expect remote listeners.</param> /// <param name="single">When true, only check one message.</param> /// <param name="repeatMultiplier">Expected message count multiplier.</param> private void CheckSend(object topic = null, IIgnite grid = null, IMessaging msg = null, bool remoteListen = false, bool single = false, int repeatMultiplier = 1) { IClusterGroup cluster; if (msg != null) cluster = msg.ClusterGroup; else { grid = grid ?? _grid1; msg = grid.GetMessaging(); cluster = grid.GetCluster().ForLocal(); } // Messages will repeat due to multiple nodes listening var expectedRepeat = repeatMultiplier * (remoteListen ? cluster.GetNodes().Count : 1); var messages = Enumerable.Range(1, 10).Select(x => NextMessage()).OrderBy(x => x).ToList(); // Single message MessagingTestHelper.ClearReceived(expectedRepeat); msg.Send(messages[0], topic); MessagingTestHelper.VerifyReceive(cluster, messages.Take(1), m => m.ToList(), expectedRepeat); if (single) return; // Multiple messages (receive order is undefined) MessagingTestHelper.ClearReceived(messages.Count * expectedRepeat); msg.SendAll(messages, topic); MessagingTestHelper.VerifyReceive(cluster, messages, m => m.OrderBy(x => x), expectedRepeat); // Multiple messages, ordered MessagingTestHelper.ClearReceived(messages.Count * expectedRepeat); messages.ForEach(x => msg.SendOrdered(x, topic, MessagingTestHelper.MessageTimeout)); if (remoteListen) // in remote scenario messages get mixed up due to different timing on different nodes MessagingTestHelper.VerifyReceive(cluster, messages, m => m.OrderBy(x => x), expectedRepeat); else MessagingTestHelper.VerifyReceive(cluster, messages, m => m.Reverse(), expectedRepeat); } /// <summary> /// Checks that no message has arrived. /// </summary> private void CheckNoMessage(object topic, IIgnite grid = null) { // this will result in an exception in case of a message MessagingTestHelper.ClearReceived(0); (grid ?? _grid1).GetMessaging().SendAll(NextMessage(), topic); Thread.Sleep(MessagingTestHelper.SleepTimeout); MessagingTestHelper.AssertFailures(); } /// <summary> /// Gets the Ignite configuration. /// </summary> private static IgniteConfiguration GetConfiguration(string name) { return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { IgniteInstanceName = name }; } /// <summary> /// Generates next message with sequential ID and current test name. /// </summary> private static string NextMessage() { var id = NextId(); return id + "_" + TestContext.CurrentContext.Test.Name; } /// <summary> /// Generates next sequential ID. /// </summary> private static int NextId() { return Interlocked.Increment(ref _messageId); } } /// <summary> /// Messaging test helper class. /// </summary> [Serializable] public static class MessagingTestHelper { /** */ public static readonly ConcurrentStack<ReceivedMessage> ReceivedMessages = new ConcurrentStack<ReceivedMessage>(); /** */ private static readonly ConcurrentStack<string> Failures = new ConcurrentStack<string>(); /** */ private static readonly CountdownEvent ReceivedEvent = new CountdownEvent(0); /** */ public static volatile bool ListenResult = true; /** */ public static readonly TimeSpan MessageTimeout = TimeSpan.FromMilliseconds(5000); /** */ public static readonly TimeSpan SleepTimeout = TimeSpan.FromMilliseconds(50); /// <summary> /// Clears received message information. /// </summary> /// <param name="expectedCount">The expected count of messages to be received.</param> public static void ClearReceived(int expectedCount) { ReceivedMessages.Clear(); ReceivedEvent.Reset(expectedCount); } /// <summary> /// Verifies received messages against expected messages. /// </summary> /// <param name="cluster">Cluster.</param> /// <param name="expectedMessages">Expected messages.</param> /// <param name="resultFunc">Result transform function.</param> /// <param name="expectedRepeat">Expected repeat count.</param> public static void VerifyReceive(IClusterGroup cluster, IEnumerable<string> expectedMessages, Func<IEnumerable<string>, IEnumerable<string>> resultFunc, int expectedRepeat) { expectedMessages = expectedMessages.SelectMany(x => Enumerable.Repeat(x, expectedRepeat)).ToArray(); var expectedMessagesStr = string.Join(", ", expectedMessages); // check if expected message count has been received; Wait returns false if there were none. Assert.IsTrue(ReceivedEvent.Wait(MessageTimeout), string.Format("expectedMessages: {0}, expectedRepeat: {1}, remaining: {2}", expectedMessagesStr, expectedRepeat, ReceivedEvent.CurrentCount)); var receivedMessages = ReceivedMessages.ToArray(); var actualMessages = resultFunc(receivedMessages.Select(m => m.Message)).ToArray(); CollectionAssert.AreEqual( expectedMessages, actualMessages, string.Format("Expected messages: '{0}', actual messages: '{1}', expectedRepeat: {2}", expectedMessagesStr, string.Join(", ", receivedMessages.Select(x => x.ToString())), expectedRepeat)); // check that all messages came from local node. var localNodeId = cluster.Ignite.GetCluster().GetLocalNode().Id; Assert.AreEqual(localNodeId, ReceivedMessages.Select(m => m.NodeId).Distinct().Single()); AssertFailures(); } /// <summary> /// Gets the message listener. /// </summary> /// <returns>New instance of message listener.</returns> public static RemoteListener GetListener(string name = null) { return new RemoteListener(name); } /// <summary> /// Combines accumulated failures and throws an assertion, if there are any. /// Clears accumulated failures. /// </summary> public static void AssertFailures() { if (Failures.Any()) Assert.Fail(Failures.Reverse().Aggregate((x, y) => string.Format("{0}\n{1}", x, y))); Failures.Clear(); } /// <summary> /// Remote listener. /// </summary> public class RemoteListener : IMessageListener<string> { /** */ private readonly string _name; /** */ public RemoteListener(string name) { _name = name; } /** <inheritdoc /> */ public bool Invoke(Guid nodeId, string message) { var receivedMessage = new ReceivedMessage(message, nodeId, GetHashCode(), _name); try { ReceivedMessages.Push(receivedMessage); ReceivedEvent.Signal(); return ListenResult; } catch (Exception ex) { // When executed on remote nodes, these exceptions will not go to sender, // so we have to accumulate them. Failures.Push(string.Format("Exception in Listen (msg: {0}, id: {1}): {2}", message, nodeId, ex)); throw; } } } /// <summary> /// Received message data. /// </summary> public class ReceivedMessage { /** */ private readonly string _message; /** */ private readonly Guid _nodeId; /** */ private readonly int _listenerId; /** */ private readonly string _listenerName; /** */ public ReceivedMessage(string message, Guid nodeId, int listenerId, string listenerName) { _message = message; _nodeId = nodeId; _listenerId = listenerId; _listenerName = listenerName; } /** */ public string Message { get { return _message; } } /** */ public Guid NodeId { get { return _nodeId; } } /** <inheritdoc /> */ public override string ToString() { return string.Format( "ReceivedMessage [{0}, {1}, {2}, {3}]", _message, _nodeId, _listenerId, _listenerName); } } } /// <summary> /// Test message filter. /// </summary> [Serializable] public class MessageListener<T> : IMessageListener<T> { /** */ private readonly Func<Guid, T, bool> _invoke; #pragma warning disable 649 /** Grid. */ [InstanceResource] // ReSharper disable once UnassignedField.Local private IIgnite _grid; #pragma warning restore 649 /// <summary> /// Initializes a new instance of the <see cref="MessageListener{T}"/> class. /// </summary> /// <param name="invoke">The invoke delegate.</param> public MessageListener(Func<Guid, T, bool> invoke) { _invoke = invoke; } /** <inheritdoc /> */ public bool Invoke(Guid nodeId, T message) { Assert.IsNotNull(_grid); return _invoke(nodeId, message); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Orleans.CodeGeneration; using Orleans.Serialization; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; namespace UnitTests.Serialization { /// <summary> /// Summary description for SerializationTests /// </summary> [Collection(TestEnvironmentFixture.DefaultCollection)] public class SerializationTestsDifferentTypes { private readonly TestEnvironmentFixture fixture; public SerializationTestsDifferentTypes(TestEnvironmentFixture fixture) { this.fixture = fixture; } [Fact, TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_DateTime() { // Local Kind DateTime inputLocal = DateTime.Now; DateTime outputLocal = this.fixture.Serializer.RoundTripSerializationForTesting(inputLocal); Assert.Equal(inputLocal.ToString(CultureInfo.InvariantCulture), outputLocal.ToString(CultureInfo.InvariantCulture)); Assert.Equal(inputLocal.Kind, outputLocal.Kind); // UTC Kind DateTime inputUtc = DateTime.UtcNow; DateTime outputUtc = this.fixture.Serializer.RoundTripSerializationForTesting(inputUtc); Assert.Equal(inputUtc.ToString(CultureInfo.InvariantCulture), outputUtc.ToString(CultureInfo.InvariantCulture)); Assert.Equal(inputUtc.Kind, outputUtc.Kind); // Unspecified Kind DateTime inputUnspecified = new DateTime(0x08d27e2c0cc7dfb9); DateTime outputUnspecified = this.fixture.Serializer.RoundTripSerializationForTesting(inputUnspecified); Assert.Equal(inputUnspecified.ToString(CultureInfo.InvariantCulture), outputUnspecified.ToString(CultureInfo.InvariantCulture)); Assert.Equal(inputUnspecified.Kind, outputUnspecified.Kind); } [Fact, TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_DateTimeOffset() { // Local Kind DateTime inputLocalDateTime = DateTime.Now; DateTimeOffset inputLocal = new DateTimeOffset(inputLocalDateTime); DateTimeOffset outputLocal = this.fixture.Serializer.RoundTripSerializationForTesting(inputLocal); Assert.Equal(inputLocal, outputLocal); Assert.Equal( inputLocal.ToString(CultureInfo.InvariantCulture), outputLocal.ToString(CultureInfo.InvariantCulture)); Assert.Equal(inputLocal.DateTime.Kind, outputLocal.DateTime.Kind); // UTC Kind DateTime inputUtcDateTime = DateTime.UtcNow; DateTimeOffset inputUtc = new DateTimeOffset(inputUtcDateTime); DateTimeOffset outputUtc = this.fixture.Serializer.RoundTripSerializationForTesting(inputUtc); Assert.Equal(inputUtc, outputUtc); Assert.Equal( inputUtc.ToString(CultureInfo.InvariantCulture), outputUtc.ToString(CultureInfo.InvariantCulture)); Assert.Equal(inputUtc.DateTime.Kind, outputUtc.DateTime.Kind); // Unspecified Kind DateTime inputUnspecifiedDateTime = new DateTime(0x08d27e2c0cc7dfb9); DateTimeOffset inputUnspecified = new DateTimeOffset(inputUnspecifiedDateTime); DateTimeOffset outputUnspecified = this.fixture.Serializer.Deserialize<DateTimeOffset>(this.fixture.Serializer.SerializeToArray(inputUnspecified)); Assert.Equal(inputUnspecified, outputUnspecified); Assert.Equal( inputUnspecified.ToString(CultureInfo.InvariantCulture), outputUnspecified.ToString(CultureInfo.InvariantCulture)); Assert.Equal(inputUnspecified.DateTime.Kind, outputUnspecified.DateTime.Kind); } [Fact, TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_RecursiveSerialization() { TestTypeA input = new TestTypeA(); input.Collection = new HashSet<TestTypeA>(); input.Collection.Add(input); _ = this.fixture.Serializer.RoundTripSerializationForTesting(input); } [Fact, TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_CultureInfo() { var input = new List<CultureInfo> { CultureInfo.GetCultureInfo("en"), CultureInfo.GetCultureInfo("de") }; foreach (var cultureInfo in input) { var output = this.fixture.Serializer.RoundTripSerializationForTesting(cultureInfo); Assert.Equal(cultureInfo, output); } } [Fact, TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_CultureInfoList() { var input = new List<CultureInfo> { CultureInfo.GetCultureInfo("en"), CultureInfo.GetCultureInfo("de") }; var output = this.fixture.Serializer.RoundTripSerializationForTesting(input); Assert.True(input.SequenceEqual(output)); } [Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_ValueTuple() { var input = new List<ValueTuple<int>> { ValueTuple.Create(1), ValueTuple.Create(100) }; foreach (var valueTuple in input) { var output = this.fixture.Serializer.RoundTripSerializationForTesting(valueTuple); Assert.Equal(valueTuple, output); } } [Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_ValueTuple2() { var input = new List<ValueTuple<int, int>> { ValueTuple.Create(1, 2), ValueTuple.Create(100, 200) }; foreach (var valueTuple in input) { var output = this.fixture.Serializer.RoundTripSerializationForTesting(valueTuple); Assert.Equal(valueTuple, output); } } [Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_ValueTuple3() { var input = new List<ValueTuple<int, int, int>> { ValueTuple.Create(1, 2, 3), ValueTuple.Create(100, 200, 300) }; foreach (var valueTuple in input) { var output = this.fixture.Serializer.RoundTripSerializationForTesting(valueTuple); Assert.Equal(valueTuple, output); } } [Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_ValueTuple4() { var input = new List<ValueTuple<int, int, int, int>> { ValueTuple.Create(1, 2, 3, 4), ValueTuple.Create(100, 200, 300, 400) }; foreach (var valueTuple in input) { var output = this.fixture.Serializer.RoundTripSerializationForTesting(valueTuple); Assert.Equal(valueTuple, output); } } [Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_ValueTuple5() { var input = new List<ValueTuple<int, int, int, int, int>> { ValueTuple.Create(1, 2, 3, 4, 5), ValueTuple.Create(100, 200, 300, 400, 500) }; foreach (var valueTuple in input) { var output = this.fixture.Serializer.RoundTripSerializationForTesting(valueTuple); Assert.Equal(valueTuple, output); } } [Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_ValueTuple6() { var input = new List<ValueTuple<int, int, int, int, int, int>> { ValueTuple.Create(1, 2, 3, 4, 5, 6), ValueTuple.Create(100, 200, 300, 400, 500, 600) }; foreach (var valueTuple in input) { var output = this.fixture.Serializer.RoundTripSerializationForTesting(valueTuple); Assert.Equal(valueTuple, output); } } [Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_ValueTuple7() { var input = new List<ValueTuple<int, int, int, int, int, int, int>> { ValueTuple.Create(1, 2, 3, 4, 5, 6, 7), ValueTuple.Create(100, 200, 300, 400, 500, 600, 700) }; foreach (var valueTuple in input) { var output = this.fixture.Serializer.RoundTripSerializationForTesting(valueTuple); Assert.Equal(valueTuple, output); } } [Fact(Skip = "See https://github.com/dotnet/orleans/issues/3531"), TestCategory("BVT"), TestCategory("Serialization")] public void SerializationTests_ValueTuple8() { var valueTuple = ValueTuple.Create(1, 2, 3, 4, 5, 6, 7, 8); var output = this.fixture.Serializer.RoundTripSerializationForTesting(valueTuple); Assert.Equal(valueTuple, output); } } public static class SerializerExtensions { public static T RoundTripSerializationForTesting<T>(this Serializer serializer, T value) => serializer.Deserialize<T>(serializer.SerializeToArray(value)); } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading; using WebSocketSharp; namespace Example1 { internal class AudioStreamer : IDisposable { private Dictionary<uint, Queue> _audioBox; private Timer _heartbeatTimer; private uint? _id; private string _name; private Notifier _notifier; private WebSocket _websocket; public AudioStreamer (string url) { _websocket = new WebSocket (url); _audioBox = new Dictionary<uint, Queue> (); _heartbeatTimer = new Timer (sendHeartbeat, null, -1, -1); _id = null; _notifier = new Notifier (); configure (); } private void configure () { #if DEBUG _websocket.Log.Level = LogLevel.Trace; #endif _websocket.OnOpen += (sender, e) => _websocket.Send (createTextMessage ("connection", String.Empty)); _websocket.OnMessage += (sender, e) => { if (e.IsText) { _notifier.Notify (convertTextMessage (e.Data)); } else { var msg = convertBinaryMessage (e.RawData); if (msg.user_id == _id) return; if (_audioBox.ContainsKey (msg.user_id)) { _audioBox[msg.user_id].Enqueue (msg.buffer_array); return; } var queue = Queue.Synchronized (new Queue ()); queue.Enqueue (msg.buffer_array); _audioBox.Add (msg.user_id, queue); } }; _websocket.OnError += (sender, e) => _notifier.Notify ( new NotificationMessage { Summary = "AudioStreamer (error)", Body = e.Message, Icon = "notification-message-im" }); _websocket.OnClose += (sender, e) => _notifier.Notify ( new NotificationMessage { Summary = "AudioStreamer (disconnect)", Body = String.Format ("code: {0} reason: {1}", e.Code, e.Reason), Icon = "notification-message-im" }); } private AudioMessage convertBinaryMessage (byte[] data) { var id = data.SubArray (0, 4).To<uint> (ByteOrder.Big); var chNum = data.SubArray (4, 1)[0]; var buffLen = data.SubArray (5, 4).To<uint> (ByteOrder.Big); var buffArr = new float[chNum, buffLen]; var offset = 9; ((int) chNum).Times ( i => buffLen.Times ( j => { buffArr[i, j] = data.SubArray (offset, 4).To<float> (ByteOrder.Big); offset += 4; })); return new AudioMessage { user_id = id, ch_num = chNum, buffer_length = buffLen, buffer_array = buffArr }; } private NotificationMessage convertTextMessage (string data) { var json = JObject.Parse (data); var id = (uint) json["user_id"]; var name = (string) json["name"]; var type = (string) json["type"]; string body; if (type == "message") { body = String.Format ("{0}: {1}", name, (string) json["message"]); } else if (type == "start_music") { body = String.Format ("{0}: Started playing music!", name); } else if (type == "connection") { var users = (JArray) json["message"]; var buff = new StringBuilder ("Now keeping connections:"); foreach (JToken user in users) buff.AppendFormat ( "\n- user_id: {0} name: {1}", (uint) user["user_id"], (string) user["name"]); body = buff.ToString (); } else if (type == "connected") { _id = id; _heartbeatTimer.Change (30000, 30000); body = String.Format ("user_id: {0} name: {1}", id, name); } else { body = "Received unknown type message."; } return new NotificationMessage { Summary = String.Format ("AudioStreamer ({0})", type), Body = body, Icon = "notification-message-im" }; } private byte[] createBinaryMessage (float[,] bufferArray) { var msg = new List<byte> (); var id = (uint) _id; var chNum = bufferArray.GetLength (0); var buffLen = bufferArray.GetLength (1); msg.AddRange (id.ToByteArray (ByteOrder.Big)); msg.Add ((byte) chNum); msg.AddRange (((uint) buffLen).ToByteArray (ByteOrder.Big)); chNum.Times ( i => buffLen.Times ( j => msg.AddRange (bufferArray[i, j].ToByteArray (ByteOrder.Big)))); return msg.ToArray (); } private string createTextMessage (string type, string message) { return JsonConvert.SerializeObject ( new TextMessage { user_id = _id, name = _name, type = type, message = message }); } private void sendHeartbeat (object state) { _websocket.Send (createTextMessage ("heartbeat", String.Empty)); } public void Connect (string username) { _name = username; _websocket.Connect (); } public void Disconnect () { _heartbeatTimer.Change (-1, -1); _websocket.Close (CloseStatusCode.Away); _audioBox.Clear (); _id = null; _name = null; } public void Write (string message) { _websocket.Send (createTextMessage ("message", message)); } void IDisposable.Dispose () { Disconnect (); _heartbeatTimer.Dispose (); _notifier.Close (); } } }
/* * 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 rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RDS.Model { /// <summary> /// This data type is used as a request parameter in the <a>ModifyDBParameterGroup</a> /// and <a>ResetDBParameterGroup</a> actions. /// /// /// <para> /// This data type is used as a response element in the <a>DescribeEngineDefaultParameters</a> /// and <a>DescribeDBParameters</a> actions. /// </para> /// </summary> public partial class Parameter { private string _allowedValues; private ApplyMethod _applyMethod; private string _applyType; private string _dataType; private string _description; private bool? _isModifiable; private string _minimumEngineVersion; private string _parameterName; private string _parameterValue; private string _source; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public Parameter() { } /// <summary> /// Gets and sets the property AllowedValues. /// <para> /// Specifies the valid range of values for the parameter. /// </para> /// </summary> public string AllowedValues { get { return this._allowedValues; } set { this._allowedValues = value; } } // Check to see if AllowedValues property is set internal bool IsSetAllowedValues() { return this._allowedValues != null; } /// <summary> /// Gets and sets the property ApplyMethod. /// <para> /// Indicates when to apply parameter updates. /// </para> /// </summary> public ApplyMethod ApplyMethod { get { return this._applyMethod; } set { this._applyMethod = value; } } // Check to see if ApplyMethod property is set internal bool IsSetApplyMethod() { return this._applyMethod != null; } /// <summary> /// Gets and sets the property ApplyType. /// <para> /// Specifies the engine specific parameters type. /// </para> /// </summary> public string ApplyType { get { return this._applyType; } set { this._applyType = value; } } // Check to see if ApplyType property is set internal bool IsSetApplyType() { return this._applyType != null; } /// <summary> /// Gets and sets the property DataType. /// <para> /// Specifies the valid data type for the parameter. /// </para> /// </summary> public string DataType { get { return this._dataType; } set { this._dataType = value; } } // Check to see if DataType property is set internal bool IsSetDataType() { return this._dataType != null; } /// <summary> /// Gets and sets the property Description. /// <para> /// Provides a description of the parameter. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property IsModifiable. /// <para> /// Indicates whether (<code>true</code>) or not (<code>false</code>) the parameter can /// be modified. Some parameters have security or operational implications that prevent /// them from being changed. /// </para> /// </summary> public bool IsModifiable { get { return this._isModifiable.GetValueOrDefault(); } set { this._isModifiable = value; } } // Check to see if IsModifiable property is set internal bool IsSetIsModifiable() { return this._isModifiable.HasValue; } /// <summary> /// Gets and sets the property MinimumEngineVersion. /// <para> /// The earliest engine version to which the parameter can apply. /// </para> /// </summary> public string MinimumEngineVersion { get { return this._minimumEngineVersion; } set { this._minimumEngineVersion = value; } } // Check to see if MinimumEngineVersion property is set internal bool IsSetMinimumEngineVersion() { return this._minimumEngineVersion != null; } /// <summary> /// Gets and sets the property ParameterName. /// <para> /// Specifies the name of the parameter. /// </para> /// </summary> public string ParameterName { get { return this._parameterName; } set { this._parameterName = value; } } // Check to see if ParameterName property is set internal bool IsSetParameterName() { return this._parameterName != null; } /// <summary> /// Gets and sets the property ParameterValue. /// <para> /// Specifies the value of the parameter. /// </para> /// </summary> public string ParameterValue { get { return this._parameterValue; } set { this._parameterValue = value; } } // Check to see if ParameterValue property is set internal bool IsSetParameterValue() { return this._parameterValue != null; } /// <summary> /// Gets and sets the property Source. /// <para> /// Indicates the source of the parameter value. /// </para> /// </summary> public string Source { get { return this._source; } set { this._source = value; } } // Check to see if Source property is set internal bool IsSetSource() { return this._source != null; } } }
using System.Diagnostics.CodeAnalysis; using UnityEngine; namespace Assets.InputMapper.Devices { /// <summary> /// Defines available keys on a keyboard device. /// </summary> [SuppressMessage("ReSharper", "UnusedMember.Global")] public enum KeyboardKey { // NOTE taken from Unity, inappropriate values commented out //None = KeyCode.None, Backspace = KeyCode.Backspace, Tab = KeyCode.Tab, Clear = KeyCode.Clear, Return = KeyCode.Return, Pause = KeyCode.Pause, Escape = KeyCode.Escape, Space = KeyCode.Space, Exclaim = KeyCode.Exclaim, DoubleQuote = KeyCode.DoubleQuote, Hash = KeyCode.Hash, Dollar = KeyCode.Dollar, Ampersand = KeyCode.Ampersand, Quote = KeyCode.Quote, LeftParen = KeyCode.LeftParen, RightParen = KeyCode.RightParen, Asterisk = KeyCode.Asterisk, Plus = KeyCode.Plus, Comma = KeyCode.Comma, Minus = KeyCode.Minus, Period = KeyCode.Period, Slash = KeyCode.Slash, Alpha0 = KeyCode.Alpha0, Alpha1 = KeyCode.Alpha1, Alpha2 = KeyCode.Alpha2, Alpha3 = KeyCode.Alpha3, Alpha4 = KeyCode.Alpha4, Alpha5 = KeyCode.Alpha5, Alpha6 = KeyCode.Alpha6, Alpha7 = KeyCode.Alpha7, Alpha8 = KeyCode.Alpha8, Alpha9 = KeyCode.Alpha9, Colon = KeyCode.Colon, Semicolon = KeyCode.Semicolon, Less = KeyCode.Less, Equals = KeyCode.Equals, Greater = KeyCode.Greater, Question = KeyCode.Question, At = KeyCode.At, LeftBracket = KeyCode.LeftBracket, Backslash = KeyCode.Backslash, RightBracket = KeyCode.RightBracket, Caret = KeyCode.Caret, Underscore = KeyCode.Underscore, BackQuote = KeyCode.BackQuote, A = KeyCode.A, B = KeyCode.B, C = KeyCode.C, D = KeyCode.D, E = KeyCode.E, F = KeyCode.F, G = KeyCode.G, H = KeyCode.H, I = KeyCode.I, J = KeyCode.J, K = KeyCode.K, L = KeyCode.L, M = KeyCode.M, N = KeyCode.N, O = KeyCode.O, P = KeyCode.P, Q = KeyCode.Q, R = KeyCode.R, S = KeyCode.S, T = KeyCode.T, U = KeyCode.U, V = KeyCode.V, W = KeyCode.W, X = KeyCode.X, Y = KeyCode.Y, Z = KeyCode.Z, Delete = KeyCode.Delete, Keypad0 = KeyCode.Keypad0, Keypad1 = KeyCode.Keypad1, Keypad2 = KeyCode.Keypad2, Keypad3 = KeyCode.Keypad3, Keypad4 = KeyCode.Keypad4, Keypad5 = KeyCode.Keypad5, Keypad6 = KeyCode.Keypad6, Keypad7 = KeyCode.Keypad7, Keypad8 = KeyCode.Keypad8, Keypad9 = KeyCode.Keypad9, KeypadPeriod = KeyCode.KeypadPeriod, KeypadDivide = KeyCode.KeypadDivide, KeypadMultiply = KeyCode.KeypadMultiply, KeypadMinus = KeyCode.KeypadMinus, KeypadPlus = KeyCode.KeypadPlus, KeypadEnter = KeyCode.KeypadEnter, KeypadEquals = KeyCode.KeypadEquals, UpArrow = KeyCode.UpArrow, DownArrow = KeyCode.DownArrow, RightArrow = KeyCode.RightArrow, LeftArrow = KeyCode.LeftArrow, Insert = KeyCode.Insert, Home = KeyCode.Home, End = KeyCode.End, PageUp = KeyCode.PageUp, PageDown = KeyCode.PageDown, F1 = KeyCode.F1, F2 = KeyCode.F2, F3 = KeyCode.F3, F4 = KeyCode.F4, F5 = KeyCode.F5, F6 = KeyCode.F6, F7 = KeyCode.F7, F8 = KeyCode.F8, F9 = KeyCode.F9, F10 = KeyCode.F10, F11 = KeyCode.F11, F12 = KeyCode.F12, F13 = KeyCode.F13, F14 = KeyCode.F14, F15 = KeyCode.F15, Numlock = KeyCode.Numlock, CapsLock = KeyCode.CapsLock, ScrollLock = KeyCode.ScrollLock, RightShift = KeyCode.RightShift, LeftShift = KeyCode.LeftShift, RightControl = KeyCode.RightControl, LeftControl = KeyCode.LeftControl, RightAlt = KeyCode.RightAlt, LeftAlt = KeyCode.LeftAlt, RightApple = KeyCode.RightApple, RightCommand = KeyCode.RightCommand, LeftApple = KeyCode.LeftApple, LeftCommand = KeyCode.LeftCommand, LeftWindows = KeyCode.LeftWindows, RightWindows = KeyCode.RightWindows, AltGr = KeyCode.AltGr, Help = KeyCode.Help, Print = KeyCode.Print, SysReq = KeyCode.SysReq, Break = KeyCode.Break, Menu = KeyCode.Menu //Mouse0 = KeyCode.Mouse0, //Mouse1 = KeyCode.Mouse1, //Mouse2 = KeyCode.Mouse2, //Mouse3 = KeyCode.Mouse3, //Mouse4 = KeyCode.Mouse4, //Mouse5 = KeyCode.Mouse5, //Mouse6 = KeyCode.Mouse6, //JoystickButton0 = KeyCode.JoystickButton0, //JoystickButton1 = KeyCode.JoystickButton1, //JoystickButton2 = KeyCode.JoystickButton2, //JoystickButton3 = KeyCode.JoystickButton3, //JoystickButton4 = KeyCode.JoystickButton4, //JoystickButton5 = KeyCode.JoystickButton5, //JoystickButton6 = KeyCode.JoystickButton6, //JoystickButton7 = KeyCode.JoystickButton7, //JoystickButton8 = KeyCode.JoystickButton8, //JoystickButton9 = KeyCode.JoystickButton9, //JoystickButton10 = KeyCode.JoystickButton10, //JoystickButton11 = KeyCode.JoystickButton11, //JoystickButton12 = KeyCode.JoystickButton12, //JoystickButton13 = KeyCode.JoystickButton13, //JoystickButton14 = KeyCode.JoystickButton14, //JoystickButton15 = KeyCode.JoystickButton15, //JoystickButton16 = KeyCode.JoystickButton16, //JoystickButton17 = KeyCode.JoystickButton17, //JoystickButton18 = KeyCode.JoystickButton18, //JoystickButton19 = KeyCode.JoystickButton19, //Joystick1Button0 = KeyCode.Joystick1Button0, //Joystick1Button1 = KeyCode.Joystick1Button1, //Joystick1Button2 = KeyCode.Joystick1Button2, //Joystick1Button3 = KeyCode.Joystick1Button3, //Joystick1Button4 = KeyCode.Joystick1Button4, //Joystick1Button5 = KeyCode.Joystick1Button5, //Joystick1Button6 = KeyCode.Joystick1Button6, //Joystick1Button7 = KeyCode.Joystick1Button7, //Joystick1Button8 = KeyCode.Joystick1Button8, //Joystick1Button9 = KeyCode.Joystick1Button9, //Joystick1Button10 = KeyCode.Joystick1Button10, //Joystick1Button11 = KeyCode.Joystick1Button11, //Joystick1Button12 = KeyCode.Joystick1Button12, //Joystick1Button13 = KeyCode.Joystick1Button13, //Joystick1Button14 = KeyCode.Joystick1Button14, //Joystick1Button15 = KeyCode.Joystick1Button15, //Joystick1Button16 = KeyCode.Joystick1Button16, //Joystick1Button17 = KeyCode.Joystick1Button17, //Joystick1Button18 = KeyCode.Joystick1Button18, //Joystick1Button19 = KeyCode.Joystick1Button19, //Joystick2Button0 = KeyCode.Joystick2Button0, //Joystick2Button1 = KeyCode.Joystick2Button1, //Joystick2Button2 = KeyCode.Joystick2Button2, //Joystick2Button3 = KeyCode.Joystick2Button3, //Joystick2Button4 = KeyCode.Joystick2Button4, //Joystick2Button5 = KeyCode.Joystick2Button5, //Joystick2Button6 = KeyCode.Joystick2Button6, //Joystick2Button7 = KeyCode.Joystick2Button7, //Joystick2Button8 = KeyCode.Joystick2Button8, //Joystick2Button9 = KeyCode.Joystick2Button9, //Joystick2Button10 = KeyCode.Joystick2Button10, //Joystick2Button11 = KeyCode.Joystick2Button11, //Joystick2Button12 = KeyCode.Joystick2Button12, //Joystick2Button13 = KeyCode.Joystick2Button13, //Joystick2Button14 = KeyCode.Joystick2Button14, //Joystick2Button15 = KeyCode.Joystick2Button15, //Joystick2Button16 = KeyCode.Joystick2Button16, //Joystick2Button17 = KeyCode.Joystick2Button17, //Joystick2Button18 = KeyCode.Joystick2Button18, //Joystick2Button19 = KeyCode.Joystick2Button19, //Joystick3Button0 = KeyCode.Joystick3Button0, //Joystick3Button1 = KeyCode.Joystick3Button1, //Joystick3Button2 = KeyCode.Joystick3Button2, //Joystick3Button3 = KeyCode.Joystick3Button3, //Joystick3Button4 = KeyCode.Joystick3Button4, //Joystick3Button5 = KeyCode.Joystick3Button5, //Joystick3Button6 = KeyCode.Joystick3Button6, //Joystick3Button7 = KeyCode.Joystick3Button7, //Joystick3Button8 = KeyCode.Joystick3Button8, //Joystick3Button9 = KeyCode.Joystick3Button9, //Joystick3Button10 = KeyCode.Joystick3Button10, //Joystick3Button11 = KeyCode.Joystick3Button11, //Joystick3Button12 = KeyCode.Joystick3Button12, //Joystick3Button13 = KeyCode.Joystick3Button13, //Joystick3Button14 = KeyCode.Joystick3Button14, //Joystick3Button15 = KeyCode.Joystick3Button15, //Joystick3Button16 = KeyCode.Joystick3Button16, //Joystick3Button17 = KeyCode.Joystick3Button17, //Joystick3Button18 = KeyCode.Joystick3Button18, //Joystick3Button19 = KeyCode.Joystick3Button19, //Joystick4Button0 = KeyCode.Joystick4Button0, //Joystick4Button1 = KeyCode.Joystick4Button1, //Joystick4Button2 = KeyCode.Joystick4Button2, //Joystick4Button3 = KeyCode.Joystick4Button3, //Joystick4Button4 = KeyCode.Joystick4Button4, //Joystick4Button5 = KeyCode.Joystick4Button5, //Joystick4Button6 = KeyCode.Joystick4Button6, //Joystick4Button7 = KeyCode.Joystick4Button7, //Joystick4Button8 = KeyCode.Joystick4Button8, //Joystick4Button9 = KeyCode.Joystick4Button9, //Joystick4Button10 = KeyCode.Joystick4Button10, //Joystick4Button11 = KeyCode.Joystick4Button11, //Joystick4Button12 = KeyCode.Joystick4Button12, //Joystick4Button13 = KeyCode.Joystick4Button13, //Joystick4Button14 = KeyCode.Joystick4Button14, //Joystick4Button15 = KeyCode.Joystick4Button15, //Joystick4Button16 = KeyCode.Joystick4Button16, //Joystick4Button17 = KeyCode.Joystick4Button17, //Joystick4Button18 = KeyCode.Joystick4Button18, //Joystick4Button19 = KeyCode.Joystick4Button19, //Joystick5Button0 = KeyCode.Joystick5Button0, //Joystick5Button1 = KeyCode.Joystick5Button1, //Joystick5Button2 = KeyCode.Joystick5Button2, //Joystick5Button3 = KeyCode.Joystick5Button3, //Joystick5Button4 = KeyCode.Joystick5Button4, //Joystick5Button5 = KeyCode.Joystick5Button5, //Joystick5Button6 = KeyCode.Joystick5Button6, //Joystick5Button7 = KeyCode.Joystick5Button7, //Joystick5Button8 = KeyCode.Joystick5Button8, //Joystick5Button9 = KeyCode.Joystick5Button9, //Joystick5Button10 = KeyCode.Joystick5Button10, //Joystick5Button11 = KeyCode.Joystick5Button11, //Joystick5Button12 = KeyCode.Joystick5Button12, //Joystick5Button13 = KeyCode.Joystick5Button13, //Joystick5Button14 = KeyCode.Joystick5Button14, //Joystick5Button15 = KeyCode.Joystick5Button15, //Joystick5Button16 = KeyCode.Joystick5Button16, //Joystick5Button17 = KeyCode.Joystick5Button17, //Joystick5Button18 = KeyCode.Joystick5Button18, //Joystick5Button19 = KeyCode.Joystick5Button19, //Joystick6Button0 = KeyCode.Joystick6Button0, //Joystick6Button1 = KeyCode.Joystick6Button1, //Joystick6Button2 = KeyCode.Joystick6Button2, //Joystick6Button3 = KeyCode.Joystick6Button3, //Joystick6Button4 = KeyCode.Joystick6Button4, //Joystick6Button5 = KeyCode.Joystick6Button5, //Joystick6Button6 = KeyCode.Joystick6Button6, //Joystick6Button7 = KeyCode.Joystick6Button7, //Joystick6Button8 = KeyCode.Joystick6Button8, //Joystick6Button9 = KeyCode.Joystick6Button9, //Joystick6Button10 = KeyCode.Joystick6Button10, //Joystick6Button11 = KeyCode.Joystick6Button11, //Joystick6Button12 = KeyCode.Joystick6Button12, //Joystick6Button13 = KeyCode.Joystick6Button13, //Joystick6Button14 = KeyCode.Joystick6Button14, //Joystick6Button15 = KeyCode.Joystick6Button15, //Joystick6Button16 = KeyCode.Joystick6Button16, //Joystick6Button17 = KeyCode.Joystick6Button17, //Joystick6Button18 = KeyCode.Joystick6Button18, //Joystick6Button19 = KeyCode.Joystick6Button19, //Joystick7Button0 = KeyCode.Joystick7Button0, //Joystick7Button1 = KeyCode.Joystick7Button1, //Joystick7Button2 = KeyCode.Joystick7Button2, //Joystick7Button3 = KeyCode.Joystick7Button3, //Joystick7Button4 = KeyCode.Joystick7Button4, //Joystick7Button5 = KeyCode.Joystick7Button5, //Joystick7Button6 = KeyCode.Joystick7Button6, //Joystick7Button7 = KeyCode.Joystick7Button7, //Joystick7Button8 = KeyCode.Joystick7Button8, //Joystick7Button9 = KeyCode.Joystick7Button9, //Joystick7Button10 = KeyCode.Joystick7Button10, //Joystick7Button11 = KeyCode.Joystick7Button11, //Joystick7Button12 = KeyCode.Joystick7Button12, //Joystick7Button13 = KeyCode.Joystick7Button13, //Joystick7Button14 = KeyCode.Joystick7Button14, //Joystick7Button15 = KeyCode.Joystick7Button15, //Joystick7Button16 = KeyCode.Joystick7Button16, //Joystick7Button17 = KeyCode.Joystick7Button17, //Joystick7Button18 = KeyCode.Joystick7Button18, //Joystick7Button19 = KeyCode.Joystick7Button19, //Joystick8Button0 = KeyCode.Joystick8Button0, //Joystick8Button1 = KeyCode.Joystick8Button1, //Joystick8Button2 = KeyCode.Joystick8Button2, //Joystick8Button3 = KeyCode.Joystick8Button3, //Joystick8Button4 = KeyCode.Joystick8Button4, //Joystick8Button5 = KeyCode.Joystick8Button5, //Joystick8Button6 = KeyCode.Joystick8Button6, //Joystick8Button7 = KeyCode.Joystick8Button7, //Joystick8Button8 = KeyCode.Joystick8Button8, //Joystick8Button9 = KeyCode.Joystick8Button9, //Joystick8Button10 = KeyCode.Joystick8Button10, //Joystick8Button11 = KeyCode.Joystick8Button11, //Joystick8Button12 = KeyCode.Joystick8Button12, //Joystick8Button13 = KeyCode.Joystick8Button13, //Joystick8Button14 = KeyCode.Joystick8Button14, //Joystick8Button15 = KeyCode.Joystick8Button15, //Joystick8Button16 = KeyCode.Joystick8Button16, //Joystick8Button17 = KeyCode.Joystick8Button17, //Joystick8Button18 = KeyCode.Joystick8Button18, //Joystick8Button19 = KeyCode.Joystick8Button19 } }
// // System.Net.ListenerAsyncResult // // Authors: // Gonzalo Paniagua Javier (gonzalo@ximian.com) // // Copyright (c) 2005 Ximian, Inc (http://www.ximian.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Threading; namespace Reactor.Net { class ListenerAsyncResult : IAsyncResult { private ManualResetEvent handle; private bool synch; private bool completed; private AsyncCallback cb; private object state; private Exception exception; private HttpListenerContext context; private object locker = new object(); private ListenerAsyncResult forward; internal bool EndCalled; internal bool InGet; public ListenerAsyncResult(AsyncCallback cb, object state) { this.cb = cb; this.state = state; } internal void Complete(Exception exc) { if (forward != null) { forward.Complete(exc); return; } exception = exc; if (InGet && (exc is ObjectDisposedException)) { exception = new HttpListenerException(500, "Listener closed"); } lock (locker) { completed = true; if (handle != null) { handle.Set(); } if (cb != null) { ThreadPool.UnsafeQueueUserWorkItem(InvokeCB, this); } } } static WaitCallback InvokeCB = new WaitCallback(InvokeCallback); static void InvokeCallback(object o) { ListenerAsyncResult ares = (ListenerAsyncResult)o; if (ares.forward != null) { InvokeCallback(ares.forward); return; } try { ares.cb(ares); } catch { } } internal void Complete(HttpListenerContext context) { Complete(context, false); } internal void Complete(HttpListenerContext context, bool synch) { if (forward != null) { forward.Complete(context, synch); return; } this.synch = synch; this.context = context; lock (locker) { AuthenticationSchemes schemes = context.Listener.SelectAuthenticationScheme(context); if ((schemes == AuthenticationSchemes.Basic || context.Listener.AuthenticationSchemes == AuthenticationSchemes.Negotiate) && context.Request.Headers["Authorization"] == null) { context.Response.StatusCode = 401; context.Response.Headers["WWW-Authenticate"] = schemes + " realm=\"" + context.Listener.Realm + "\""; context.Response.OutputStream.Close(); IAsyncResult ares = context.Listener.BeginGetContext(cb, state); this.forward = (ListenerAsyncResult)ares; lock (forward.locker) { if (handle != null) { forward.handle = handle; } } ListenerAsyncResult next = forward; for (int i = 0; next.forward != null; i++) { if (i > 20) { Complete(new HttpListenerException(400, "Too many authentication errors")); } next = next.forward; } } else { completed = true; this.synch = false; if (handle != null) { handle.Set(); } if (cb != null) { ThreadPool.UnsafeQueueUserWorkItem(InvokeCB, this); } } } } internal HttpListenerContext GetContext() { if (forward != null) { return forward.GetContext(); } if (exception != null) { throw exception; } return context; } public object AsyncState { get { if (forward != null) { return forward.AsyncState; } return state; } } public WaitHandle AsyncWaitHandle { get { if (forward != null) { return forward.AsyncWaitHandle; } lock (locker) { if (handle == null) { handle = new ManualResetEvent(completed); } } return handle; } } public bool CompletedSynchronously { get { if (forward != null) { return forward.CompletedSynchronously; } return synch; } } public bool IsCompleted { get { if (forward != null) { return forward.IsCompleted; } lock (locker) { return completed; } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Threading; using System.Transactions; using log4net; using Rhino.Queues.Internal; using Rhino.Queues.Model; using Rhino.Queues.Protocol; using Rhino.Queues.Storage; using System.Linq; namespace Rhino.Queues { using Exceptions; using Utils; public class QueueManager : IQueueManager { [ThreadStatic] private static TransactionEnlistment Enlistment; [ThreadStatic] private static Transaction CurrentlyEnslistedTransaction; private volatile bool wasDisposed; private volatile int currentlyInCriticalReceiveStatus; private volatile int currentlyInsideTransaction; private readonly IPEndPoint endpoint; private readonly object newMessageArrivedLock = new object(); private readonly string path; private readonly Timer purgeOldDataTimer; private readonly QueueStorage queueStorage; private readonly Receiver receiver; private readonly Thread sendingThread; private readonly QueuedMessagesSender queuedMessagesSender; private readonly ILog logger = LogManager.GetLogger(typeof(QueueManager)); private volatile bool waitingForAllMessagesToBeSent; private readonly ThreadSafeSet<MessageId> receivedMsgs = new ThreadSafeSet<MessageId>(); private bool disposing; public int NumberOfReceivedMessagesToKeep { get; set; } public int? NumberOfMessagesToKeepInProcessedQueues { get; set; } public int? NumberOfMessagesToKeepOutgoingQueues { get; set; } public TimeSpan? OldestMessageInProcessedQueues { get; set; } public TimeSpan? OldestMessageInOutgoingQueues { get; set; } public event Action<Endpoint> FailedToSendMessagesTo; public QueueManager(IPEndPoint endpoint, string path) { NumberOfMessagesToKeepInProcessedQueues = 100; NumberOfMessagesToKeepOutgoingQueues = 100; NumberOfReceivedMessagesToKeep = 100000; OldestMessageInProcessedQueues = TimeSpan.FromDays(3); OldestMessageInOutgoingQueues = TimeSpan.FromDays(3); this.endpoint = endpoint; this.path = path; queueStorage = new QueueStorage(path); queueStorage.Initialize(); queueStorage.Global(actions => { receivedMsgs.Add(actions.GetAlreadyReceivedMessageIds()); actions.Commit(); }); receiver = new Receiver(endpoint, AcceptMessages); receiver.Start(); HandleRecovery(); queuedMessagesSender = new QueuedMessagesSender(queueStorage, this); sendingThread = new Thread(queuedMessagesSender.Send) { IsBackground = true, Name = "Rhino Queue Sender Thread for " + path }; sendingThread.Start(); purgeOldDataTimer = new Timer(PurgeOldData, null, TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(3)); } private void PurgeOldData(object ignored) { logger.DebugFormat("Starting to purge old data"); try { queueStorage.Global(actions => { foreach (var queue in Queues) { var queueActions = actions.GetQueue(queue); var messages = queueActions.GetAllProcessedMessages(); if (NumberOfMessagesToKeepInProcessedQueues != null) messages = messages.Skip(NumberOfMessagesToKeepInProcessedQueues.Value); if (OldestMessageInProcessedQueues != null) messages = messages.Where(x => (DateTime.Now - x.SentAt) > OldestMessageInProcessedQueues.Value); foreach (var message in messages) { logger.DebugFormat("Purging message {0} from queue {0}/{1}", message.Id, message.Queue, message.SubQueue); queueActions.DeleteHistoric(message.Bookmark); } } var sentMessages = actions.GetSentMessages(); if (NumberOfMessagesToKeepOutgoingQueues != null) sentMessages = sentMessages.Skip(NumberOfMessagesToKeepOutgoingQueues.Value); if (OldestMessageInOutgoingQueues != null) sentMessages = sentMessages.Where(x => (DateTime.Now - x.SentAt) > OldestMessageInOutgoingQueues.Value); foreach (var sentMessage in sentMessages) { logger.DebugFormat("Purging sent message {0} to {1}/{2}/{3}", sentMessage.Id, sentMessage.Endpoint, sentMessage.Queue, sentMessage.SubQueue); actions.DeleteMessageToSendHistoric(sentMessage.Bookmark); } receivedMsgs.Remove(actions.DeleteOldestReceivedMessages(NumberOfReceivedMessagesToKeep)); actions.Commit(); }); } catch (Exception exception) { logger.Warn("Failed to purge old data from the system", exception); } } private void HandleRecovery() { var recoveryRequired = false; queueStorage.Global(actions => { actions.MarkAllOutgoingInFlightMessagesAsReadyToSend(); actions.MarkAllProcessedMessagesWithTransactionsNotRegisterForRecoveryAsReadyToDeliver(); foreach (var bytes in actions.GetRecoveryInformation()) { recoveryRequired = true; TransactionManager.Reenlist(queueStorage.Id, bytes, new TransactionEnlistment(queueStorage, () => { }, () => { })); } actions.Commit(); }); if (recoveryRequired) TransactionManager.RecoveryComplete(queueStorage.Id); } public string Path { get { return path; } } public IPEndPoint Endpoint { get { return endpoint; } } #region IDisposable Members public void Dispose() { if (wasDisposed) return; DisposeResourcesWhoseDisposalCannotFail(); queueStorage.Dispose(); // only after we finish incoming recieves, and finish processing // active transactions can we mark it as disposed wasDisposed = true; } public void DisposeRudely() { if (wasDisposed) return; DisposeResourcesWhoseDisposalCannotFail(); queueStorage.DisposeRudely(); // only after we finish incoming recieves, and finish processing // active transactions can we mark it as disposed wasDisposed = true; } private void DisposeResourcesWhoseDisposalCannotFail() { disposing = true; lock (newMessageArrivedLock) { Monitor.PulseAll(newMessageArrivedLock); } purgeOldDataTimer.Dispose(); queuedMessagesSender.Stop(); sendingThread.Join(); receiver.Dispose(); while (currentlyInCriticalReceiveStatus > 0) { logger.WarnFormat("Waiting for {0} messages that are currently in critical receive status", currentlyInCriticalReceiveStatus); Thread.Sleep(TimeSpan.FromSeconds(1)); } while (currentlyInsideTransaction > 0) { logger.WarnFormat("Waiting for {0} transactions currently running", currentlyInsideTransaction); Thread.Sleep(TimeSpan.FromSeconds(1)); } } #endregion private void AssertNotDisposed() { if (wasDisposed) throw new ObjectDisposedException("QueueManager"); } private void AssertNotDisposedOrDisposing() { if (disposing || wasDisposed) throw new ObjectDisposedException("QueueManager"); } public void WaitForAllMessagesToBeSent() { waitingForAllMessagesToBeSent = true; try { var hasMessagesToSend = true; do { queueStorage.Send(actions => { hasMessagesToSend = actions.HasMessagesToSend(); actions.Commit(); }); if (hasMessagesToSend) Thread.Sleep(100); } while (hasMessagesToSend); } finally { waitingForAllMessagesToBeSent = false; } } public IQueue GetQueue(string queue) { return new Queue(this, queue); } public PersistentMessage[] GetAllMessages(string queueName, string subqueue) { AssertNotDisposedOrDisposing(); PersistentMessage[] messages = null; queueStorage.Global(actions => { messages = actions.GetQueue(queueName).GetAllMessages(subqueue).ToArray(); actions.Commit(); }); return messages; } public HistoryMessage[] GetAllProcessedMessages(string queueName) { AssertNotDisposedOrDisposing(); HistoryMessage[] messages = null; queueStorage.Global(actions => { messages = actions.GetQueue(queueName).GetAllProcessedMessages().ToArray(); actions.Commit(); }); return messages; } public PersistentMessageToSend[] GetAllSentMessages() { AssertNotDisposedOrDisposing(); PersistentMessageToSend[] msgs = null; queueStorage.Global(actions => { msgs = actions.GetSentMessages().ToArray(); actions.Commit(); }); return msgs; } public PersistentMessageToSend[] GetMessagesCurrentlySending() { AssertNotDisposedOrDisposing(); PersistentMessageToSend[] msgs = null; queueStorage.Send(actions => { msgs = actions.GetMessagesToSend().ToArray(); actions.Commit(); }); return msgs; } public Message Peek(string queueName) { return Peek(queueName, null, TimeSpan.FromDays(1)); } public Message Peek(string queueName, TimeSpan timeout) { return Peek(queueName, null, timeout); } public Message Peek(string queueName, string subqueue) { return Peek(queueName, subqueue, TimeSpan.FromDays(1)); } public Message Peek(string queueName, string subqueue, TimeSpan timeout) { var remaining = timeout; while (true) { var message = PeekMessageFromQueue(queueName, subqueue); if (message != null) return message; lock (newMessageArrivedLock) { message = PeekMessageFromQueue(queueName, subqueue); if (message != null) return message; var sp = Stopwatch.StartNew(); if (Monitor.Wait(newMessageArrivedLock, remaining) == false) throw new TimeoutException("No message arrived in the specified timeframe " + timeout); remaining = Max(TimeSpan.Zero, remaining - sp.Elapsed); } } } private static TimeSpan Max(TimeSpan x, TimeSpan y) { return x >= y ? x : y; } public Message Receive(string queueName) { return Receive(queueName, null, TimeSpan.FromDays(1)); } public Message Receive(string queueName, TimeSpan timeout) { return Receive(queueName, null, timeout); } public Message Receive(string queueName, string subqueue) { return Receive(queueName, subqueue, TimeSpan.FromDays(1)); } public Message Receive(string queueName, string subqueue, TimeSpan timeout) { EnsureEnslistment(); var remaining = timeout; while (true) { var message = GetMessageFromQueue(queueName, subqueue); if (message != null) return message; lock (newMessageArrivedLock) { message = GetMessageFromQueue(queueName, subqueue); if (message != null) return message; var sp = Stopwatch.StartNew(); if (Monitor.Wait(newMessageArrivedLock, remaining) == false) throw new TimeoutException("No message arrived in the specified timeframe " + timeout); remaining = remaining - sp.Elapsed; } } } public MessageId Send(Uri uri, MessagePayload payload) { if (waitingForAllMessagesToBeSent) throw new CannotSendWhileWaitingForAllMessagesToBeSentException("Currently waiting for all messages to be sent, so we cannot send. You probably have a race condition in your application."); EnsureEnslistment(); var parts = uri.AbsolutePath.Substring(1).Split('/'); var queue = parts[0]; string subqueue = null; if (parts.Length > 1) { subqueue = string.Join("/", parts.Skip(1).ToArray()); } Guid msgId = Guid.Empty; queueStorage.Global(actions => { var port = uri.Port; if (port == -1) port = 2200; msgId = actions.RegisterToSend(new Endpoint(uri.Host, port), queue, subqueue, payload, Enlistment.Id); actions.Commit(); }); return new MessageId { SourceInstanceId = queueStorage.Id, MessageIdentifier = msgId }; } private void EnsureEnslistment() { AssertNotDisposedOrDisposing(); if (Transaction.Current == null) throw new InvalidOperationException("You must use TransactionScope when using Rhino.Queues"); if (CurrentlyEnslistedTransaction == Transaction.Current) return; // need to change the enslitment #pragma warning disable 420 Interlocked.Increment(ref currentlyInsideTransaction); #pragma warning restore 420 Enlistment = new TransactionEnlistment(queueStorage, () => { lock (newMessageArrivedLock) { Monitor.PulseAll(newMessageArrivedLock); } #pragma warning disable 420 Interlocked.Decrement(ref currentlyInsideTransaction); #pragma warning restore 420 }, AssertNotDisposed); CurrentlyEnslistedTransaction = Transaction.Current; } private PersistentMessage GetMessageFromQueue(string queueName, string subqueue) { AssertNotDisposedOrDisposing(); PersistentMessage message = null; queueStorage.Global(actions => { message = actions.GetQueue(queueName).Dequeue(subqueue); if (message != null) { actions.RegisterUpdateToReverse( Enlistment.Id, message.Bookmark, MessageStatus.ReadyToDeliver, subqueue); } actions.Commit(); }); return message; } private PersistentMessage PeekMessageFromQueue(string queueName, string subqueue) { AssertNotDisposedOrDisposing(); PersistentMessage message = null; queueStorage.Global(actions => { message = actions.GetQueue(queueName).Peek(subqueue); actions.Commit(); }); if (message != null) { logger.DebugFormat("Peeked message with id '{0}' from '{1}/{2}'", message.Id, queueName, subqueue); } return message; } private IMessageAcceptance AcceptMessages(Message[] msgs) { var bookmarks = new List<MessageBookmark>(); queueStorage.Global(actions => { foreach (var msg in receivedMsgs.Filter(msgs, message => message.Id)) { var queue = actions.GetQueue(msg.Queue); var bookmark = queue.Enqueue(msg); bookmarks.Add(bookmark); } actions.Commit(); }); var msgIds = msgs.Select(m => m.Id).ToArray(); return new MessageAcceptance(this, bookmarks, msgIds, queueStorage); } #region Nested type: MessageAcceptance private class MessageAcceptance : IMessageAcceptance { private readonly IList<MessageBookmark> bookmarks; private readonly IEnumerable<MessageId> messageIds; private readonly QueueManager parent; private readonly QueueStorage queueStorage; public MessageAcceptance(QueueManager parent, IList<MessageBookmark> bookmarks, IEnumerable<MessageId> messageIds, QueueStorage queueStorage) { this.parent = parent; this.bookmarks = bookmarks; this.messageIds = messageIds; this.queueStorage = queueStorage; #pragma warning disable 420 Interlocked.Increment(ref parent.currentlyInCriticalReceiveStatus); #pragma warning restore 420 } #region IMessageAcceptance Members public void Commit() { try { parent.AssertNotDisposed(); queueStorage.Global(actions => { foreach (var bookmark in bookmarks) { actions.GetQueue(bookmark.QueueName) .SetMessageStatus(bookmark, MessageStatus.ReadyToDeliver); } foreach (var id in messageIds) { actions.MarkReceived(id); } actions.Commit(); }); parent.receivedMsgs.Add(messageIds); lock (parent.newMessageArrivedLock) { Monitor.PulseAll(parent.newMessageArrivedLock); } } finally { #pragma warning disable 420 Interlocked.Decrement(ref parent.currentlyInCriticalReceiveStatus); #pragma warning restore 420 } } public void Abort() { try { parent.AssertNotDisposed(); queueStorage.Global(actions => { foreach (var bookmark in bookmarks) { actions.GetQueue(bookmark.QueueName) .Discard(bookmark); } actions.Commit(); }); } finally { #pragma warning disable 420 Interlocked.Decrement(ref parent.currentlyInCriticalReceiveStatus); #pragma warning restore 420 } } #endregion } #endregion public void CreateQueues(params string[] queueNames) { AssertNotDisposedOrDisposing(); queueStorage.Global(actions => { foreach (var queueName in queueNames) { actions.CreateQueueIfDoesNotExists(queueName); } actions.Commit(); }); } public string[] Queues { get { AssertNotDisposedOrDisposing(); string[] queues = null; queueStorage.Global(actions => { queues = actions.GetAllQueuesNames(); actions.Commit(); }); return queues; } } public void MoveTo(string subqueue, Message message) { AssertNotDisposedOrDisposing(); EnsureEnslistment(); queueStorage.Global(actions => { var queue = actions.GetQueue(message.Queue); var bookmark = queue.MoveTo(subqueue, (PersistentMessage)message); actions.RegisterUpdateToReverse(Enlistment.Id, bookmark, MessageStatus.ReadyToDeliver, message.SubQueue ); actions.Commit(); }); } public void EnqueueDirectlyTo(string queue, string subqueue, MessagePayload payload) { EnsureEnslistment(); queueStorage.Global(actions => { var queueActions = actions.GetQueue(queue); var bookmark = queueActions.Enqueue(new PersistentMessage { Data = payload.Data, Headers = payload.Headers, Id = new MessageId { SourceInstanceId = queueStorage.Id, MessageIdentifier = GuidCombGenerator.Generate() }, Queue = queue, SentAt = DateTime.Now, SubQueue = subqueue, Status = MessageStatus.EnqueueWait }); actions.RegisterUpdateToReverse(Enlistment.Id, bookmark, MessageStatus.EnqueueWait, subqueue); actions.Commit(); }); lock (newMessageArrivedLock) { Monitor.PulseAll(newMessageArrivedLock); } } public PersistentMessage PeekById(string queueName, MessageId id) { PersistentMessage message = null; queueStorage.Global(actions => { var queue = actions.GetQueue(queueName); message = queue.PeekById(id); actions.Commit(); }); return message; } public string[] GetSubqueues(string queueName) { string[] result = null; queueStorage.Global(actions => { var queue = actions.GetQueue(queueName); result = queue.Subqueues; actions.Commit(); }); return result; } public int GetNumberOfMessages(string queueName) { int numberOfMsgs = 0; queueStorage.Global(actions => { numberOfMsgs = actions.GetNumberOfMessages(queueName); actions.Commit(); }); return numberOfMsgs; } public void FailedToSendTo(Endpoint endpointThatWeFailedToSendTo) { var action = FailedToSendMessagesTo; if (action != null) action(endpointThatWeFailedToSendTo); } } }
// Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol.Models { using System.Linq; /// <summary> /// An Azure Batch task to add. /// </summary> public partial class TaskAddParameter { /// <summary> /// Initializes a new instance of the TaskAddParameter class. /// </summary> public TaskAddParameter() { } /// <summary> /// Initializes a new instance of the TaskAddParameter class. /// </summary> /// <param name="id">A string that uniquely identifies the task within /// the job.</param> /// <param name="commandLine">The command line of the task. For /// multi-instance tasks, the command line is executed on the primary /// subtask after all the subtasks have finished executing the /// coordianation command line.</param> /// <param name="displayName">A display name for the task.</param> /// <param name="exitConditions">How the Batch service should respond /// when the task completes.</param> /// <param name="resourceFiles">A list of files that the Batch service /// will download to the compute node before running the command /// line.</param> /// <param name="environmentSettings">A list of environment variable /// settings for the task.</param> /// <param name="affinityInfo">A locality hint that can be used by the /// Batch service to select a compute node on which to start the new /// task.</param> /// <param name="constraints">The execution constraints that apply to /// this task.</param> /// <param name="runElevated">Whether to run the task in elevated /// mode.</param> /// <param name="multiInstanceSettings">Information about how to run /// the multi-instance task.</param> /// <param name="dependsOn">Any other tasks that this task depends /// on.</param> /// <param name="applicationPackageReferences">A list of application /// packages that the Batch service will deploy to the compute node /// before running the command line.</param> public TaskAddParameter(string id, string commandLine, string displayName = default(string), ExitConditions exitConditions = default(ExitConditions), System.Collections.Generic.IList<ResourceFile> resourceFiles = default(System.Collections.Generic.IList<ResourceFile>), System.Collections.Generic.IList<EnvironmentSetting> environmentSettings = default(System.Collections.Generic.IList<EnvironmentSetting>), AffinityInformation affinityInfo = default(AffinityInformation), TaskConstraints constraints = default(TaskConstraints), bool? runElevated = default(bool?), MultiInstanceSettings multiInstanceSettings = default(MultiInstanceSettings), TaskDependencies dependsOn = default(TaskDependencies), System.Collections.Generic.IList<ApplicationPackageReference> applicationPackageReferences = default(System.Collections.Generic.IList<ApplicationPackageReference>)) { Id = id; DisplayName = displayName; CommandLine = commandLine; ExitConditions = exitConditions; ResourceFiles = resourceFiles; EnvironmentSettings = environmentSettings; AffinityInfo = affinityInfo; Constraints = constraints; RunElevated = runElevated; MultiInstanceSettings = multiInstanceSettings; DependsOn = dependsOn; ApplicationPackageReferences = applicationPackageReferences; } /// <summary> /// Gets or sets a string that uniquely identifies the task within the /// job. /// </summary> /// <remarks> /// The id can contain any combination of alphanumeric characters /// including hyphens and underscores, and cannot contain more than /// 64 characters. It is common to use a GUID for the id. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets a display name for the task. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "displayName")] public string DisplayName { get; set; } /// <summary> /// Gets or sets the command line of the task. For multi-instance /// tasks, the command line is executed on the primary subtask after /// all the subtasks have finished executing the coordianation /// command line. /// </summary> /// <remarks> /// The command line does not run under a shell, and therefore cannot /// take advantage of shell features such as environment variable /// expansion. If you want to take advantage of such features, you /// should invoke the shell in the command line, for example using /// "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "commandLine")] public string CommandLine { get; set; } /// <summary> /// Gets or sets how the Batch service should respond when the task /// completes. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "exitConditions")] public ExitConditions ExitConditions { get; set; } /// <summary> /// Gets or sets a list of files that the Batch service will download /// to the compute node before running the command line. /// </summary> /// <remarks> /// For multi-instance tasks, the resource files will only be /// downloaded to the compute node on which the primary subtask is /// executed. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "resourceFiles")] public System.Collections.Generic.IList<ResourceFile> ResourceFiles { get; set; } /// <summary> /// Gets or sets a list of environment variable settings for the task. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "environmentSettings")] public System.Collections.Generic.IList<EnvironmentSetting> EnvironmentSettings { get; set; } /// <summary> /// Gets or sets a locality hint that can be used by the Batch service /// to select a compute node on which to start the new task. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "affinityInfo")] public AffinityInformation AffinityInfo { get; set; } /// <summary> /// Gets or sets the execution constraints that apply to this task. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "constraints")] public TaskConstraints Constraints { get; set; } /// <summary> /// Gets or sets whether to run the task in elevated mode. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "runElevated")] public bool? RunElevated { get; set; } /// <summary> /// Gets or sets information about how to run the multi-instance task. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "multiInstanceSettings")] public MultiInstanceSettings MultiInstanceSettings { get; set; } /// <summary> /// Gets or sets any other tasks that this task depends on. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "dependsOn")] public TaskDependencies DependsOn { get; set; } /// <summary> /// Gets or sets a list of application packages that the Batch service /// will deploy to the compute node before running the command line. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "applicationPackageReferences")] public System.Collections.Generic.IList<ApplicationPackageReference> ApplicationPackageReferences { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Id == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "Id"); } if (CommandLine == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "CommandLine"); } if (this.ResourceFiles != null) { foreach (var element in this.ResourceFiles) { if (element != null) { element.Validate(); } } } if (this.EnvironmentSettings != null) { foreach (var element1 in this.EnvironmentSettings) { if (element1 != null) { element1.Validate(); } } } if (this.AffinityInfo != null) { this.AffinityInfo.Validate(); } if (this.MultiInstanceSettings != null) { this.MultiInstanceSettings.Validate(); } if (this.ApplicationPackageReferences != null) { foreach (var element2 in this.ApplicationPackageReferences) { if (element2 != null) { element2.Validate(); } } } } } }
// 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 CompareNotLessThanOrEqualDouble() { var test = new SimpleBinaryOpTest__CompareNotLessThanOrEqualDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareNotLessThanOrEqualDouble { 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(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); 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<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, 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 Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareNotLessThanOrEqualDouble testClass) { var result = Sse2.CompareNotLessThanOrEqual(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareNotLessThanOrEqualDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.CompareNotLessThanOrEqual( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareNotLessThanOrEqualDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__CompareNotLessThanOrEqualDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.CompareNotLessThanOrEqual( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_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 = Sse2.CompareNotLessThanOrEqual( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_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 = Sse2.CompareNotLessThanOrEqual( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_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(Sse2).GetMethod(nameof(Sse2.CompareNotLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.CompareNotLessThanOrEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.CompareNotLessThanOrEqual( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(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<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.CompareNotLessThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareNotLessThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareNotLessThanOrEqual(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareNotLessThanOrEqualDouble(); var result = Sse2.CompareNotLessThanOrEqual(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__CompareNotLessThanOrEqualDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.CompareNotLessThanOrEqual( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.CompareNotLessThanOrEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.CompareNotLessThanOrEqual( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(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 = Sse2.CompareNotLessThanOrEqual(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 = Sse2.CompareNotLessThanOrEqual( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&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(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != (!(left[0] <= right[0]) ? -1 : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != (!(left[i] <= right[i]) ? -1 : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareNotLessThanOrEqual)}<Double>(Vector128<Double>, Vector128<Double>): {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; } } } }
/* * Conversion.cs - Implementation of the * "Microsoft.VisualBasic.Conversion" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace Microsoft.VisualBasic { using System; using System.Text; using Microsoft.VisualBasic.CompilerServices; [StandardModule] public sealed class Conversion { // This class cannot be instantiated. private Conversion() {} // Get the error message for a particular error number. public static String ErrorToString() { String desc = Information.Err().Description; if(desc == null || desc == String.Empty) { return ErrorToString(Information.Err().Number); } else { return desc; } } public static String ErrorToString(int errornumber) { if(errornumber == 0) { return String.Empty; } String res = S._(String.Format("VB_Error{0}", errornumber)); if(res != null) { return res; } return S._("VB_ErrorDefault"); } // Get the "fix" integer version of a value. public static short Fix(short Number) { return Number; } public static int Fix(int Number) { return Number; } public static long Fix(long Number) { return Number; } public static double Fix(double Number) { if(Number >= 0.0) { return Math.Floor(Number); } else { return Math.Ceiling(Number); } } public static float Fix(float Number) { if(Number >= 0.0) { return (float)(Math.Floor(Number)); } else { return (float)(Math.Ceiling(Number)); } } public static Decimal Fix(Decimal Number) { return Decimal.Truncate(Number); } public static Object Fix(Object Number) { if(Number == null) { throw new ArgumentNullException("Number"); } switch(ObjectType.GetTypeCode(Number)) { case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: return Fix(IntegerType.FromObject(Number)); case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return Number; case TypeCode.Single: return Fix(SingleType.FromObject(Number)); case TypeCode.Double: return Fix(DoubleType.FromObject(Number)); case TypeCode.Decimal: return Fix(DecimalType.FromObject(Number)); case TypeCode.String: return Fix(DoubleType.FromString (StringType.FromObject(Number))); } throw new ArgumentException(S._("VB_InvalidNumber"), "Number"); } // Get the hexadecimal form of a value. public static String Hex(byte Number) { return Number.ToString("X"); } public static String Hex(short Number) { return Number.ToString("X"); } public static String Hex(int Number) { return Number.ToString("X"); } public static String Hex(long Number) { return Number.ToString("X"); } public static String Hex(Object Number) { if(Number == null) { throw new ArgumentNullException("Number"); } switch(ObjectType.GetTypeCode(Number)) { case TypeCode.Byte: return Hex(ByteType.FromObject(Number)); case TypeCode.Int16: return Hex(ShortType.FromObject(Number)); case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.UInt16: case TypeCode.Int32: return Hex(IntegerType.FromObject(Number)); case TypeCode.Int64: return Hex(LongType.FromObject(Number)); case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return Hex(LongType.FromObject(Number)); case TypeCode.String: return Hex(LongType.FromString (StringType.FromObject(Number))); } throw new ArgumentException(S._("VB_InvalidNumber"), "Number"); } // Get the integer version of a value. public static short Int(short Number) { return Number; } public static int Int(int Number) { return Number; } public static long Int(long Number) { return Number; } public static double Int(double Number) { return Math.Floor(Number); } public static float Int(float Number) { return (float)(Math.Floor(Number)); } public static Decimal Int(Decimal Number) { return Decimal.Floor(Number); } public static Object Int(Object Number) { if(Number == null) { throw new ArgumentNullException("Number"); } switch(ObjectType.GetTypeCode(Number)) { case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: return Int(IntegerType.FromObject(Number)); case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return Number; case TypeCode.Single: return Int(SingleType.FromObject(Number)); case TypeCode.Double: return Int(DoubleType.FromObject(Number)); case TypeCode.Decimal: return Int(DecimalType.FromObject(Number)); case TypeCode.String: return Int(DoubleType.FromString (StringType.FromObject(Number))); } throw new ArgumentException(S._("VB_InvalidNumber"), "Number"); } // Get the octal form of a value. public static String Oct(byte Number) { return Oct((long)Number); } public static String Oct(short Number) { return Oct((long)(ushort)Number); } public static String Oct(int Number) { return Oct((long)Number); } public static String Oct(long Number) { int numDigits = 1; long mask = 7; while((Number & ~mask) != 0) { ++numDigits; mask |= (mask << 3); } StringBuilder builder = new StringBuilder(); while(numDigits > 0) { --numDigits; mask = Number >> (numDigits * 3); builder.Append((char)(0x30 + (int)(mask & 7))); } return builder.ToString(); } public static String Oct(Object Number) { if(Number == null) { throw new ArgumentNullException("Number"); } switch(ObjectType.GetTypeCode(Number)) { case TypeCode.Byte: return Oct(ByteType.FromObject(Number)); case TypeCode.Int16: return Oct(ShortType.FromObject(Number)); case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.UInt16: case TypeCode.Int32: return Oct(IntegerType.FromObject(Number)); case TypeCode.Int64: return Oct(LongType.FromObject(Number)); case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return Oct(LongType.FromObject(Number)); case TypeCode.String: return Oct(LongType.FromString (StringType.FromObject(Number))); } throw new ArgumentException(S._("VB_InvalidNumber"), "Number"); } // Convert an object into a string. public static String Str(Object Number) { return StringType.FromObject(Number); } // Get the numeric value of a string. public static double Val(String InputStr) { return DoubleType.FromString(InputStr); } public static double Val(Object Expression) { return Val(Str(Expression)); } public static int Val(char Expression) { if(Expression >= '0' && Expression <= '9') { return (int)(Expression - '0'); } else { return 0; } } }; // class Conversion }; // namespace Microsoft.VisualBasic
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Compute.Tests { public class VMScaleSetScenarioTests : VMScaleSetVMTestsBase { /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet with extension /// Get VMScaleSet Model View /// Get VMScaleSet Instance View /// List VMScaleSets in a RG /// List Available Skus /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations")] public void TestVMScaleSetScenarioOperations() { using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context); } } /// <summary> /// Covers following Operations for ManagedDisks: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet with extension /// Get VMScaleSet Model View /// Get VMScaleSet Instance View /// List VMScaleSets in a RG /// List Available Skus /// Delete VMScaleSet /// Delete RG /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_ManagedDisks")] public void TestVMScaleSetScenarioOperations_ManagedDisks_PirImage() { using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, hasManagedDisks: true, useVmssExtension: false); } } /// <summary> /// To record this test case, you need to run it again zone supported regions like eastus2euap. /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_ManagedDisks_PirImage_SingleZone")] public void TestVMScaleSetScenarioOperations_ManagedDisks_PirImage_SingleZone() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "centralus"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, hasManagedDisks: true, useVmssExtension: false, zones: new List<string> { "1" }); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it in region which support local diff disks. /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_DiffDisks")] public void TestVMScaleSetScenarioOperations_DiffDisks() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "northeurope"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, vmSize: VirtualMachineSizeTypes.StandardDS5V2, hasManagedDisks: true, hasDiffDisks: true); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it in region which support encryption at host /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_EncryptionAtHost")] public void TestVMScaleSetScenarioOperations_EncryptionAtHost() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, vmSize: VirtualMachineSizeTypes.StandardDS1V2, hasManagedDisks: true, encryptionAtHostEnabled: true); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it in region which support DiskEncryptionSet resource for the Disks /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_With_DiskEncryptionSet")] public void TestVMScaleSetScenarioOperations_With_DiskEncryptionSet() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { string diskEncryptionSetId = getDefaultDiskEncryptionSetId(); Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, vmSize: VirtualMachineSizeTypes.StandardA1V2, hasManagedDisks: true, osDiskSizeInGB: 175, diskEncryptionSetId: diskEncryptionSetId); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_UltraSSD")] public void TestVMScaleSetScenarioOperations_UltraSSD() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, vmSize: VirtualMachineSizeTypes.StandardE4sV3, hasManagedDisks: true, useVmssExtension: false, zones: new List<string> { "1" }, enableUltraSSD: true, osDiskSizeInGB: 175); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it again zone supported regions like eastus2euap. /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_ManagedDisks_PirImage_Zones")] public void TestVMScaleSetScenarioOperations_ManagedDisks_PirImage_Zones() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "centralus"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal( context, hasManagedDisks: true, useVmssExtension: false, zones: new List<string> { "1", "3" }, osDiskSizeInGB: 175); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } /// <summary> /// To record this test case, you need to run it again zone supported regions like eastus2euap. /// </summary> [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_PpgScenario")] public void TestVMScaleSetScenarioOperations_PpgScenario() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, hasManagedDisks: true, useVmssExtension: false, isPpgScenario: true); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_AutomaticPlacementOnDedicatedHostGroup")] public void TestVMScaleSetScenarioOperations_AutomaticPlacementOnDedicatedHostGroup() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "westus"); // This test was recorded in WestUSValidation, where the platform image typically used for recording is not available. // Hence the following custom image was used. ImageReference imageReference = new ImageReference { Publisher = "AzureRT.PIRCore.TestWAStage", Offer = "TestUbuntuServer", Sku = "16.04", Version = "latest" }; using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, hasManagedDisks: true, useVmssExtension: false, isAutomaticPlacementOnDedicatedHostGroupScenario: true, vmSize: VirtualMachineSizeTypes.StandardD2sV3, faultDomainCount: 1, capacity: 1, shouldOverProvision: false, validateVmssVMInstanceView: true, imageReference: imageReference, validateListSku: false, deleteAsPartOfTest: false); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_ScheduledEvents")] public void TestVMScaleSetScenarioOperations_ScheduledEvents() { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2"); using (MockContext context = MockContext.Start(this.GetType())) { TestScaleSetOperationsInternal(context, hasManagedDisks: true, useVmssExtension: false, vmScaleSetCustomizer: vmScaleSet => { vmScaleSet.VirtualMachineProfile.ScheduledEventsProfile = new ScheduledEventsProfile { TerminateNotificationProfile = new TerminateNotificationProfile { Enable = true, NotBeforeTimeout = "PT6M", } }; }, vmScaleSetValidator: vmScaleSet => { Assert.True(true == vmScaleSet.VirtualMachineProfile.ScheduledEventsProfile?.TerminateNotificationProfile?.Enable); Assert.True("PT6M" == vmScaleSet.VirtualMachineProfile.ScheduledEventsProfile?.TerminateNotificationProfile?.NotBeforeTimeout); }); } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_AutomaticRepairsPolicyTest")] public void TestVMScaleSetScenarioOperations_AutomaticRepairsPolicyTest() { string environmentVariable = "AZURE_VM_TEST_LOCATION"; string region = "centraluseuap"; string originalTestLocation = Environment.GetEnvironmentVariable(environmentVariable); try { using (MockContext context = MockContext.Start(this.GetType())) { Environment.SetEnvironmentVariable(environmentVariable, region); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); var getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, null, (vmScaleSet) => { vmScaleSet.Overprovision = false; }, createWithManagedDisks: true, createWithPublicIpAddress: false, createWithHealthProbe: true); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); // Set Automatic Repairs to true inputVMScaleSet.AutomaticRepairsPolicy = new AutomaticRepairsPolicy() { Enabled = true }; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.NotNull(getResponse.AutomaticRepairsPolicy); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); // Update Automatic Repairs default values inputVMScaleSet.AutomaticRepairsPolicy = new AutomaticRepairsPolicy() { Enabled = true, GracePeriod = "PT35M" }; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.NotNull(getResponse.AutomaticRepairsPolicy); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); // Set automatic repairs to null inputVMScaleSet.AutomaticRepairsPolicy = null; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); Assert.NotNull(getResponse.AutomaticRepairsPolicy); Assert.True(getResponse.AutomaticRepairsPolicy.Enabled == true); Assert.Equal("PT35M", getResponse.AutomaticRepairsPolicy.GracePeriod, ignoreCase: true); // Disable Automatic Repairs inputVMScaleSet.AutomaticRepairsPolicy = new AutomaticRepairsPolicy() { Enabled = false }; UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet); getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName); Assert.NotNull(getResponse.AutomaticRepairsPolicy); Assert.True(getResponse.AutomaticRepairsPolicy.Enabled == false); } finally { //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } [Fact] [Trait("Name", "TestVMScaleSetScenarioOperations_OrchestrationService")] public void TestVMScaleSetScenarioOperations_OrchestrationService() { string environmentVariable = "AZURE_VM_TEST_LOCATION"; string region = "northeurope"; string originalTestLocation = Environment.GetEnvironmentVariable(environmentVariable); try { using (MockContext context = MockContext.Start(this.GetType())) { Environment.SetEnvironmentVariable(environmentVariable, region); EnsureClientsInitialized(context); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); AutomaticRepairsPolicy automaticRepairsPolicy = new AutomaticRepairsPolicy() { Enabled = true }; var getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, null, (vmScaleSet) => { vmScaleSet.Overprovision = false; }, createWithManagedDisks: true, createWithPublicIpAddress: false, createWithHealthProbe: true, automaticRepairsPolicy: automaticRepairsPolicy); ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true); var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); Assert.True(getInstanceViewResponse.OrchestrationServices.Count == 1); Assert.Equal("Running", getInstanceViewResponse.OrchestrationServices[0].ServiceState); Assert.Equal("AutomaticRepairs", getInstanceViewResponse.OrchestrationServices[0].ServiceName); OrchestrationServiceStateInput orchestrationServiceStateInput = new OrchestrationServiceStateInput() { ServiceName = OrchestrationServiceNames.AutomaticRepairs, Action = OrchestrationServiceStateAction.Suspend }; m_CrpClient.VirtualMachineScaleSets.SetOrchestrationServiceState(rgName, vmssName, orchestrationServiceStateInput); getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); Assert.Equal(OrchestrationServiceState.Suspended.ToString(), getInstanceViewResponse.OrchestrationServices[0].ServiceState); orchestrationServiceStateInput.Action = OrchestrationServiceStateAction.Resume; m_CrpClient.VirtualMachineScaleSets.SetOrchestrationServiceState(rgName, vmssName, orchestrationServiceStateInput); getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); Assert.Equal(OrchestrationServiceState.Running.ToString(), getInstanceViewResponse.OrchestrationServices[0].ServiceState); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmssName); } finally { //Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose //of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } } } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); } } private void TestScaleSetOperationsInternal(MockContext context, string vmSize = null, bool hasManagedDisks = false, bool useVmssExtension = true, bool hasDiffDisks = false, IList<string> zones = null, int? osDiskSizeInGB = null, bool isPpgScenario = false, bool? enableUltraSSD = false, Action<VirtualMachineScaleSet> vmScaleSetCustomizer = null, Action<VirtualMachineScaleSet> vmScaleSetValidator = null, string diskEncryptionSetId = null, bool? encryptionAtHostEnabled = null, bool isAutomaticPlacementOnDedicatedHostGroupScenario = false, int? faultDomainCount = null, int? capacity = null, bool shouldOverProvision = true, bool validateVmssVMInstanceView = false, ImageReference imageReference = null, bool validateListSku = true, bool deleteAsPartOfTest = true) { EnsureClientsInitialized(context); ImageReference imageRef = imageReference ?? GetPlatformVMImage(useWindowsImage: true); // Create resource group var rgName = TestUtilities.GenerateName(TestPrefix); var vmssName = TestUtilities.GenerateName("vmss"); string storageAccountName = TestUtilities.GenerateName(TestPrefix); VirtualMachineScaleSet inputVMScaleSet; VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile() { Extensions = new List<VirtualMachineScaleSetExtension>() { GetTestVMSSVMExtension(autoUpdateMinorVersion:false), } }; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist"); string ppgId = null; string ppgName = null; if (isPpgScenario) { ppgName = ComputeManagementTestUtilities.GenerateName("ppgtest"); ppgId = CreateProximityPlacementGroup(rgName, ppgName); } string dedicatedHostGroupName = null, dedicatedHostName = null, dedicatedHostGroupReferenceId = null, dedicatedHostReferenceId = null; if (isAutomaticPlacementOnDedicatedHostGroupScenario) { dedicatedHostGroupName = ComputeManagementTestUtilities.GenerateName("dhgtest"); dedicatedHostName = ComputeManagementTestUtilities.GenerateName("dhtest"); dedicatedHostGroupReferenceId = Helpers.GetDedicatedHostGroupRef(m_subId, rgName, dedicatedHostGroupName); dedicatedHostReferenceId = Helpers.GetDedicatedHostRef(m_subId, rgName, dedicatedHostGroupName, dedicatedHostName); } VirtualMachineScaleSet getResponse = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, useVmssExtension ? extensionProfile : null, (vmScaleSet) => { vmScaleSet.Overprovision = shouldOverProvision; if (!String.IsNullOrEmpty(vmSize)) { vmScaleSet.Sku.Name = vmSize; } vmScaleSetCustomizer?.Invoke(vmScaleSet); }, createWithManagedDisks: hasManagedDisks, hasDiffDisks : hasDiffDisks, zones: zones, osDiskSizeInGB: osDiskSizeInGB, ppgId: ppgId, enableUltraSSD: enableUltraSSD, diskEncryptionSetId: diskEncryptionSetId, encryptionAtHostEnabled: encryptionAtHostEnabled, faultDomainCount: faultDomainCount, capacity: capacity, dedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId, dedicatedHostGroupName: dedicatedHostGroupName, dedicatedHostName: dedicatedHostName); if (diskEncryptionSetId != null) { Assert.True(getResponse.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet != null, "OsDisk.ManagedDisk.DiskEncryptionSet is null"); Assert.True(string.Equals(diskEncryptionSetId, getResponse.VirtualMachineProfile.StorageProfile.OsDisk.ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase), "OsDisk.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource"); Assert.Equal(1, getResponse.VirtualMachineProfile.StorageProfile.DataDisks.Count); Assert.True(getResponse.VirtualMachineProfile.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet != null, ".DataDisks.ManagedDisk.DiskEncryptionSet is null"); Assert.True(string.Equals(diskEncryptionSetId, getResponse.VirtualMachineProfile.StorageProfile.DataDisks[0].ManagedDisk.DiskEncryptionSet.Id, StringComparison.OrdinalIgnoreCase), "DataDisks.ManagedDisk.DiskEncryptionSet.Id is not matching with expected DiskEncryptionSet resource"); } if (encryptionAtHostEnabled != null) { Assert.True(getResponse.VirtualMachineProfile.SecurityProfile.EncryptionAtHost == encryptionAtHostEnabled.Value, "SecurityProfile.EncryptionAtHost is not same as expected"); } ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks, ppgId: ppgId, dedicatedHostGroupReferenceId: dedicatedHostGroupReferenceId); var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName); Assert.NotNull(getInstanceViewResponse); ValidateVMScaleSetInstanceView(inputVMScaleSet, getInstanceViewResponse); if (isPpgScenario) { ProximityPlacementGroup outProximityPlacementGroup = m_CrpClient.ProximityPlacementGroups.Get(rgName, ppgName); Assert.Equal(1, outProximityPlacementGroup.VirtualMachineScaleSets.Count); string expectedVmssReferenceId = Helpers.GetVMScaleSetReferenceId(m_subId, rgName, vmssName); Assert.Equal(expectedVmssReferenceId, outProximityPlacementGroup.VirtualMachineScaleSets.First().Id, StringComparer.OrdinalIgnoreCase); } var listResponse = m_CrpClient.VirtualMachineScaleSets.List(rgName); ValidateVMScaleSet(inputVMScaleSet, listResponse.FirstOrDefault(x => x.Name == vmssName), hasManagedDisks); if (validateListSku) { var listSkusResponse = m_CrpClient.VirtualMachineScaleSets.ListSkus(rgName, vmssName); Assert.NotNull(listSkusResponse); Assert.False(listSkusResponse.Count() == 0); } if (zones != null) { var query = new Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineScaleSetVM>(); query.SetFilter(vm => vm.LatestModelApplied == true); var listVMsResponse = m_CrpClient.VirtualMachineScaleSetVMs.List(rgName, vmssName, query); Assert.False(listVMsResponse == null, "VMScaleSetVMs not returned"); Assert.True(listVMsResponse.Count() == inputVMScaleSet.Sku.Capacity); foreach (var vmScaleSetVM in listVMsResponse) { string instanceId = vmScaleSetVM.InstanceId; var getVMResponse = m_CrpClient.VirtualMachineScaleSetVMs.Get(rgName, vmssName, instanceId); ValidateVMScaleSetVM(inputVMScaleSet, instanceId, getVMResponse, hasManagedDisks); } } if (validateVmssVMInstanceView) { VirtualMachineScaleSetVMInstanceView vmssVMInstanceView = m_CrpClient.VirtualMachineScaleSetVMs.GetInstanceView(rgName, vmssName, "0"); ValidateVMScaleSetVMInstanceView(vmssVMInstanceView, hasManagedDisks, dedicatedHostReferenceId); } vmScaleSetValidator?.Invoke(getResponse); if (deleteAsPartOfTest) { m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmssName); } } finally { if (deleteAsPartOfTest) { m_ResourcesClient.ResourceGroups.Delete(rgName); } else { // Fire and forget. No need to wait for RG deletion completion m_ResourcesClient.ResourceGroups.BeginDelete(rgName); } } } } }
//------------------------------------------------------------------------------ // <copyright file="HybridDictionary.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Collections.Specialized { using System.Collections; using System.Globalization; /// <devdoc> /// <para> /// This data structure implements IDictionary first using a linked list /// (ListDictionary) and then switching over to use Hashtable when large. This is recommended /// for cases where the number of elements in a dictionary is unknown and might be small. /// /// It also has a single boolean parameter to allow case-sensitivity that is not affected by /// ambient culture and has been optimized for looking up case-insensitive symbols /// </para> /// </devdoc> [Serializable] public class HybridDictionary: IDictionary { // These numbers have been carefully tested to be optimal. Please don't change them // without doing thorough performance testing. private const int CutoverPoint = 9; private const int InitialHashtableSize = 13; private const int FixedSizeCutoverPoint = 6; // Instance variables. This keeps the HybridDictionary very light-weight when empty private ListDictionary list; private Hashtable hashtable; private bool caseInsensitive; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HybridDictionary() { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HybridDictionary(int initialSize) : this(initialSize, false) { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HybridDictionary(bool caseInsensitive) { this.caseInsensitive = caseInsensitive; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public HybridDictionary(int initialSize, bool caseInsensitive) { this.caseInsensitive = caseInsensitive; if (initialSize >= FixedSizeCutoverPoint) { if (caseInsensitive) { hashtable = new Hashtable(initialSize, StringComparer.OrdinalIgnoreCase); } else { hashtable = new Hashtable(initialSize); } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object this[object key] { get { // < ListDictionary cachedList = list; if (hashtable != null) { return hashtable[key]; } else if (cachedList != null) { return cachedList[key]; } else { // < if (key == null) { throw new ArgumentNullException("key", SR.GetString(SR.ArgumentNull_Key)); } return null; } } set { if (hashtable != null) { hashtable[key] = value; } else if (list != null) { if (list.Count >= CutoverPoint - 1) { ChangeOver(); hashtable[key] = value; } else { list[key] = value; } } else { list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); list[key] = value; } } } private ListDictionary List { get { if (list == null) { list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); } return list; } } private void ChangeOver() { IDictionaryEnumerator en = list.GetEnumerator(); Hashtable newTable; if (caseInsensitive) { newTable = new Hashtable(InitialHashtableSize, StringComparer.OrdinalIgnoreCase); } else { newTable = new Hashtable(InitialHashtableSize); } while (en.MoveNext()) { newTable.Add(en.Key, en.Value); } // < hashtable = newTable; list = null; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int Count { get { ListDictionary cachedList = list; if (hashtable != null) { return hashtable.Count; } else if (cachedList != null) { return cachedList.Count; } else { return 0; } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ICollection Keys { get { if (hashtable != null) { return hashtable.Keys; } else { return List.Keys; } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsReadOnly { get { return false; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsFixedSize { get { return false; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool IsSynchronized { get { return false; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object SyncRoot { get { return this; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public ICollection Values { get { if (hashtable != null) { return hashtable.Values; } else { return List.Values; } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Add(object key, object value) { if (hashtable != null) { hashtable.Add(key, value); } else { if (list == null) { list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); list.Add(key, value); } else { if (list.Count + 1 >= CutoverPoint) { ChangeOver(); hashtable.Add(key, value); } else { list.Add(key, value); } } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Clear() { if(hashtable != null) { Hashtable cachedHashtable = hashtable; hashtable = null; cachedHashtable.Clear(); } if( list != null) { ListDictionary cachedList = list; list = null; cachedList.Clear(); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Contains(object key) { ListDictionary cachedList = list; if (hashtable != null) { return hashtable.Contains(key); } else if (cachedList != null) { return cachedList.Contains(key); } else { if (key == null) { throw new ArgumentNullException("key", SR.GetString(SR.ArgumentNull_Key)); } return false; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void CopyTo(Array array, int index) { if (hashtable != null) { hashtable.CopyTo(array, index); } else { List.CopyTo(array, index); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public IDictionaryEnumerator GetEnumerator() { if (hashtable != null) { return hashtable.GetEnumerator(); } if (list == null) { list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); } return list.GetEnumerator(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> IEnumerator IEnumerable.GetEnumerator() { if (hashtable != null) { return hashtable.GetEnumerator(); } if (list == null) { list = new ListDictionary(caseInsensitive ? StringComparer.OrdinalIgnoreCase : null); } return list.GetEnumerator(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Remove(object key) { if (hashtable != null) { hashtable.Remove(key); } else if (list != null){ list.Remove(key); } else { if (key == null) { throw new ArgumentNullException("key", SR.GetString(SR.ArgumentNull_Key)); } } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** CLASS: XMLUtil ** ** <OWNER>[....]</OWNER> ** ** PURPOSE: Helpers for XML input & output ** ===========================================================*/ namespace System.Security.Util { using System; using System.Security; using System.Security.Permissions; using System.Security.Policy; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.IO; using System.Text; using System.Runtime.CompilerServices; using PermissionState = System.Security.Permissions.PermissionState; using BindingFlags = System.Reflection.BindingFlags; using Assembly = System.Reflection.Assembly; using System.Threading; using System.Globalization; using System.Reflection; using System.Diagnostics.Contracts; internal static class XMLUtil { // // Warning: Element constructors have side-effects on their // third argument. // private const String BuiltInPermission = "System.Security.Permissions."; #if FEATURE_CAS_POLICY private const String BuiltInMembershipCondition = "System.Security.Policy."; private const String BuiltInCodeGroup = "System.Security.Policy."; private const String BuiltInApplicationSecurityManager = "System.Security.Policy."; private static readonly char[] sepChar = {',', ' '}; #endif public static SecurityElement NewPermissionElement (IPermission ip) { return NewPermissionElement (ip.GetType ().FullName) ; } public static SecurityElement NewPermissionElement (String name) { SecurityElement ecr = new SecurityElement( "Permission" ); ecr.AddAttribute( "class", name ); return ecr; } public static void AddClassAttribute( SecurityElement element, Type type, String typename ) { // Replace any quotes with apostrophes so that we can include quoted materials // within classnames. Notably the assembly name member 'loc' uses a quoted string. // NOTE: this makes assumptions as to what reflection is expecting for a type string // it will need to be updated if reflection changes what it wants. if ( typename == null ) typename = type.FullName; Contract.Assert( type.FullName.Equals( typename ), "Incorrect class name passed! Was : " + typename + " Shoule be: " + type.FullName); element.AddAttribute( "class", typename + ", " + type.Module.Assembly.FullName.Replace( '\"', '\'' ) ); } internal static bool ParseElementForAssemblyIdentification(SecurityElement el, out String className, out String assemblyName, // for example "WindowsBase" out String assemblyVersion) { className = null; assemblyName = null; assemblyVersion = null; String fullClassName = el.Attribute( "class" ); if (fullClassName == null) { return false; } if (fullClassName.IndexOf('\'') >= 0) { fullClassName = fullClassName.Replace( '\'', '\"' ); } int commaIndex = fullClassName.IndexOf( ',' ); int namespaceClassNameLength; // If the classname is tagged with assembly information, find where // the assembly information begins. if (commaIndex == -1) { return false; } namespaceClassNameLength = commaIndex; className = fullClassName.Substring(0, namespaceClassNameLength); String assemblyFullName = fullClassName.Substring(commaIndex + 1); AssemblyName an = new AssemblyName(assemblyFullName); assemblyName = an.Name; assemblyVersion = an.Version.ToString(); return true; } [System.Security.SecurityCritical] // auto-generated private static bool ParseElementForObjectCreation( SecurityElement el, String requiredNamespace, out String className, out int classNameStart, out int classNameLength ) { className = null; classNameStart = 0; classNameLength = 0; int requiredNamespaceLength = requiredNamespace.Length; String fullClassName = el.Attribute( "class" ); if (fullClassName == null) { throw new ArgumentException( Environment.GetResourceString( "Argument_NoClass" ) ); } if (fullClassName.IndexOf('\'') >= 0) { fullClassName = fullClassName.Replace( '\'', '\"' ); } if (!PermissionToken.IsMscorlibClassName( fullClassName )) { return false; } int commaIndex = fullClassName.IndexOf( ',' ); int namespaceClassNameLength; // If the classname is tagged with assembly information, find where // the assembly information begins. if (commaIndex == -1) { namespaceClassNameLength = fullClassName.Length; } else { namespaceClassNameLength = commaIndex; } // Only if the length of the class name is greater than the namespace info // on our requiredNamespace do we continue // with our check. if (namespaceClassNameLength > requiredNamespaceLength) { // Make sure we are in the required namespace. if (fullClassName.StartsWith(requiredNamespace, StringComparison.Ordinal)) { className = fullClassName; classNameLength = namespaceClassNameLength - requiredNamespaceLength; classNameStart = requiredNamespaceLength; return true; } } return false; } #if FEATURE_CAS_POLICY public static String SecurityObjectToXmlString(Object ob) { if(ob == null) return ""; PermissionSet pset = ob as PermissionSet; if(pset != null) return pset.ToXml().ToString(); return ((IPermission)ob).ToXml().ToString(); } [System.Security.SecurityCritical] // auto-generated public static Object XmlStringToSecurityObject(String s) { if(s == null) return null; if(s.Length < 1) return null; return SecurityElement.FromString(s).ToSecurityObject(); } #endif // FEATURE_CAS_POLICY [SecuritySafeCritical] public static IPermission CreatePermission (SecurityElement el, PermissionState permState, bool ignoreTypeLoadFailures) { if (el == null || !(el.Tag.Equals("Permission") || el.Tag.Equals("IPermission")) ) throw new ArgumentException( String.Format( null, Environment.GetResourceString( "Argument_WrongElementType" ), "<Permission>" ) ) ; Contract.EndContractBlock(); String className; int classNameLength; int classNameStart; if (!ParseElementForObjectCreation( el, BuiltInPermission, out className, out classNameStart, out classNameLength )) { goto USEREFLECTION; } // We have a built in permission, figure out which it is. // UIPermission // FileIOPermission // SecurityPermission // PrincipalPermission // ReflectionPermission // FileDialogPermission // EnvironmentPermission // GacIdentityPermission // UrlIdentityPermission // SiteIdentityPermission // ZoneIdentityPermission // KeyContainerPermission // UnsafeForHostPermission // HostProtectionPermission // StrongNameIdentityPermission #if !FEATURE_CORECLR // IsolatedStorageFilePermission #endif #if !FEATURE_PAL // RegistryPermission // PublisherIdentityPermission #endif // !FEATURE_PAL switch (classNameLength) { case 12: // UIPermission if (String.Compare(className, classNameStart, "UIPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new UIPermission( permState ); else goto USEREFLECTION; case 16: // FileIOPermission if (String.Compare(className, classNameStart, "FileIOPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new FileIOPermission( permState ); else goto USEREFLECTION; case 18: #if !FEATURE_PAL // RegistryPermission // SecurityPermission if (className[classNameStart] == 'R') { if (String.Compare(className, classNameStart, "RegistryPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new RegistryPermission( permState ); else goto USEREFLECTION; } else { if (String.Compare(className, classNameStart, "SecurityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new SecurityPermission( permState ); else goto USEREFLECTION; } #else // !FEATURE_PAL if (String.Compare(className, classNameStart, "SecurityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new SecurityPermission( permState ); else goto USEREFLECTION; #endif // !FEATURE_PAL #if !FEATURE_CORECLR case 19: // PrincipalPermission if (String.Compare(className, classNameStart, "PrincipalPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new PrincipalPermission( permState ); else goto USEREFLECTION; #endif // !FEATURE_CORECLR case 20: // ReflectionPermission // FileDialogPermission if (className[classNameStart] == 'R') { if (String.Compare(className, classNameStart, "ReflectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new ReflectionPermission( permState ); else goto USEREFLECTION; } else { if (String.Compare(className, classNameStart, "FileDialogPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new FileDialogPermission( permState ); else goto USEREFLECTION; } case 21: // EnvironmentPermission // UrlIdentityPermission // GacIdentityPermission if (className[classNameStart] == 'E') { if (String.Compare(className, classNameStart, "EnvironmentPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new EnvironmentPermission( permState ); else goto USEREFLECTION; } else if (className[classNameStart] == 'U') { if (String.Compare(className, classNameStart, "UrlIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new UrlIdentityPermission( permState ); else goto USEREFLECTION; } else { if (String.Compare(className, classNameStart, "GacIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new GacIdentityPermission( permState ); else goto USEREFLECTION; } case 22: // SiteIdentityPermission // ZoneIdentityPermission // KeyContainerPermission if (className[classNameStart] == 'S') { if (String.Compare(className, classNameStart, "SiteIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new SiteIdentityPermission( permState ); else goto USEREFLECTION; } else if (className[classNameStart] == 'Z') { if (String.Compare(className, classNameStart, "ZoneIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new ZoneIdentityPermission( permState ); else goto USEREFLECTION; } else { #if !FEATURE_PAL if (String.Compare(className, classNameStart, "KeyContainerPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new KeyContainerPermission( permState ); else #endif // !FEATURE_PAL goto USEREFLECTION; } case 24: // HostProtectionPermission if (String.Compare(className, classNameStart, "HostProtectionPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new HostProtectionPermission( permState ); else goto USEREFLECTION; #if FEATURE_X509 && FEATURE_CAS_POLICY case 27: // PublisherIdentityPermission if (String.Compare(className, classNameStart, "PublisherIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new PublisherIdentityPermission( permState ); else goto USEREFLECTION; #endif // FEATURE_X509 && FEATURE_CAS_POLICY case 28: // StrongNameIdentityPermission if (String.Compare(className, classNameStart, "StrongNameIdentityPermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new StrongNameIdentityPermission( permState ); else goto USEREFLECTION; #if !FEATURE_CORECLR case 29: // IsolatedStorageFilePermission if (String.Compare(className, classNameStart, "IsolatedStorageFilePermission", 0, classNameLength, StringComparison.Ordinal) == 0) return new IsolatedStorageFilePermission( permState ); else goto USEREFLECTION; #endif default: goto USEREFLECTION; } USEREFLECTION: Object[] objs = new Object[1]; objs[0] = permState; Type permClass = null; IPermission perm = null; new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); permClass = GetClassFromElement(el, ignoreTypeLoadFailures); if (permClass == null) return null; if (!(typeof(IPermission).IsAssignableFrom(permClass))) throw new ArgumentException( Environment.GetResourceString("Argument_NotAPermissionType") ); perm = (IPermission) Activator.CreateInstance(permClass, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, objs, null ); return perm; } #if FEATURE_CAS_POLICY #pragma warning disable 618 // CodeGroups are obsolete [System.Security.SecuritySafeCritical] // auto-generated public static CodeGroup CreateCodeGroup (SecurityElement el) { if (el == null || !el.Tag.Equals("CodeGroup")) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "<CodeGroup>" ) ) ; Contract.EndContractBlock(); String className; int classNameLength; int classNameStart; if (!ParseElementForObjectCreation( el, BuiltInCodeGroup, out className, out classNameStart, out classNameLength )) { goto USEREFLECTION; } switch (classNameLength) { case 12: // NetCodeGroup if (String.Compare(className, classNameStart, "NetCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) return new NetCodeGroup(); else goto USEREFLECTION; case 13: // FileCodeGroup if (String.Compare(className, classNameStart, "FileCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) return new FileCodeGroup(); else goto USEREFLECTION; case 14: // UnionCodeGroup if (String.Compare(className, classNameStart, "UnionCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) return new UnionCodeGroup(); else goto USEREFLECTION; case 19: // FirstMatchCodeGroup if (String.Compare(className, classNameStart, "FirstMatchCodeGroup", 0, classNameLength, StringComparison.Ordinal) == 0) return new FirstMatchCodeGroup(); else goto USEREFLECTION; default: goto USEREFLECTION; } USEREFLECTION: Type groupClass = null; CodeGroup group = null; new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); groupClass = GetClassFromElement(el, true); if (groupClass == null) return null; if (!(typeof(CodeGroup).IsAssignableFrom(groupClass))) throw new ArgumentException( Environment.GetResourceString("Argument_NotACodeGroupType") ); group = (CodeGroup) Activator.CreateInstance(groupClass, true); Contract.Assert( groupClass.Module.Assembly != Assembly.GetExecutingAssembly(), "This path should not get called for mscorlib based classes" ); return group; } #pragma warning restore 618 [System.Security.SecurityCritical] // auto-generated internal static IMembershipCondition CreateMembershipCondition( SecurityElement el ) { if (el == null || !el.Tag.Equals("IMembershipCondition")) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "Argument_WrongElementType" ), "<IMembershipCondition>" ) ) ; Contract.EndContractBlock(); String className; int classNameStart; int classNameLength; if (!ParseElementForObjectCreation( el, BuiltInMembershipCondition, out className, out classNameStart, out classNameLength )) { goto USEREFLECTION; } // We have a built in membership condition, figure out which it is. // Here's the list of built in membership conditions as of 9/17/2002 // System.Security.Policy.AllMembershipCondition // System.Security.Policy.URLMembershipCondition // System.Security.Policy.SHA1MembershipCondition // System.Security.Policy.SiteMembershipCondition // System.Security.Policy.ZoneMembershipCondition // System.Security.Policy.PublisherMembershipCondition // System.Security.Policy.StrongNameMembershipCondition // System.Security.Policy.ApplicationMembershipCondition // System.Security.Policy.DomainApplicationMembershipCondition // System.Security.Policy.ApplicationDirectoryMembershipCondition switch (classNameLength) { case 22: // AllMembershipCondition // URLMembershipCondition if (className[classNameStart] == 'A') { if (String.Compare(className, classNameStart, "AllMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new AllMembershipCondition(); else goto USEREFLECTION; } else { if (String.Compare(className, classNameStart, "UrlMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new UrlMembershipCondition(); else goto USEREFLECTION; } case 23: #if !FEATURE_PAL // HashMembershipCondition // SiteMembershipCondition // ZoneMembershipCondition if (className[classNameStart] == 'H') { if (String.Compare(className, classNameStart, "HashMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new HashMembershipCondition(); else goto USEREFLECTION; } else if (className[classNameStart] == 'S') #else // SiteMembershipCondition // ZoneMembershipCondition if (className[classNameStart] == 'S') #endif // !FEATURE_PAL { if (String.Compare(className, classNameStart, "SiteMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new SiteMembershipCondition(); else goto USEREFLECTION; } else { if (String.Compare(className, classNameStart, "ZoneMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new ZoneMembershipCondition(); else goto USEREFLECTION; } case 28: #if !FEATURE_PAL // PublisherMembershipCondition if (String.Compare(className, classNameStart, "PublisherMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new PublisherMembershipCondition(); else #endif // !FEATURE_PAL goto USEREFLECTION; case 29: // StrongNameMembershipCondition if (String.Compare(className, classNameStart, "StrongNameMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new StrongNameMembershipCondition(); else goto USEREFLECTION; case 39: // ApplicationDirectoryMembershipCondition if (String.Compare(className, classNameStart, "ApplicationDirectoryMembershipCondition", 0, classNameLength, StringComparison.Ordinal) == 0) return new ApplicationDirectoryMembershipCondition(); else goto USEREFLECTION; default: goto USEREFLECTION; } USEREFLECTION: Type condClass = null; IMembershipCondition cond = null; new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Assert(); condClass = GetClassFromElement(el, true); if (condClass == null) return null; if (!(typeof(IMembershipCondition).IsAssignableFrom(condClass))) throw new ArgumentException( Environment.GetResourceString("Argument_NotAMembershipCondition") ); cond = (IMembershipCondition) Activator.CreateInstance(condClass, true); return cond; } #endif //#if FEATURE_CAS_POLICY internal static Type GetClassFromElement (SecurityElement el, bool ignoreTypeLoadFailures) { String className = el.Attribute( "class" ); if (className == null) { if (ignoreTypeLoadFailures) return null; else throw new ArgumentException( String.Format( null, Environment.GetResourceString("Argument_InvalidXMLMissingAttr"), "class") ); } if (ignoreTypeLoadFailures) { try { return Type.GetType(className, false, false); } catch (SecurityException) { return null; } } else return Type.GetType(className, true, false); } public static bool IsPermissionElement (IPermission ip, SecurityElement el) { if (!el.Tag.Equals ("Permission") && !el.Tag.Equals ("IPermission")) return false; return true; } public static bool IsUnrestricted (SecurityElement el) { String sUnrestricted = el.Attribute( "Unrestricted" ); if (sUnrestricted == null) return false; return sUnrestricted.Equals( "true" ) || sUnrestricted.Equals( "TRUE" ) || sUnrestricted.Equals( "True" ); } public static String BitFieldEnumToString( Type type, Object value ) { int iValue = (int)value; if (iValue == 0) return Enum.GetName( type, 0 ); StringBuilder result = StringBuilderCache.Acquire(); bool first = true; int flag = 0x1; for (int i = 1; i < 32; ++i) { if ((flag & iValue) != 0) { String sFlag = Enum.GetName( type, flag ); if (sFlag == null) continue; if (!first) { result.Append( ", " ); } result.Append( sFlag ); first = false; } flag = flag << 1; } return StringBuilderCache.GetStringAndRelease(result); } } }
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> /// Sickbay Medication Administrations Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SAIMDataSet : EduHubDataSet<SAIM> { /// <inheritdoc /> public override string Name { get { return "SAIM"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SAIMDataSet(EduHubContext Context) : base(Context) { Index_INVOLVEMENTID = new Lazy<Dictionary<int, IReadOnlyList<SAIM>>>(() => this.ToGroupedDictionary(i => i.INVOLVEMENTID)); Index_STAFF = new Lazy<NullDictionary<string, IReadOnlyList<SAIM>>>(() => this.ToGroupedNullDictionary(i => i.STAFF)); Index_TID = new Lazy<Dictionary<int, SAIM>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SAIM" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SAIM" /> fields for each CSV column header</returns> internal override Action<SAIM, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SAIM, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "INVOLVEMENTID": mapper[i] = (e, v) => e.INVOLVEMENTID = int.Parse(v); break; case "MEDICATION": mapper[i] = (e, v) => e.MEDICATION = v; break; case "STAFF": mapper[i] = (e, v) => e.STAFF = v; break; case "ADMIN_BY_OTHER": mapper[i] = (e, v) => e.ADMIN_BY_OTHER = v; break; case "ADMIN_TIME": mapper[i] = (e, v) => e.ADMIN_TIME = v == null ? (short?)null : short.Parse(v); break; case "DOSE": mapper[i] = (e, v) => e.DOSE = v; break; case "ADMIN_NOTES": mapper[i] = (e, v) => e.ADMIN_NOTES = 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="SAIM" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SAIM" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SAIM" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SAIM}"/> of entities</returns> internal override IEnumerable<SAIM> ApplyDeltaEntities(IEnumerable<SAIM> Entities, List<SAIM> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.INVOLVEMENTID; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.INVOLVEMENTID.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<int, IReadOnlyList<SAIM>>> Index_INVOLVEMENTID; private Lazy<NullDictionary<string, IReadOnlyList<SAIM>>> Index_STAFF; private Lazy<Dictionary<int, SAIM>> Index_TID; #endregion #region Index Methods /// <summary> /// Find SAIM by INVOLVEMENTID field /// </summary> /// <param name="INVOLVEMENTID">INVOLVEMENTID value used to find SAIM</param> /// <returns>List of related SAIM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SAIM> FindByINVOLVEMENTID(int INVOLVEMENTID) { return Index_INVOLVEMENTID.Value[INVOLVEMENTID]; } /// <summary> /// Attempt to find SAIM by INVOLVEMENTID field /// </summary> /// <param name="INVOLVEMENTID">INVOLVEMENTID value used to find SAIM</param> /// <param name="Value">List of related SAIM entities</param> /// <returns>True if the list of related SAIM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByINVOLVEMENTID(int INVOLVEMENTID, out IReadOnlyList<SAIM> Value) { return Index_INVOLVEMENTID.Value.TryGetValue(INVOLVEMENTID, out Value); } /// <summary> /// Attempt to find SAIM by INVOLVEMENTID field /// </summary> /// <param name="INVOLVEMENTID">INVOLVEMENTID value used to find SAIM</param> /// <returns>List of related SAIM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SAIM> TryFindByINVOLVEMENTID(int INVOLVEMENTID) { IReadOnlyList<SAIM> value; if (Index_INVOLVEMENTID.Value.TryGetValue(INVOLVEMENTID, out value)) { return value; } else { return null; } } /// <summary> /// Find SAIM by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find SAIM</param> /// <returns>List of related SAIM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SAIM> FindBySTAFF(string STAFF) { return Index_STAFF.Value[STAFF]; } /// <summary> /// Attempt to find SAIM by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find SAIM</param> /// <param name="Value">List of related SAIM entities</param> /// <returns>True if the list of related SAIM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySTAFF(string STAFF, out IReadOnlyList<SAIM> Value) { return Index_STAFF.Value.TryGetValue(STAFF, out Value); } /// <summary> /// Attempt to find SAIM by STAFF field /// </summary> /// <param name="STAFF">STAFF value used to find SAIM</param> /// <returns>List of related SAIM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SAIM> TryFindBySTAFF(string STAFF) { IReadOnlyList<SAIM> value; if (Index_STAFF.Value.TryGetValue(STAFF, out value)) { return value; } else { return null; } } /// <summary> /// Find SAIM by TID field /// </summary> /// <param name="TID">TID value used to find SAIM</param> /// <returns>Related SAIM entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SAIM FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find SAIM by TID field /// </summary> /// <param name="TID">TID value used to find SAIM</param> /// <param name="Value">Related SAIM entity</param> /// <returns>True if the related SAIM entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out SAIM Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find SAIM by TID field /// </summary> /// <param name="TID">TID value used to find SAIM</param> /// <returns>Related SAIM entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SAIM TryFindByTID(int TID) { SAIM value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SAIM 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].[SAIM]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SAIM]( [TID] int IDENTITY NOT NULL, [INVOLVEMENTID] int NOT NULL, [MEDICATION] varchar(30) NULL, [STAFF] varchar(4) NULL, [ADMIN_BY_OTHER] varchar(30) NULL, [ADMIN_TIME] smallint NULL, [DOSE] varchar(30) NULL, [ADMIN_NOTES] varchar(MAX) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SAIM_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [SAIM_Index_INVOLVEMENTID] ON [dbo].[SAIM] ( [INVOLVEMENTID] ASC ); CREATE NONCLUSTERED INDEX [SAIM_Index_STAFF] ON [dbo].[SAIM] ( [STAFF] 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].[SAIM]') AND name = N'SAIM_Index_STAFF') ALTER INDEX [SAIM_Index_STAFF] ON [dbo].[SAIM] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SAIM]') AND name = N'SAIM_Index_TID') ALTER INDEX [SAIM_Index_TID] ON [dbo].[SAIM] 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].[SAIM]') AND name = N'SAIM_Index_STAFF') ALTER INDEX [SAIM_Index_STAFF] ON [dbo].[SAIM] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SAIM]') AND name = N'SAIM_Index_TID') ALTER INDEX [SAIM_Index_TID] ON [dbo].[SAIM] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SAIM"/> 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="SAIM"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SAIM> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[SAIM] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SAIM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SAIM data set</returns> public override EduHubDataSetDataReader<SAIM> GetDataSetDataReader() { return new SAIMDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SAIM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SAIM data set</returns> public override EduHubDataSetDataReader<SAIM> GetDataSetDataReader(List<SAIM> Entities) { return new SAIMDataReader(new EduHubDataSetLoadedReader<SAIM>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SAIMDataReader : EduHubDataSetDataReader<SAIM> { public SAIMDataReader(IEduHubDataSetReader<SAIM> Reader) : base (Reader) { } public override int FieldCount { get { return 11; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // INVOLVEMENTID return Current.INVOLVEMENTID; case 2: // MEDICATION return Current.MEDICATION; case 3: // STAFF return Current.STAFF; case 4: // ADMIN_BY_OTHER return Current.ADMIN_BY_OTHER; case 5: // ADMIN_TIME return Current.ADMIN_TIME; case 6: // DOSE return Current.DOSE; case 7: // ADMIN_NOTES return Current.ADMIN_NOTES; case 8: // LW_DATE return Current.LW_DATE; case 9: // LW_TIME return Current.LW_TIME; case 10: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // MEDICATION return Current.MEDICATION == null; case 3: // STAFF return Current.STAFF == null; case 4: // ADMIN_BY_OTHER return Current.ADMIN_BY_OTHER == null; case 5: // ADMIN_TIME return Current.ADMIN_TIME == null; case 6: // DOSE return Current.DOSE == null; case 7: // ADMIN_NOTES return Current.ADMIN_NOTES == null; case 8: // LW_DATE return Current.LW_DATE == null; case 9: // LW_TIME return Current.LW_TIME == null; case 10: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // INVOLVEMENTID return "INVOLVEMENTID"; case 2: // MEDICATION return "MEDICATION"; case 3: // STAFF return "STAFF"; case 4: // ADMIN_BY_OTHER return "ADMIN_BY_OTHER"; case 5: // ADMIN_TIME return "ADMIN_TIME"; case 6: // DOSE return "DOSE"; case 7: // ADMIN_NOTES return "ADMIN_NOTES"; case 8: // LW_DATE return "LW_DATE"; case 9: // LW_TIME return "LW_TIME"; case 10: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "INVOLVEMENTID": return 1; case "MEDICATION": return 2; case "STAFF": return 3; case "ADMIN_BY_OTHER": return 4; case "ADMIN_TIME": return 5; case "DOSE": return 6; case "ADMIN_NOTES": return 7; case "LW_DATE": return 8; case "LW_TIME": return 9; case "LW_USER": return 10; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Xunit; namespace Apache.Geode.Client.UnitTests { [Trait("Category", "UnitTests")] public class Tests2 : IDisposable { private readonly Cache _cacheOne; private readonly Cache _cacheTwo; public Tests2() { var cacheFactory = new CacheFactory(); _cacheOne = cacheFactory.Create(); _cacheTwo = cacheFactory.Create(); } public void Dispose() { _cacheOne.Close(); _cacheTwo.Close(); } [Fact] public void RegisterSerializerForTwoCaches() { Assert.NotEqual(_cacheOne, _cacheTwo); var dummyPdxSerializerOne = new DummyPdxSerializer(); _cacheOne.TypeRegistry.PdxSerializer = dummyPdxSerializerOne; var dummyPdxSerializerTwo = new DummyPdxSerializer(); _cacheTwo.TypeRegistry.PdxSerializer = dummyPdxSerializerTwo; var cacheOnePdxSerializer = _cacheOne.TypeRegistry.PdxSerializer; var cacheTwoPdxSerializer = _cacheTwo.TypeRegistry.PdxSerializer; Assert.Same(dummyPdxSerializerOne, cacheOnePdxSerializer); Assert.Same(dummyPdxSerializerTwo, cacheTwoPdxSerializer); Assert.NotSame(cacheOnePdxSerializer, cacheTwoPdxSerializer); } [Fact] public void SetPdxTypeMapper() { var dummyPdxTypeMapper = new DummyPdxTypeMapper(); _cacheOne.TypeRegistry.PdxTypeMapper = dummyPdxTypeMapper; Assert.Same(dummyPdxTypeMapper, _cacheOne.TypeRegistry.PdxTypeMapper); Assert.Null(_cacheTwo.TypeRegistry.PdxTypeMapper); } [Fact] public void GetPdxTypeName() { var dummyPdxTypeMapper = new DummyPdxTypeMapper(); _cacheOne.TypeRegistry.PdxTypeMapper = dummyPdxTypeMapper; var pdxName = _cacheOne.TypeRegistry.GetPdxTypeName("bar"); Assert.Equal("foo", pdxName); Assert.Equal("bar", _cacheTwo.TypeRegistry.GetPdxTypeName("bar")); } [Fact] public void GetLocalTypeName() { var dummyPdxTypeMapper = new DummyPdxTypeMapper(); _cacheOne.TypeRegistry.PdxTypeMapper = dummyPdxTypeMapper; var localName = _cacheOne.TypeRegistry.GetLocalTypeName("foo"); Assert.Equal("bar", localName); Assert.Equal("foo", _cacheTwo.TypeRegistry.GetLocalTypeName("foo")); } private static bool _pdxDelegate1Called; private static IPdxSerializable DelegateForPdx1() { _pdxDelegate1Called = true; return Pdx1.CreateDeserializable(); } private static bool _pdxDelegate2Called; private static IPdxSerializable DelegateForPdx2() { _pdxDelegate2Called = true; return Pdx2.CreateDeserializable(); } [Fact] public void RegisterPdxType() { _cacheOne.TypeRegistry.RegisterPdxType(DelegateForPdx1); _cacheTwo.TypeRegistry.RegisterPdxType(DelegateForPdx2); _pdxDelegate1Called = false; var pdx1Type = _cacheOne.TypeRegistry.GetPdxType(typeof(Pdx1).FullName); Assert.True(_pdxDelegate1Called); _pdxDelegate2Called = false; var pdx2Type = _cacheOne.TypeRegistry.GetPdxType(typeof(Pdx2).FullName); Assert.False(_pdxDelegate2Called); } [Fact] public void SetSniProxy() { PoolFactory poolFactory = _cacheOne.GetPoolFactory() .AddLocator("localhost", 10334) .SetSniProxy("haproxy", 7777); Pool pool = poolFactory.Create("testPool"); string sniProxyHost = pool.SniProxyHost; int sniProxyPort = pool.SniProxyPort; Assert.Equal(sniProxyHost, "haproxy"); Assert.Equal(sniProxyPort, 7777); } private class DummyPdxSerializer : IPdxSerializer { public object FromData(string classname, IPdxReader reader) { throw new NotImplementedException(); } public bool ToData(object o, IPdxWriter writer) { throw new NotImplementedException(); } } private class DummyPdxTypeMapper : IPdxTypeMapper { public string FromPdxTypeName(string pdxTypeName) { return "foo".Equals(pdxTypeName) ? "bar" : null; } public string ToPdxTypeName(string localTypeName) { return "bar".Equals(localTypeName) ? "foo" : null; } } private class Pdx1 : IPdxSerializable { // object fields private int _mId; private string _mPkid; private string _mType; private string _mStatus; private string[] _mNames; private byte[] _mNewVal; private DateTime _mCreationDate; private byte[] _mArrayZeroSize; private byte[] _mArrayNull; public Pdx1() { } public Pdx1(int id, int size, string[] names) { _mNames = names; _mId = id; _mPkid = id.ToString(); _mStatus = (id % 2 == 0) ? "active" : "inactive"; _mType = "type" + (id % 3); if (size > 0) { _mNewVal = new byte[size]; for (var index = 0; index < size; index++) { _mNewVal[index] = (byte) 'B'; } } _mCreationDate = DateTime.Now; _mArrayNull = null; _mArrayZeroSize = new byte[0]; } public void FromData(IPdxReader reader) { _mId = reader.ReadInt("id"); var isIdentity = reader.IsIdentityField("id"); if (isIdentity == false) throw new IllegalStateException("Pdx1 id is identity field"); var isId = reader.HasField("id"); if (isId == false) throw new IllegalStateException("Pdx1 id field not found"); var isNotId = reader.HasField("ID"); if (isNotId) throw new IllegalStateException("Pdx1 isNotId field found"); _mPkid = reader.ReadString("pkid"); _mType = reader.ReadString("type"); _mStatus = reader.ReadString("status"); _mNames = reader.ReadStringArray("names"); _mNewVal = reader.ReadByteArray("newVal"); _mCreationDate = reader.ReadDate("creationDate"); _mArrayNull = reader.ReadByteArray("arrayNull"); _mArrayZeroSize = reader.ReadByteArray("arrayZeroSize"); } public void ToData(IPdxWriter writer) { writer .WriteInt("id", _mId) //identity field .MarkIdentityField("id") .WriteString("pkid", _mPkid) .WriteString("type", _mType) .WriteString("status", _mStatus) .WriteStringArray("names", _mNames) .WriteByteArray("newVal", _mNewVal) .WriteDate("creationDate", _mCreationDate) .WriteByteArray("arrayNull", _mArrayNull) .WriteByteArray("arrayZeroSize", _mArrayZeroSize); } public static IPdxSerializable CreateDeserializable() { return new Pdx1(777, 100, new[] {"LEAF", "Volt", "Bolt"}); } } private class Pdx2 : IPdxSerializable { // object fields private int _mId; private string _mPkid; private string _mPkid2; private string _mType; private string _mStatus; private string _mStatus2; private string[] _mNames; private string[] _mAddresses; private byte[] _mNewVal; private DateTime _mCreationDate; private byte[] _mArrayZeroSize; private byte[] _mArrayNull; public Pdx2() { } public Pdx2(int id, int size, string[] names, string[] addresses) { _mNames = names; _mAddresses = addresses; _mId = id; _mPkid = id.ToString(); _mPkid2 = id + "two"; _mStatus = (id % 2 == 0) ? "active" : "inactive"; _mStatus2 = (id % 3 == 0) ? "red" : "green"; _mType = "type" + (id % 3); if (size > 0) { _mNewVal = new byte[size]; for (var index = 0; index < size; index++) { _mNewVal[index] = (byte) 'B'; } } _mCreationDate = DateTime.Now; _mArrayNull = null; _mArrayZeroSize = new byte[0]; } public void FromData(IPdxReader reader) { _mId = reader.ReadInt("id"); var isIdentity = reader.IsIdentityField("id"); if (isIdentity == false) throw new IllegalStateException("Pdx2 id is identity field"); var isId = reader.HasField("id"); if (isId == false) throw new IllegalStateException("Pdx2 id field not found"); var isNotId = reader.HasField("ID"); if (isNotId) throw new IllegalStateException("Pdx2 isNotId field found"); _mPkid = reader.ReadString("pkid"); _mPkid2 = reader.ReadString("pkid2"); _mType = reader.ReadString("type"); _mStatus = reader.ReadString("status"); _mStatus2 = reader.ReadString("status2"); _mNames = reader.ReadStringArray("names"); _mAddresses = reader.ReadStringArray("addresses"); _mNewVal = reader.ReadByteArray("newVal"); _mCreationDate = reader.ReadDate("creationDate"); _mArrayNull = reader.ReadByteArray("arrayNull"); _mArrayZeroSize = reader.ReadByteArray("arrayZeroSize"); } public void ToData(IPdxWriter writer) { writer .WriteInt("id", _mId) //identity field .MarkIdentityField("id") .WriteString("pkid", _mPkid) .WriteString("pkid2", _mPkid2) .WriteString("type", _mType) .WriteString("status", _mStatus) .WriteString("status2", _mStatus2) .WriteStringArray("names", _mNames) .WriteStringArray("addresses", _mAddresses) .WriteByteArray("newVal", _mNewVal) .WriteDate("creationDate", _mCreationDate) .WriteByteArray("arrayNull", _mArrayNull) .WriteByteArray("arrayZeroSize", _mArrayZeroSize); } public static IPdxSerializable CreateDeserializable() { return new Pdx2(777, 100, new[] {"Nissan", "Chevy", "Volvo"}, new[] {"4451 Court St", "1171 Elgin Ave", "721 NW 173rd Pl"}); } } } }
using UnityEngine; using System.Collections; [System.Serializable] public class tk2dTextMeshData { public int version = 0; public tk2dFontData font; public string text = ""; public Color color = Color.white; public Color color2 = Color.white; public bool useGradient = false; public int textureGradient = 0; public TextAnchor anchor = TextAnchor.LowerLeft; public Vector3 scale = Vector3.one; public bool kerning = false; public int maxChars = 16; public bool inlineStyling = false; public bool formatting = false; public int wordWrapWidth = 0; public float spacing = 0.0f; public float lineSpacing = 0.0f; } [ExecuteInEditMode] [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))] [AddComponentMenu("2D Toolkit/Text/tk2dTextMesh")] /// <summary> /// Text mesh /// </summary> public class tk2dTextMesh : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild { tk2dFontData _fontInst; string _formattedText = ""; // This stuff now kept in tk2dTextMeshData. Remove in future version. [SerializeField] tk2dFontData _font = null; [SerializeField] string _text = ""; [SerializeField] Color _color = Color.white; [SerializeField] Color _color2 = Color.white; [SerializeField] bool _useGradient = false; [SerializeField] int _textureGradient = 0; [SerializeField] TextAnchor _anchor = TextAnchor.LowerLeft; [SerializeField] Vector3 _scale = new Vector3(1.0f, 1.0f, 1.0f); [SerializeField] bool _kerning = false; [SerializeField] int _maxChars = 16; [SerializeField] bool _inlineStyling = false; [SerializeField] bool _formatting = false; [SerializeField] int _wordWrapWidth = 0; [SerializeField] float spacing = 0.0f; [SerializeField] float lineSpacing = 0.0f; // Holding the data in this struct for the next version [SerializeField] tk2dTextMeshData data = new tk2dTextMeshData(); // Batcher needs to grab this public string FormattedText { get {return _formattedText;} } void UpgradeData() { if (data.version != 1) { data.font = _font; data.text = _text; data.color = _color; data.color2 = _color2; data.useGradient = _useGradient; data.textureGradient = _textureGradient; data.anchor = _anchor; data.scale = _scale; data.kerning = _kerning; data.maxChars = _maxChars; data.inlineStyling = _inlineStyling; data.formatting = _formatting; data.wordWrapWidth = _wordWrapWidth; data.spacing = spacing; data.lineSpacing = lineSpacing; } data.version = 1; } Vector3[] vertices; Vector2[] uvs; Vector2[] uv2; Color32[] colors; Color32[] untintedColors; static int GetInlineStyleCommandLength(int cmdSymbol) { int val = 0; switch (cmdSymbol) { case 'c': val = 5; break; // cRGBA case 'C': val = 9; break; // CRRGGBBAA case 'g': val = 9; break; // gRGBARGBA case 'G': val = 17; break; // GRRGGBBAARRGGBBAA } return val; } /// <summary> /// Formats the string using the current settings, and returns the formatted string. /// You can use this if you need to calculate how many lines your string is going to be wrapped to. /// </summary> public string FormatText(string unformattedString) { string returnValue = ""; FormatText(ref returnValue, unformattedString); return returnValue; } void FormatText() { FormatText(ref _formattedText, data.text); } void FormatText(ref string _targetString, string _source) { if (formatting == false || wordWrapWidth == 0 || _fontInst.texelSize == Vector2.zero) { _targetString = _source; return; } float lineWidth = _fontInst.texelSize.x * wordWrapWidth; System.Text.StringBuilder target = new System.Text.StringBuilder(_source.Length); float widthSoFar = 0.0f; float wordStart = 0.0f; int targetWordStartIndex = -1; int fmtWordStartIndex = -1; bool ignoreNextCharacter = false; for (int i = 0; i < _source.Length; ++i) { char idx = _source[i]; tk2dFontChar chr; bool inlineHatChar = (idx == '^'); if (_fontInst.useDictionary) { if (!_fontInst.charDict.ContainsKey(idx)) idx = (char)0; chr = _fontInst.charDict[idx]; } else { if (idx >= _fontInst.chars.Length) idx = (char)0; // should be space chr = _fontInst.chars[idx]; } if (inlineHatChar) idx = '^'; if (ignoreNextCharacter) { ignoreNextCharacter = false; continue; } if (data.inlineStyling && idx == '^' && i + 1 < _source.Length) { if (_source[i + 1] == '^') { ignoreNextCharacter = true; target.Append('^'); // add the second hat that we'll skip } else { int cmdLength = GetInlineStyleCommandLength(_source[i + 1]); int skipLength = 1 + cmdLength; // The ^ plus the command for (int j = 0; j < skipLength; ++j) { if (i + j < _source.Length) { target.Append(_source[i + j]); } } i += skipLength - 1; continue; } } if (idx == '\n') { widthSoFar = 0.0f; wordStart = 0.0f; targetWordStartIndex = target.Length; fmtWordStartIndex = i; } else if (idx == ' '/* || idx == '.' || idx == ',' || idx == ':' || idx == ';' || idx == '!'*/) { /*if ((widthSoFar + chr.p1.x * data.scale.x) > lineWidth) { target.Append('\n'); widthSoFar = chr.advance * data.scale.x; } else {*/ widthSoFar += chr.advance * data.scale.x; //} wordStart = widthSoFar; targetWordStartIndex = target.Length; fmtWordStartIndex = i; } else { if ((widthSoFar + chr.p1.x * data.scale.x) > lineWidth) { // If the last word started after the start of the line if (wordStart > 0.0f) { wordStart = 0.0f; widthSoFar = 0.0f; // rewind target.Remove(targetWordStartIndex + 1, target.Length - targetWordStartIndex - 1); target.Append('\n'); i = fmtWordStartIndex; continue; // don't add this character } else { target.Append('\n'); widthSoFar = chr.advance * data.scale.x; } } else { widthSoFar += chr.advance * data.scale.x; } } target.Append(idx); } _targetString = target.ToString(); } [System.FlagsAttribute] enum UpdateFlags { UpdateNone = 0, UpdateText = 1, // update text vertices & uvs UpdateColors = 2, // only colors have changed UpdateBuffers = 4, // update buffers (maxchars has changed) }; UpdateFlags updateFlags = UpdateFlags.UpdateBuffers; Mesh mesh; MeshFilter meshFilter; // accessors /// <summary>Gets or sets the font. Call <see cref="Commit"/> to commit changes.</summary> public tk2dFontData font { get { UpgradeData(); return data.font; } set { UpgradeData(); data.font = value; _fontInst = data.font.inst; updateFlags |= UpdateFlags.UpdateText; UpdateMaterial(); } } /// <summary>Enables or disables formatting. Call <see cref="Commit"/> to commit changes.</summary> public bool formatting { get { UpgradeData(); return data.formatting; } set { UpgradeData(); if (data.formatting != value) { data.formatting = value; updateFlags |= UpdateFlags.UpdateText; } } } /// <summary>Change word wrap width. This only works when formatting is enabled. /// Call <see cref="Commit"/> to commit changes.</summary> public int wordWrapWidth { get { UpgradeData(); return data.wordWrapWidth; } set { UpgradeData(); if (data.wordWrapWidth != value) { data.wordWrapWidth = value; updateFlags |= UpdateFlags.UpdateText; } } } /// <summary>Gets or sets the text. Call <see cref="Commit"/> to commit changes.</summary> public string text { get { UpgradeData(); return data.text; } set { UpgradeData(); data.text = value; updateFlags |= UpdateFlags.UpdateText; } } /// <summary>Gets or sets the color. Call <see cref="Commit"/> to commit changes.</summary> public Color color { get { UpgradeData(); return data.color; } set { UpgradeData(); data.color = value; updateFlags |= UpdateFlags.UpdateColors; } } /// <summary>Gets or sets the secondary color (used in the gradient). Call <see cref="Commit"/> to commit changes.</summary> public Color color2 { get { UpgradeData(); return data.color2; } set { UpgradeData(); data.color2 = value; updateFlags |= UpdateFlags.UpdateColors; } } /// <summary>Use vertex vertical gradient. Call <see cref="Commit"/> to commit changes.</summary> public bool useGradient { get { UpgradeData(); return data.useGradient; } set { UpgradeData(); data.useGradient = value; updateFlags |= UpdateFlags.UpdateColors; } } /// <summary>Gets or sets the text anchor. Call <see cref="Commit"/> to commit changes.</summary> public TextAnchor anchor { get { UpgradeData(); return data.anchor; } set { UpgradeData(); data.anchor = value; updateFlags |= UpdateFlags.UpdateText; } } /// <summary>Gets or sets the scale. Call <see cref="Commit"/> to commit changes.</summary> public Vector3 scale { get { UpgradeData(); return data.scale; } set { UpgradeData(); data.scale = value; updateFlags |= UpdateFlags.UpdateText; } } /// <summary>Gets or sets kerning state. Call <see cref="Commit"/> to commit changes.</summary> public bool kerning { get { UpgradeData(); return data.kerning; } set { UpgradeData(); data.kerning = value; updateFlags |= UpdateFlags.UpdateText; } } /// <summary>Gets or sets maxChars. Call <see cref="Commit"/> to commit changes. /// NOTE: This will free & allocate memory, avoid using at runtime. /// </summary> public int maxChars { get { UpgradeData(); return data.maxChars; } set { UpgradeData(); data.maxChars = value; updateFlags |= UpdateFlags.UpdateBuffers; } } /// <summary>Gets or sets the default texture gradient. /// You can also change texture gradient inline by using ^1 - ^9 sequences within your text. /// Call <see cref="Commit"/> to commit changes.</summary> public int textureGradient { get { UpgradeData(); return data.textureGradient; } set { UpgradeData(); data.textureGradient = value % font.gradientCount; updateFlags |= UpdateFlags.UpdateText; } } /// <summary>Enables or disables inline styling (texture gradient). Call <see cref="Commit"/> to commit changes.</summary> public bool inlineStyling { get { UpgradeData(); return data.inlineStyling; } set { UpgradeData(); data.inlineStyling = value; updateFlags |= tk2dTextMesh.UpdateFlags.UpdateText; } } /// <summary>Additional spacing between characters. /// This can be negative to bring characters closer together. /// Call <see cref="Commit"/> to commit changes.</summary> public float Spacing { get { UpgradeData(); return data.spacing; } set { UpgradeData(); if (data.spacing != value) { data.spacing = value; updateFlags |= UpdateFlags.UpdateText; } } } /// <summary>Additional line spacing for multieline text. /// This can be negative to bring lines closer together. /// Call <see cref="Commit"/> to commit changes.</summary> public float LineSpacing { get { UpgradeData(); return data.lineSpacing; } set { UpgradeData(); if (data.lineSpacing != value) { data.lineSpacing = value; updateFlags |= UpdateFlags.UpdateText; } } } void InitInstance() { if (_fontInst == null && data.font != null) _fontInst = data.font.inst; } // Use this for initialization void Awake() { UpgradeData(); if (data.font != null) _fontInst = data.font.inst; // force rebuild when awakened, for when the object has been pooled, etc // this is probably not the best way to do it updateFlags = UpdateFlags.UpdateBuffers; if (data.font != null) { Init(); UpdateMaterial(); } } protected void OnDestroy() { if (meshFilter == null) { meshFilter = GetComponent<MeshFilter>(); } if (meshFilter != null) { mesh = meshFilter.sharedMesh; } if (mesh) { DestroyImmediate(mesh, true); meshFilter.mesh = null; } } bool useInlineStyling { get { return inlineStyling && _fontInst.textureGradients; } } /// <summary> /// Returns the number of characters drawn for the currently active string. /// This may be less than string.Length - some characters are used as escape codes for switching texture gradient ^0-^9 /// Also, there might be more characters in the string than have been allocated for the textmesh, in which case /// the string will be truncated. /// </summary> public int NumDrawnCharacters() { int charsDrawn = NumTotalCharacters(); if (charsDrawn > data.maxChars) charsDrawn = data.maxChars; return charsDrawn; } /// <summary> /// Returns the number of characters excluding texture gradient escape codes. /// </summary> public int NumTotalCharacters() { InitInstance(); if ((updateFlags & (UpdateFlags.UpdateText | UpdateFlags.UpdateBuffers)) != 0) FormatText(); int numChars = 0; for (int i = 0; i < _formattedText.Length; ++i) { int idx = _formattedText[i]; bool inlineHatChar = (idx == '^'); if (_fontInst.useDictionary) { if (!_fontInst.charDict.ContainsKey(idx)) idx = 0; } else { if (idx >= _fontInst.chars.Length) idx = 0; // should be space } if (inlineHatChar) idx = '^'; if (idx == '\n') { continue; } else if (data.inlineStyling) { if (idx == '^' && i + 1 < _formattedText.Length) { if (_formattedText[i + 1] == '^') { ++i; } else { i += GetInlineStyleCommandLength(_formattedText[i + 1]); continue; } } } ++numChars; } return numChars; } public Vector2 GetMeshDimensionsForString(string str) { return tk2dTextGeomGen.GetMeshDimensionsForString(str, tk2dTextGeomGen.Data( data, _fontInst, _formattedText )); } public void Init(bool force) { if (force) { updateFlags |= UpdateFlags.UpdateBuffers; } Init(); } public void Init() { if (_fontInst && ((updateFlags & UpdateFlags.UpdateBuffers) != 0 || mesh == null)) { _fontInst.InitDictionary(); FormatText(); var geomData = tk2dTextGeomGen.Data( data, _fontInst, _formattedText ); // volatile data int numVertices; int numIndices; tk2dTextGeomGen.GetTextMeshGeomDesc(out numVertices, out numIndices, geomData); vertices = new Vector3[numVertices]; uvs = new Vector2[numVertices]; colors = new Color32[numVertices]; untintedColors = new Color32[numVertices]; if (_fontInst.textureGradients) { uv2 = new Vector2[numVertices]; } int[] triangles = new int[numIndices]; int target = tk2dTextGeomGen.SetTextMeshGeom(vertices, uvs, uv2, untintedColors, 0, geomData); if (!_fontInst.isPacked) { Color32 topColor = data.color; Color32 bottomColor = data.useGradient ? data.color2 : data.color; for (int i = 0; i < numVertices; ++i) { Color32 c = ((i % 4) < 2) ? topColor : bottomColor; byte red = (byte)(((int)untintedColors[i].r * (int)c.r) / 255); byte green = (byte)(((int)untintedColors[i].g * (int)c.g) / 255); byte blue = (byte)(((int)untintedColors[i].b * (int)c.b) / 255); byte alpha = (byte)(((int)untintedColors[i].a * (int)c.a) / 255); if (_fontInst.premultipliedAlpha) { red = (byte)(((int)red * (int)alpha) / 255); green = (byte)(((int)green * (int)alpha) / 255); blue = (byte)(((int)blue * (int)alpha) / 255); } colors[i] = new Color32(red, green, blue, alpha); } } else { colors = untintedColors; } tk2dTextGeomGen.SetTextMeshIndices(triangles, 0, 0, geomData, target); if (mesh == null) { if (meshFilter == null) meshFilter = GetComponent<MeshFilter>(); mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; meshFilter.mesh = mesh; } else { mesh.Clear(); } mesh.vertices = vertices; mesh.uv = uvs; if (font.textureGradients) { mesh.uv2 = uv2; } mesh.triangles = triangles; mesh.colors32 = colors; mesh.RecalculateBounds(); updateFlags = UpdateFlags.UpdateNone; } } /// <summary> /// Call commit after changing properties to commit the changes. /// This is deffered to a commit call as more than one operation may require rebuilding the buffers, eg. scaling and changing text. /// This will be wasteful if performed multiple times. /// </summary> public void Commit() { // Make sure instance is set up, might not be when calling from Awake. InitInstance(); // make sure fonts dictionary is initialized properly before proceeding _fontInst.InitDictionary(); // Can come in here without anything initalized when // instantiated in code if ((updateFlags & UpdateFlags.UpdateBuffers) != 0 || mesh == null) { Init(); } else { if ((updateFlags & UpdateFlags.UpdateText) != 0) { FormatText(); var geomData = tk2dTextGeomGen.Data( data, _fontInst, _formattedText ); int target = tk2dTextGeomGen.SetTextMeshGeom(vertices, uvs, uv2, untintedColors, 0, geomData); for (int i = target; i < data.maxChars; ++i) { // was/is unnecessary to fill anything else vertices[i * 4 + 0] = vertices[i * 4 + 1] = vertices[i * 4 + 2] = vertices[i * 4 + 3] = Vector3.zero; } mesh.vertices = vertices; mesh.uv = uvs; if (_fontInst.textureGradients) { mesh.uv2 = uv2; } if (_fontInst.isPacked) { colors = untintedColors; mesh.colors32 = colors; } if (data.inlineStyling) { updateFlags |= UpdateFlags.UpdateColors; } mesh.RecalculateBounds(); } if (!font.isPacked && (updateFlags & UpdateFlags.UpdateColors) != 0) // packed fonts don't support tinting { Color32 topColor = data.color; Color32 bottomColor = data.useGradient ? data.color2 : data.color; for (int i = 0; i < colors.Length; ++i) { Color32 c = ((i % 4) < 2) ? topColor : bottomColor; byte red = (byte)(((int)untintedColors[i].r * (int)c.r) / 255); byte green = (byte)(((int)untintedColors[i].g * (int)c.g) / 255); byte blue = (byte)(((int)untintedColors[i].b * (int)c.b) / 255); byte alpha = (byte)(((int)untintedColors[i].a * (int)c.a) / 255); if (_fontInst.premultipliedAlpha) { red = (byte)(((int)red * (int)alpha) / 255); green = (byte)(((int)green * (int)alpha) / 255); blue = (byte)(((int)blue * (int)alpha) / 255); } colors[i] = new Color32(red, green, blue, alpha); } mesh.colors32 = colors; } } updateFlags = UpdateFlags.UpdateNone; } /// <summary> /// Makes the text mesh pixel perfect to the active camera. /// Automatically detects <see cref="tk2dCamera"/> if present /// Otherwise uses Camera.main /// </summary> public void MakePixelPerfect() { float s = 1.0f; if (tk2dCamera.inst != null) { if (_fontInst.version < 1) { Debug.LogError("Need to rebuild font."); } s = _fontInst.invOrthoSize * _fontInst.halfTargetHeight; } else if (Camera.main) { if (Camera.main.orthographic) { s = Camera.main.orthographicSize; } else { float zdist = (transform.position.z - Camera.main.transform.position.z); s = tk2dPixelPerfectHelper.CalculateScaleForPerspectiveCamera(Camera.main.fov, zdist); } } scale = new Vector3(Mathf.Sign(scale.x) * s, Mathf.Sign(scale.y) * s, Mathf.Sign(scale.z) * s); } // tk2dRuntime.ISpriteCollectionEditor public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection) { if (data.font != null && data.font.spriteCollection != null) return data.font.spriteCollection == spriteCollection; // No easy way to identify this at this stage return true; } void UpdateMaterial() { if (GetComponent<Renderer>().sharedMaterial != _fontInst.materialInst) GetComponent<Renderer>().material = _fontInst.materialInst; } public void ForceBuild() { if (data.font != null) { _fontInst = data.font.inst; UpdateMaterial(); } Init(true); } #if UNITY_EDITOR void OnDrawGizmos() { if (mesh != null) { Bounds b = mesh.bounds; Gizmos.color = Color.clear; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(b.center, b.extents * 2); Gizmos.matrix = Matrix4x4.identity; Gizmos.color = Color.white; } } #endif }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Transaction.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Cocopops.Protobuf.Model.Transaction { /// <summary>Holder for reflection information generated from Transaction.proto</summary> public static partial class TransactionReflection { #region Descriptor /// <summary>File descriptor for Transaction.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TransactionReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChFUcmFuc2FjdGlvbi5wcm90bxIXQ29jb3BvcHMuUHJvdG9idWYuTW9kZWwa", "FUJhc2VUcmFuc2FjdGlvbi5wcm90bxoZRXh0ZW5kZWRUcmFuc2FjdGlvbi5w", "cm90byKwAQoLVHJhbnNhY3Rpb24SRAoQYmFzZV90cmFuc2FjdGlvbhgBIAEo", "CzIoLkNvY29wb3BzLlByb3RvYnVmLk1vZGVsLkJhc2VUcmFuc2FjdGlvbkgA", "EkwKFGV4dGVuZGVkX3RyYW5zYWN0aW9uGAIgASgLMiwuQ29jb3BvcHMuUHJv", "dG9idWYuTW9kZWwuRXh0ZW5kZWRUcmFuc2FjdGlvbkgAQg0KC3RyYW5zYWN0", "aW9uQiaqAiNDb2NvcG9wcy5Qcm90b2J1Zi5Nb2RlbC5UcmFuc2FjdGlvbmIG", "cHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Cocopops.Protobuf.Model.BaseTransaction.BaseTransactionReflection.Descriptor, global::Cocopops.Protobuf.Model.ExtendedTransaction.ExtendedTransactionReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Cocopops.Protobuf.Model.Transaction.Transaction), global::Cocopops.Protobuf.Model.Transaction.Transaction.Parser, new[]{ "BaseTransaction", "ExtendedTransaction" }, new[]{ "Transaction" }, null, null) })); } #endregion } #region Messages public sealed partial class Transaction : pb::IMessage<Transaction> { private static readonly pb::MessageParser<Transaction> _parser = new pb::MessageParser<Transaction>(() => new Transaction()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Transaction> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Cocopops.Protobuf.Model.Transaction.TransactionReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Transaction() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Transaction(Transaction other) : this() { switch (other.TransactionCase) { case TransactionOneofCase.BaseTransaction: BaseTransaction = other.BaseTransaction.Clone(); break; case TransactionOneofCase.ExtendedTransaction: ExtendedTransaction = other.ExtendedTransaction.Clone(); break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Transaction Clone() { return new Transaction(this); } /// <summary>Field number for the "base_transaction" field.</summary> public const int BaseTransactionFieldNumber = 1; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Cocopops.Protobuf.Model.BaseTransaction.BaseTransaction BaseTransaction { get { return transactionCase_ == TransactionOneofCase.BaseTransaction ? (global::Cocopops.Protobuf.Model.BaseTransaction.BaseTransaction) transaction_ : null; } set { transaction_ = value; transactionCase_ = value == null ? TransactionOneofCase.None : TransactionOneofCase.BaseTransaction; } } /// <summary>Field number for the "extended_transaction" field.</summary> public const int ExtendedTransactionFieldNumber = 2; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Cocopops.Protobuf.Model.ExtendedTransaction.ExtendedTransaction ExtendedTransaction { get { return transactionCase_ == TransactionOneofCase.ExtendedTransaction ? (global::Cocopops.Protobuf.Model.ExtendedTransaction.ExtendedTransaction) transaction_ : null; } set { transaction_ = value; transactionCase_ = value == null ? TransactionOneofCase.None : TransactionOneofCase.ExtendedTransaction; } } private object transaction_; /// <summary>Enum of possible cases for the "transaction" oneof.</summary> public enum TransactionOneofCase { None = 0, BaseTransaction = 1, ExtendedTransaction = 2, } private TransactionOneofCase transactionCase_ = TransactionOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TransactionOneofCase TransactionCase { get { return transactionCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearTransaction() { transactionCase_ = TransactionOneofCase.None; transaction_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Transaction); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Transaction other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(BaseTransaction, other.BaseTransaction)) return false; if (!object.Equals(ExtendedTransaction, other.ExtendedTransaction)) return false; if (TransactionCase != other.TransactionCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (transactionCase_ == TransactionOneofCase.BaseTransaction) hash ^= BaseTransaction.GetHashCode(); if (transactionCase_ == TransactionOneofCase.ExtendedTransaction) hash ^= ExtendedTransaction.GetHashCode(); hash ^= (int) transactionCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (transactionCase_ == TransactionOneofCase.BaseTransaction) { output.WriteRawTag(10); output.WriteMessage(BaseTransaction); } if (transactionCase_ == TransactionOneofCase.ExtendedTransaction) { output.WriteRawTag(18); output.WriteMessage(ExtendedTransaction); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (transactionCase_ == TransactionOneofCase.BaseTransaction) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(BaseTransaction); } if (transactionCase_ == TransactionOneofCase.ExtendedTransaction) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(ExtendedTransaction); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Transaction other) { if (other == null) { return; } switch (other.TransactionCase) { case TransactionOneofCase.BaseTransaction: BaseTransaction = other.BaseTransaction; break; case TransactionOneofCase.ExtendedTransaction: ExtendedTransaction = other.ExtendedTransaction; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { global::Cocopops.Protobuf.Model.BaseTransaction.BaseTransaction subBuilder = new global::Cocopops.Protobuf.Model.BaseTransaction.BaseTransaction(); if (transactionCase_ == TransactionOneofCase.BaseTransaction) { subBuilder.MergeFrom(BaseTransaction); } input.ReadMessage(subBuilder); BaseTransaction = subBuilder; break; } case 18: { global::Cocopops.Protobuf.Model.ExtendedTransaction.ExtendedTransaction subBuilder = new global::Cocopops.Protobuf.Model.ExtendedTransaction.ExtendedTransaction(); if (transactionCase_ == TransactionOneofCase.ExtendedTransaction) { subBuilder.MergeFrom(ExtendedTransaction); } input.ReadMessage(subBuilder); ExtendedTransaction = subBuilder; break; } } } } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Diagnostics; using System.Data.SqlTypes; using System.Globalization; using System.Runtime.InteropServices; namespace System.Data.SqlClient { internal sealed class SqlBuffer { internal enum StorageType { Empty = 0, Boolean, Byte, DateTime, Decimal, Double, Int16, Int32, Int64, Guid, Money, Single, String, SqlBinary, SqlCachedBuffer, SqlGuid, SqlXml, Date, DateTime2, DateTimeOffset, Time, } internal struct DateTimeInfo { // This is used to store DateTime internal int daypart; internal int timepart; } internal struct NumericInfo { // This is used to store Decimal data internal int data1; internal int data2; internal int data3; internal int data4; internal byte precision; internal byte scale; internal bool positive; } internal struct TimeInfo { internal long ticks; internal byte scale; } internal struct DateTime2Info { internal int date; internal TimeInfo timeInfo; } internal struct DateTimeOffsetInfo { internal DateTime2Info dateTime2Info; internal short offset; } [StructLayout(LayoutKind.Explicit)] internal struct Storage { [FieldOffset(0)] internal bool _boolean; [FieldOffset(0)] internal byte _byte; [FieldOffset(0)] internal DateTimeInfo _dateTimeInfo; [FieldOffset(0)] internal double _double; [FieldOffset(0)] internal NumericInfo _numericInfo; [FieldOffset(0)] internal short _int16; [FieldOffset(0)] internal int _int32; [FieldOffset(0)] internal long _int64; // also used to store Money, UtcDateTime, Date , and Time [FieldOffset(0)] internal Guid _guid; [FieldOffset(0)] internal float _single; [FieldOffset(0)] internal TimeInfo _timeInfo; [FieldOffset(0)] internal DateTime2Info _dateTime2Info; [FieldOffset(0)] internal DateTimeOffsetInfo _dateTimeOffsetInfo; } private bool _isNull; private StorageType _type; private Storage _value; private object _object; // String, SqlBinary, SqlCachedBuffer, SqlGuid, SqlString, SqlXml internal SqlBuffer() { } private SqlBuffer(SqlBuffer value) { // Clone // value types _isNull = value._isNull; _type = value._type; // ref types - should also be read only unless at some point we allow this data // to be mutable, then we will need to copy _value = value._value; _object = value._object; } internal bool IsEmpty { get { return (StorageType.Empty == _type); } } internal bool IsNull { get { return _isNull; } } internal StorageType VariantInternalStorageType { get { return _type; } } internal bool Boolean { get { ThrowIfNull(); if (StorageType.Boolean == _type) { return _value._boolean; } return (bool)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert(IsEmpty, "setting value a second time?"); _value._boolean = value; _type = StorageType.Boolean; _isNull = false; } } internal byte Byte { get { ThrowIfNull(); if (StorageType.Byte == _type) { return _value._byte; } return (byte)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert(IsEmpty, "setting value a second time?"); _value._byte = value; _type = StorageType.Byte; _isNull = false; } } internal byte[] ByteArray { get { ThrowIfNull(); return this.SqlBinary.Value; } } internal DateTime DateTime { get { ThrowIfNull(); if (StorageType.Date == _type) { return DateTime.MinValue.AddDays(_value._int32); } if (StorageType.DateTime2 == _type) { return new DateTime(GetTicksFromDateTime2Info(_value._dateTime2Info)); } if (StorageType.DateTime == _type) { return SqlTypeWorkarounds.SqlDateTimeToDateTime(_value._dateTimeInfo.daypart, _value._dateTimeInfo.timepart); } return (DateTime)this.Value; // anything else we haven't thought of goes through boxing. } } internal decimal Decimal { get { ThrowIfNull(); if (StorageType.Decimal == _type) { if (_value._numericInfo.data4 != 0 || _value._numericInfo.scale > 28) { throw new OverflowException(SQLResource.ConversionOverflowMessage); } return new decimal(_value._numericInfo.data1, _value._numericInfo.data2, _value._numericInfo.data3, !_value._numericInfo.positive, _value._numericInfo.scale); } if (StorageType.Money == _type) { long l = _value._int64; bool isNegative = false; if (l < 0) { isNegative = true; l = -l; } return new decimal((int)(l & 0xffffffff), (int)(l >> 32), 0, isNegative, 4); } return (decimal)this.Value; // anything else we haven't thought of goes through boxing. } } internal double Double { get { ThrowIfNull(); if (StorageType.Double == _type) { return _value._double; } return (double)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert(IsEmpty, "setting value a second time?"); _value._double = value; _type = StorageType.Double; _isNull = false; } } internal Guid Guid { get { ThrowIfNull(); if (StorageType.Guid == _type) { return _value._guid; } else if (StorageType.SqlGuid == _type) { return ((SqlGuid)_object).Value; } return (Guid)this.Value; } set { Debug.Assert(IsEmpty, "setting value a second time?"); _type = StorageType.Guid; _value._guid = value; _isNull = false; } } internal short Int16 { get { ThrowIfNull(); if (StorageType.Int16 == _type) { return _value._int16; } return (short)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert(IsEmpty, "setting value a second time?"); _value._int16 = value; _type = StorageType.Int16; _isNull = false; } } internal int Int32 { get { ThrowIfNull(); if (StorageType.Int32 == _type) { return _value._int32; } return (int)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert(IsEmpty, "setting value a second time?"); _value._int32 = value; _type = StorageType.Int32; _isNull = false; } } internal long Int64 { get { ThrowIfNull(); if (StorageType.Int64 == _type) { return _value._int64; } return (long)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert(IsEmpty, "setting value a second time?"); _value._int64 = value; _type = StorageType.Int64; _isNull = false; } } internal float Single { get { ThrowIfNull(); if (StorageType.Single == _type) { return _value._single; } return (float)this.Value; // anything else we haven't thought of goes through boxing. } set { Debug.Assert(IsEmpty, "setting value a second time?"); _value._single = value; _type = StorageType.Single; _isNull = false; } } internal string String { get { ThrowIfNull(); if (StorageType.String == _type) { return (string)_object; } else if (StorageType.SqlCachedBuffer == _type) { return ((SqlCachedBuffer)(_object)).ToString(); } return (string)this.Value; // anything else we haven't thought of goes through boxing. } } // use static list of format strings indexed by scale for perf private static readonly string[] s_katmaiDateTimeOffsetFormatByScale = new string[] { "yyyy-MM-dd HH:mm:ss zzz", "yyyy-MM-dd HH:mm:ss.f zzz", "yyyy-MM-dd HH:mm:ss.ff zzz", "yyyy-MM-dd HH:mm:ss.fff zzz", "yyyy-MM-dd HH:mm:ss.ffff zzz", "yyyy-MM-dd HH:mm:ss.fffff zzz", "yyyy-MM-dd HH:mm:ss.ffffff zzz", "yyyy-MM-dd HH:mm:ss.fffffff zzz", }; private static readonly string[] s_katmaiDateTime2FormatByScale = new string[] { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.f", "yyyy-MM-dd HH:mm:ss.ff", "yyyy-MM-dd HH:mm:ss.fff", "yyyy-MM-dd HH:mm:ss.ffff", "yyyy-MM-dd HH:mm:ss.fffff", "yyyy-MM-dd HH:mm:ss.ffffff", "yyyy-MM-dd HH:mm:ss.fffffff", }; private static readonly string[] s_katmaiTimeFormatByScale = new string[] { "HH:mm:ss", "HH:mm:ss.f", "HH:mm:ss.ff", "HH:mm:ss.fff", "HH:mm:ss.ffff", "HH:mm:ss.fffff", "HH:mm:ss.ffffff", "HH:mm:ss.fffffff", }; internal string KatmaiDateTimeString { get { ThrowIfNull(); if (StorageType.Date == _type) { return this.DateTime.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo); } if (StorageType.Time == _type) { byte scale = _value._timeInfo.scale; return new DateTime(_value._timeInfo.ticks).ToString(s_katmaiTimeFormatByScale[scale], DateTimeFormatInfo.InvariantInfo); } if (StorageType.DateTime2 == _type) { byte scale = _value._dateTime2Info.timeInfo.scale; return this.DateTime.ToString(s_katmaiDateTime2FormatByScale[scale], DateTimeFormatInfo.InvariantInfo); } if (StorageType.DateTimeOffset == _type) { DateTimeOffset dto = this.DateTimeOffset; byte scale = _value._dateTimeOffsetInfo.dateTime2Info.timeInfo.scale; return dto.ToString(s_katmaiDateTimeOffsetFormatByScale[scale], DateTimeFormatInfo.InvariantInfo); } return (string)this.Value; // anything else we haven't thought of goes through boxing. } } internal SqlString KatmaiDateTimeSqlString { get { if (StorageType.Date == _type || StorageType.Time == _type || StorageType.DateTime2 == _type || StorageType.DateTimeOffset == _type) { if (IsNull) { return SqlString.Null; } return new SqlString(KatmaiDateTimeString); } return (SqlString)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal TimeSpan Time { get { ThrowIfNull(); if (StorageType.Time == _type) { return new TimeSpan(_value._timeInfo.ticks); } return (TimeSpan)this.Value; // anything else we haven't thought of goes through boxing. } } internal DateTimeOffset DateTimeOffset { get { ThrowIfNull(); if (StorageType.DateTimeOffset == _type) { TimeSpan offset = new TimeSpan(0, _value._dateTimeOffsetInfo.offset, 0); // datetime part presents time in UTC return new DateTimeOffset(GetTicksFromDateTime2Info(_value._dateTimeOffsetInfo.dateTime2Info) + offset.Ticks, offset); } return (DateTimeOffset)this.Value; // anything else we haven't thought of goes through boxing. } } private static long GetTicksFromDateTime2Info(DateTime2Info dateTime2Info) { return (dateTime2Info.date * TimeSpan.TicksPerDay + dateTime2Info.timeInfo.ticks); } internal SqlBinary SqlBinary { get { if (StorageType.SqlBinary == _type) { return (SqlBinary)_object; } return (SqlBinary)this.SqlValue; // anything else we haven't thought of goes through boxing. } set { Debug.Assert(IsEmpty, "setting value a second time?"); _object = value; _type = StorageType.SqlBinary; _isNull = value.IsNull; } } internal SqlBoolean SqlBoolean { get { if (StorageType.Boolean == _type) { if (IsNull) { return SqlBoolean.Null; } return new SqlBoolean(_value._boolean); } return (SqlBoolean)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlByte SqlByte { get { if (StorageType.Byte == _type) { if (IsNull) { return SqlByte.Null; } return new SqlByte(_value._byte); } return (SqlByte)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlCachedBuffer SqlCachedBuffer { get { if (StorageType.SqlCachedBuffer == _type) { if (IsNull) { return SqlCachedBuffer.Null; } return (SqlCachedBuffer)_object; } return (SqlCachedBuffer)this.SqlValue; // anything else we haven't thought of goes through boxing. } set { Debug.Assert(IsEmpty, "setting value a second time?"); _object = value; _type = StorageType.SqlCachedBuffer; _isNull = value.IsNull; } } internal SqlXml SqlXml { get { if (StorageType.SqlXml == _type) { if (IsNull) { return SqlXml.Null; } return (SqlXml)_object; } return (SqlXml)this.SqlValue; // anything else we haven't thought of goes through boxing. } set { Debug.Assert(IsEmpty, "setting value a second time?"); _object = value; _type = StorageType.SqlXml; _isNull = value.IsNull; } } internal SqlDateTime SqlDateTime { get { if (StorageType.DateTime == _type) { if (IsNull) { return SqlDateTime.Null; } return new SqlDateTime(_value._dateTimeInfo.daypart, _value._dateTimeInfo.timepart); } return (SqlDateTime)SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlDecimal SqlDecimal { get { if (StorageType.Decimal == _type) { if (IsNull) { return SqlDecimal.Null; } return new SqlDecimal(_value._numericInfo.precision, _value._numericInfo.scale, _value._numericInfo.positive, _value._numericInfo.data1, _value._numericInfo.data2, _value._numericInfo.data3, _value._numericInfo.data4 ); } return (SqlDecimal)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlDouble SqlDouble { get { if (StorageType.Double == _type) { if (IsNull) { return SqlDouble.Null; } return new SqlDouble(_value._double); } return (SqlDouble)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlGuid SqlGuid { get { if (StorageType.Guid == _type) { return new SqlGuid(_value._guid); } else if (StorageType.SqlGuid == _type) { return IsNull ? SqlGuid.Null : (SqlGuid)_object; } return (SqlGuid)this.SqlValue; // anything else we haven't thought of goes through boxing. } set { Debug.Assert(IsEmpty, "setting value a second time?"); _object = value; _type = StorageType.SqlGuid; _isNull = value.IsNull; } } internal SqlInt16 SqlInt16 { get { if (StorageType.Int16 == _type) { if (IsNull) { return SqlInt16.Null; } return new SqlInt16(_value._int16); } return (SqlInt16)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlInt32 SqlInt32 { get { if (StorageType.Int32 == _type) { if (IsNull) { return SqlInt32.Null; } return new SqlInt32(_value._int32); } return (SqlInt32)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlInt64 SqlInt64 { get { if (StorageType.Int64 == _type) { if (IsNull) { return SqlInt64.Null; } return new SqlInt64(_value._int64); } return (SqlInt64)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlMoney SqlMoney { get { if (StorageType.Money == _type) { if (IsNull) { return SqlMoney.Null; } return SqlTypeWorkarounds.SqlMoneyCtor(_value._int64, 1/*ignored*/); } return (SqlMoney)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlSingle SqlSingle { get { if (StorageType.Single == _type) { if (IsNull) { return SqlSingle.Null; } return new SqlSingle(_value._single); } return (SqlSingle)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal SqlString SqlString { get { if (StorageType.String == _type) { if (IsNull) { return SqlString.Null; } return new SqlString((string)_object); } else if (StorageType.SqlCachedBuffer == _type) { SqlCachedBuffer data = (SqlCachedBuffer)(_object); if (data.IsNull) { return SqlString.Null; } return data.ToSqlString(); } return (SqlString)this.SqlValue; // anything else we haven't thought of goes through boxing. } } internal object SqlValue { get { switch (_type) { case StorageType.Empty: return DBNull.Value; case StorageType.Boolean: return SqlBoolean; case StorageType.Byte: return SqlByte; case StorageType.DateTime: return SqlDateTime; case StorageType.Decimal: return SqlDecimal; case StorageType.Double: return SqlDouble; case StorageType.Int16: return SqlInt16; case StorageType.Int32: return SqlInt32; case StorageType.Int64: return SqlInt64; case StorageType.Guid: return SqlGuid; case StorageType.Money: return SqlMoney; case StorageType.Single: return SqlSingle; case StorageType.String: return SqlString; case StorageType.SqlCachedBuffer: { SqlCachedBuffer data = (SqlCachedBuffer)(_object); if (data.IsNull) { return SqlXml.Null; } return data.ToSqlXml(); } case StorageType.SqlBinary: case StorageType.SqlGuid: return _object; case StorageType.SqlXml: if (_isNull) { return SqlXml.Null; } Debug.Assert(null != _object); return (SqlXml)_object; case StorageType.Date: case StorageType.DateTime2: if (_isNull) { return DBNull.Value; } return DateTime; case StorageType.DateTimeOffset: if (_isNull) { return DBNull.Value; } return DateTimeOffset; case StorageType.Time: if (_isNull) { return DBNull.Value; } return Time; } return null; // need to return the value as an object of some SQL type } } private static readonly object s_cachedTrueObject = true; private static readonly object s_cachedFalseObject = false; internal object Value { get { if (IsNull) { return DBNull.Value; } switch (_type) { case StorageType.Empty: return DBNull.Value; case StorageType.Boolean: return Boolean ? s_cachedTrueObject : s_cachedFalseObject; case StorageType.Byte: return Byte; case StorageType.DateTime: return DateTime; case StorageType.Decimal: return Decimal; case StorageType.Double: return Double; case StorageType.Int16: return Int16; case StorageType.Int32: return Int32; case StorageType.Int64: return Int64; case StorageType.Guid: return Guid; case StorageType.Money: return Decimal; case StorageType.Single: return Single; case StorageType.String: return String; case StorageType.SqlBinary: return ByteArray; case StorageType.SqlCachedBuffer: { // If we have a CachedBuffer, it's because it's an XMLTYPE column // and we have to return a string when they're asking for the CLS // value of the column. return ((SqlCachedBuffer)(_object)).ToString(); } case StorageType.SqlGuid: return Guid; case StorageType.SqlXml: { // XMLTYPE columns must be returned as string when asking for the CLS value SqlXml data = (SqlXml)_object; string s = data.Value; return s; } case StorageType.Date: return DateTime; case StorageType.DateTime2: return DateTime; case StorageType.DateTimeOffset: return DateTimeOffset; case StorageType.Time: return Time; } return null; // need to return the value as an object of some CLS type } } internal Type GetTypeFromStorageType(bool isSqlType) { if (isSqlType) { switch (_type) { case StorageType.Empty: return null; case StorageType.Boolean: return typeof(SqlBoolean); case StorageType.Byte: return typeof(SqlByte); case StorageType.DateTime: return typeof(SqlDateTime); case StorageType.Decimal: return typeof(SqlDecimal); case StorageType.Double: return typeof(SqlDouble); case StorageType.Int16: return typeof(SqlInt16); case StorageType.Int32: return typeof(SqlInt32); case StorageType.Int64: return typeof(SqlInt64); case StorageType.Guid: return typeof(SqlGuid); case StorageType.Money: return typeof(SqlMoney); case StorageType.Single: return typeof(SqlSingle); case StorageType.String: return typeof(SqlString); case StorageType.SqlCachedBuffer: return typeof(SqlString); case StorageType.SqlBinary: return typeof(object); case StorageType.SqlGuid: return typeof(SqlGuid); case StorageType.SqlXml: return typeof(SqlXml); // Date DateTime2 and DateTimeOffset have no direct Sql type to contain them } } else { //Is CLR Type switch (_type) { case StorageType.Empty: return null; case StorageType.Boolean: return typeof(bool); case StorageType.Byte: return typeof(byte); case StorageType.DateTime: return typeof(DateTime); case StorageType.Decimal: return typeof(decimal); case StorageType.Double: return typeof(double); case StorageType.Int16: return typeof(short); case StorageType.Int32: return typeof(int); case StorageType.Int64: return typeof(long); case StorageType.Guid: return typeof(Guid); case StorageType.Money: return typeof(decimal); case StorageType.Single: return typeof(float); case StorageType.String: return typeof(string); case StorageType.SqlBinary: return typeof(byte[]); case StorageType.SqlCachedBuffer: return typeof(string); case StorageType.SqlGuid: return typeof(Guid); case StorageType.SqlXml: return typeof(string); case StorageType.Date: return typeof(DateTime); case StorageType.DateTime2: return typeof(DateTime); case StorageType.DateTimeOffset: return typeof(DateTimeOffset); } } return null; // need to return the value as an object of some CLS type } internal static SqlBuffer[] CreateBufferArray(int length) { SqlBuffer[] buffers = new SqlBuffer[length]; for (int i = 0; i < buffers.Length; ++i) { buffers[i] = new SqlBuffer(); } return buffers; } internal static SqlBuffer[] CloneBufferArray(SqlBuffer[] values) { SqlBuffer[] copy = new SqlBuffer[values.Length]; for (int i = 0; i < values.Length; i++) { copy[i] = new SqlBuffer(values[i]); } return copy; } internal static void Clear(SqlBuffer[] values) { if (null != values) { for (int i = 0; i < values.Length; ++i) { values[i].Clear(); } } } internal void Clear() { _isNull = false; _type = StorageType.Empty; _object = null; } internal void SetToDateTime(int daypart, int timepart) { Debug.Assert(IsEmpty, "setting value a second time?"); _value._dateTimeInfo.daypart = daypart; _value._dateTimeInfo.timepart = timepart; _type = StorageType.DateTime; _isNull = false; } internal void SetToDecimal(byte precision, byte scale, bool positive, int[] bits) { Debug.Assert(IsEmpty, "setting value a second time?"); _value._numericInfo.precision = precision; _value._numericInfo.scale = scale; _value._numericInfo.positive = positive; _value._numericInfo.data1 = bits[0]; _value._numericInfo.data2 = bits[1]; _value._numericInfo.data3 = bits[2]; _value._numericInfo.data4 = bits[3]; _type = StorageType.Decimal; _isNull = false; } internal void SetToMoney(long value) { Debug.Assert(IsEmpty, "setting value a second time?"); _value._int64 = value; _type = StorageType.Money; _isNull = false; } internal void SetToNullOfType(StorageType storageType) { Debug.Assert(IsEmpty, "setting value a second time?"); _type = storageType; _isNull = true; _object = null; } internal void SetToString(string value) { Debug.Assert(IsEmpty, "setting value a second time?"); _object = value; _type = StorageType.String; _isNull = false; } internal void SetToDate(ReadOnlySpan<byte> bytes) { Debug.Assert(IsEmpty, "setting value a second time?"); _type = StorageType.Date; _value._int32 = GetDateFromByteArray(bytes); _isNull = false; } internal void SetToTime(ReadOnlySpan<byte> bytes, byte scale) { Debug.Assert(IsEmpty, "setting value a second time?"); _type = StorageType.Time; FillInTimeInfo(ref _value._timeInfo, bytes, scale); _isNull = false; } internal void SetToDateTime2(ReadOnlySpan<byte> bytes, byte scale) { Debug.Assert(IsEmpty, "setting value a second time?"); int length = bytes.Length; _type = StorageType.DateTime2; FillInTimeInfo(ref _value._dateTime2Info.timeInfo, bytes.Slice(0, length - 3), scale); // remaining 3 bytes is for date _value._dateTime2Info.date = GetDateFromByteArray(bytes.Slice(length - 3)); // 3 bytes for date _isNull = false; } internal void SetToDateTimeOffset(ReadOnlySpan<byte> bytes, byte scale) { Debug.Assert(IsEmpty, "setting value a second time?"); int length = bytes.Length; _type = StorageType.DateTimeOffset; FillInTimeInfo(ref _value._dateTimeOffsetInfo.dateTime2Info.timeInfo, bytes.Slice(0, length - 5), scale); // remaining 5 bytes are for date and offset _value._dateTimeOffsetInfo.dateTime2Info.date = GetDateFromByteArray(bytes.Slice(length - 5)); // 3 bytes for date _value._dateTimeOffsetInfo.offset = (short)(bytes[length - 2] + (bytes[length - 1] << 8)); // 2 bytes for offset (Int16) _isNull = false; } private static void FillInTimeInfo(ref TimeInfo timeInfo, ReadOnlySpan<byte> timeBytes, byte scale) { int length = timeBytes.Length; Debug.Assert(3 <= length && length <= 5, "invalid data length for timeInfo: " + length); Debug.Assert(0 <= scale && scale <= 7, "invalid scale: " + scale); long tickUnits = (long)timeBytes[0] + ((long)timeBytes[1] << 8) + ((long)timeBytes[2] << 16); if (length > 3) { tickUnits += ((long)timeBytes[3] << 24); } if (length > 4) { tickUnits += ((long)timeBytes[4] << 32); } timeInfo.ticks = tickUnits * TdsEnums.TICKS_FROM_SCALE[scale]; timeInfo.scale = scale; } private static int GetDateFromByteArray(ReadOnlySpan<byte> buf) { byte thirdByte = buf[2]; // reordered to optimize JIT generated bounds checks to a single instance, review generated asm before changing return buf[0] + (buf[1] << 8) + (thirdByte << 16); } private void ThrowIfNull() { if (IsNull) { throw new SqlNullValueException(); } } // [Field]As<T> method explanation: // these methods are used to bridge generic to non-generic access to value type fields on the storage struct // where typeof(T) == typeof(field) // 1) RyuJIT will recognise the pattern of (T)(object)T as being redundant and eliminate // the T and object casts leaving T, so while this looks like it will put every value type instance in a box the // enerated assembly will be short and direct // 2) another jit may not recognise the pattern and should emit the code as seen. this will box and then unbox the // value type which is no worse than the mechanism that this code replaces // where typeof(T) != typeof(field) // the jit will emit all the cast operations as written. this will put the value into a box and then attempt to // cast it, because it is an object even no conversions are use and this will generate the desired InvalidCastException // so users cannot widen a short to an int preserving external expectations internal T ByteAs<T>() { ThrowIfNull(); return (T)(object)_value._byte; } internal T BooleanAs<T>() { ThrowIfNull(); return (T)(object)_value._boolean; } internal T Int32As<T>() { ThrowIfNull(); return (T)(object)_value._int32; } internal T Int16As<T>() { ThrowIfNull(); return (T)(object)_value._int16; } internal T Int64As<T>() { ThrowIfNull(); return (T)(object)_value._int64; } internal T DoubleAs<T>() { ThrowIfNull(); return (T)(object)_value._double; } internal T SingleAs<T>() { ThrowIfNull(); return (T)(object)_value._single; } } }// namespace
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using Neo.Cryptography.ECC; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.SmartContract.Native; using Neo.VM.Types; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Numerics; using Array = Neo.VM.Types.Array; namespace Neo.SmartContract { partial class ApplicationEngine { /// <summary> /// The maximum length of event name. /// </summary> public const int MaxEventName = 32; /// <summary> /// The maximum size of notification objects. /// </summary> public const int MaxNotificationSize = 1024; /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.Platform. /// Gets the name of the current platform. /// </summary> public static readonly InteropDescriptor System_Runtime_Platform = Register("System.Runtime.Platform", nameof(GetPlatform), 1 << 3, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.GetNetwork. /// Gets the magic number of the current network. /// </summary> public static readonly InteropDescriptor System_Runtime_GetNetwork = Register("System.Runtime.GetNetwork", nameof(GetNetwork), 1 << 3, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.GetTrigger. /// Gets the trigger of the execution. /// </summary> public static readonly InteropDescriptor System_Runtime_GetTrigger = Register("System.Runtime.GetTrigger", nameof(Trigger), 1 << 3, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.GetTime. /// Gets the timestamp of the current block. /// </summary> public static readonly InteropDescriptor System_Runtime_GetTime = Register("System.Runtime.GetTime", nameof(GetTime), 1 << 3, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.GetScriptContainer. /// Gets the current script container. /// </summary> public static readonly InteropDescriptor System_Runtime_GetScriptContainer = Register("System.Runtime.GetScriptContainer", nameof(GetScriptContainer), 1 << 3, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.GetExecutingScriptHash. /// Gets the script hash of the current context. /// </summary> public static readonly InteropDescriptor System_Runtime_GetExecutingScriptHash = Register("System.Runtime.GetExecutingScriptHash", nameof(CurrentScriptHash), 1 << 4, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.GetCallingScriptHash. /// Gets the script hash of the calling contract. /// </summary> public static readonly InteropDescriptor System_Runtime_GetCallingScriptHash = Register("System.Runtime.GetCallingScriptHash", nameof(CallingScriptHash), 1 << 4, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.GetEntryScriptHash. /// Gets the script hash of the entry context. /// </summary> public static readonly InteropDescriptor System_Runtime_GetEntryScriptHash = Register("System.Runtime.GetEntryScriptHash", nameof(EntryScriptHash), 1 << 4, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.CheckWitness. /// Determines whether the specified account has witnessed the current transaction. /// </summary> public static readonly InteropDescriptor System_Runtime_CheckWitness = Register("System.Runtime.CheckWitness", nameof(CheckWitness), 1 << 10, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.GetInvocationCounter. /// Gets the number of times the current contract has been called during the execution. /// </summary> public static readonly InteropDescriptor System_Runtime_GetInvocationCounter = Register("System.Runtime.GetInvocationCounter", nameof(GetInvocationCounter), 1 << 4, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.GetRandom. /// Gets the random number generated from the VRF. /// </summary> public static readonly InteropDescriptor System_Runtime_GetRandom = Register("System.Runtime.GetRandom", nameof(GetRandom), 1 << 4, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.Log. /// Writes a log. /// </summary> public static readonly InteropDescriptor System_Runtime_Log = Register("System.Runtime.Log", nameof(RuntimeLog), 1 << 15, CallFlags.AllowNotify); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.Notify. /// Sends a notification. /// </summary> public static readonly InteropDescriptor System_Runtime_Notify = Register("System.Runtime.Notify", nameof(RuntimeNotify), 1 << 15, CallFlags.AllowNotify); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.GetNotifications. /// Gets the notifications sent by the specified contract during the execution. /// </summary> public static readonly InteropDescriptor System_Runtime_GetNotifications = Register("System.Runtime.GetNotifications", nameof(GetNotifications), 1 << 8, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.GasLeft. /// Gets the remaining GAS that can be spent in order to complete the execution. /// </summary> public static readonly InteropDescriptor System_Runtime_GasLeft = Register("System.Runtime.GasLeft", nameof(GasLeft), 1 << 4, CallFlags.None); /// <summary> /// The <see cref="InteropDescriptor"/> of System.Runtime.BurnGas. /// Burning GAS to benefit the NEO ecosystem. /// </summary> public static readonly InteropDescriptor System_Runtime_BurnGas = Register("System.Runtime.BurnGas", nameof(BurnGas), 1 << 4, CallFlags.None); /// <summary> /// The implementation of System.Runtime.Platform. /// Gets the name of the current platform. /// </summary> /// <returns>It always returns "NEO".</returns> internal protected static string GetPlatform() { return "NEO"; } /// <summary> /// The implementation of System.Runtime.GetNetwork. /// Gets the magic number of the current network. /// </summary> /// <returns>The magic number of the current network.</returns> internal protected uint GetNetwork() { return ProtocolSettings.Network; } /// <summary> /// The implementation of System.Runtime.GetTime. /// Gets the timestamp of the current block. /// </summary> /// <returns>The timestamp of the current block.</returns> protected internal ulong GetTime() { return PersistingBlock.Timestamp; } /// <summary> /// The implementation of System.Runtime.GetScriptContainer. /// Gets the current script container. /// </summary> /// <returns>The current script container.</returns> protected internal StackItem GetScriptContainer() { if (ScriptContainer is not IInteroperable interop) throw new InvalidOperationException(); return interop.ToStackItem(ReferenceCounter); } /// <summary> /// The implementation of System.Runtime.CheckWitness. /// Determines whether the specified account has witnessed the current transaction. /// </summary> /// <param name="hashOrPubkey">The hash or public key of the account.</param> /// <returns><see langword="true"/> if the account has witnessed the current transaction; otherwise, <see langword="false"/>.</returns> protected internal bool CheckWitness(byte[] hashOrPubkey) { UInt160 hash = hashOrPubkey.Length switch { 20 => new UInt160(hashOrPubkey), 33 => Contract.CreateSignatureRedeemScript(ECPoint.DecodePoint(hashOrPubkey, ECCurve.Secp256r1)).ToScriptHash(), _ => throw new ArgumentException(null, nameof(hashOrPubkey)) }; return CheckWitnessInternal(hash); } /// <summary> /// Determines whether the specified account has witnessed the current transaction. /// </summary> /// <param name="hash">The hash of the account.</param> /// <returns><see langword="true"/> if the account has witnessed the current transaction; otherwise, <see langword="false"/>.</returns> protected internal bool CheckWitnessInternal(UInt160 hash) { if (hash.Equals(CallingScriptHash)) return true; if (ScriptContainer is Transaction tx) { Signer[] signers; OracleResponse response = tx.GetAttribute<OracleResponse>(); if (response is null) { signers = tx.Signers; } else { OracleRequest request = NativeContract.Oracle.GetRequest(Snapshot, response.Id); signers = NativeContract.Ledger.GetTransaction(Snapshot, request.OriginalTxid).Signers; } Signer signer = signers.FirstOrDefault(p => p.Account.Equals(hash)); if (signer is null) return false; foreach (WitnessRule rule in signer.GetAllRules()) { if (rule.Condition.Match(this)) return rule.Action == WitnessRuleAction.Allow; } return false; } // Check allow state callflag ValidateCallFlags(CallFlags.ReadStates); // only for non-Transaction types (Block, etc) var hashes_for_verifying = ScriptContainer.GetScriptHashesForVerifying(Snapshot); return hashes_for_verifying.Contains(hash); } /// <summary> /// The implementation of System.Runtime.GetInvocationCounter. /// Gets the number of times the current contract has been called during the execution. /// </summary> /// <returns>The number of times the current contract has been called during the execution.</returns> protected internal int GetInvocationCounter() { if (!invocationCounter.TryGetValue(CurrentScriptHash, out var counter)) { invocationCounter[CurrentScriptHash] = counter = 1; } return counter; } /// <summary> /// The implementation of System.Runtime.GetRandom. /// Gets the next random number. /// </summary> /// <returns>The next random number.</returns> protected internal BigInteger GetRandom() { nonceData = Cryptography.Helper.Murmur128(nonceData, ProtocolSettings.Network); return new BigInteger(nonceData, isUnsigned: true); } /// <summary> /// The implementation of System.Runtime.Log. /// Writes a log. /// </summary> /// <param name="state">The message of the log.</param> protected internal void RuntimeLog(byte[] state) { if (state.Length > MaxNotificationSize) throw new ArgumentException(null, nameof(state)); string message = Utility.StrictUTF8.GetString(state); Log?.Invoke(this, new LogEventArgs(ScriptContainer, CurrentScriptHash, message)); } /// <summary> /// The implementation of System.Runtime.Notify. /// Sends a notification. /// </summary> /// <param name="eventName">The name of the event.</param> /// <param name="state">The arguments of the event.</param> protected internal void RuntimeNotify(byte[] eventName, Array state) { if (eventName.Length > MaxEventName) throw new ArgumentException(null, nameof(eventName)); using MemoryStream ms = new(MaxNotificationSize); using BinaryWriter writer = new(ms, Utility.StrictUTF8, true); BinarySerializer.Serialize(writer, state, MaxNotificationSize); SendNotification(CurrentScriptHash, Utility.StrictUTF8.GetString(eventName), state); } /// <summary> /// Sends a notification for the specified contract. /// </summary> /// <param name="hash">The hash of the specified contract.</param> /// <param name="eventName">The name of the event.</param> /// <param name="state">The arguments of the event.</param> protected internal void SendNotification(UInt160 hash, string eventName, Array state) { NotifyEventArgs notification = new(ScriptContainer, hash, eventName, (Array)state.DeepCopy()); Notify?.Invoke(this, notification); notifications ??= new List<NotifyEventArgs>(); notifications.Add(notification); } /// <summary> /// The implementation of System.Runtime.GetNotifications. /// Gets the notifications sent by the specified contract during the execution. /// </summary> /// <param name="hash">The hash of the specified contract. It can be set to <see langword="null"/> to get all notifications.</param> /// <returns>The notifications sent during the execution.</returns> protected internal NotifyEventArgs[] GetNotifications(UInt160 hash) { IEnumerable<NotifyEventArgs> notifications = Notifications; if (hash != null) // must filter by scriptHash notifications = notifications.Where(p => p.ScriptHash == hash); NotifyEventArgs[] array = notifications.ToArray(); if (array.Length > Limits.MaxStackSize) throw new InvalidOperationException(); return array; } /// <summary> /// The implementation of System.Runtime.BurnGas. /// Burning GAS to benefit the NEO ecosystem. /// </summary> /// <param name="gas">The amount of GAS to burn.</param> protected internal void BurnGas(long gas) { if (gas <= 0) throw new InvalidOperationException("GAS must be positive."); AddGas(gas); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic.Internal; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices { #if RHTESTCL static class InteropExtensions1 { public static bool IsNull(this RuntimeTypeHandle handle) { return handle.Equals(default(RuntimeTypeHandle)); } public static bool IsOfType(this Object obj, RuntimeTypeHandle handle) { return handle.Equals(obj.GetType().TypeHandle); } } #endif /// <summary> /// Simple fixed-size hash table. Create once and use to speed table lookup. /// Good for tool time generated data table lookup. The hash table itself be generated at tool time, but runtime generation will take less disk space /// /// 1. Size is given in constructor and never changed afterwards /// 2. Only add is supported, but remove can be added quite easily /// 3. For each entry, an integer index can be stored and received. If index is always the same as inserting order, this can be removed too. /// 4. Value is not stored. It should be managed separately /// 5. Non-generic, there is single copy in memory /// 6. Searching is implemented using two methods: GetFirst and GetNext /// /// Check StringMap below for a Dictionary<string, int> like implementation where strings are stored elsewhere, possibly in compressed form /// </summary> internal class FixedHashTable { const int slot_bucket = 0; const int slot_next = 1; const int slot_index = 2; int[] m_entries; int m_size; int m_count; /// <summary> /// Construct empty hash table /// </summary> [MethodImplAttribute(MethodImplOptions.NoInlining)] internal FixedHashTable(int size) { // Prime number is essential to reduce hash collision // Add 10%, minimum 11 to make sure hash table has around 10% free entries to reduce collision m_size = HashHelpers.GetPrime(Math.Max(11, size * 11 / 10)); // Using int array instead of creating an Entry[] array with three ints to avoid // adding a new array type, which costs around 3kb in binary size m_entries = new int[m_size * 3]; } /// <summary> /// Add an entry: Dictionay<K,V>.Add(Key(index), index) = > FixedHashTable.Add(Key(index).GetHashCode(), index) /// </summary> /// <param name="hashCode">Hash code for data[slot]</param> /// <param name="index">Normally index to external table</param> [MethodImplAttribute(MethodImplOptions.NoInlining)] internal void Add(int hashCode, int index) { int bucket = (hashCode & 0x7FFFFFFF) % m_size; m_entries[m_count * 3 + slot_index] = index; // This is not needed if m_count === index m_entries[m_count * 3 + slot_next] = m_entries[bucket * 3 + slot_bucket]; m_entries[bucket * 3 + slot_bucket] = m_count + 1; // 0 for missing now m_count++; } /// <summary> /// Get first matching entry based on hash code for enumeration, -1 for missing /// </summary> internal int GetFirst(int hashCode) { int bucket = (hashCode & 0x7FFFFFFF) % m_size; return m_entries[bucket * 3 + slot_bucket] - 1; } internal int GetIndex(int bucket) { return m_entries[bucket * 3 + slot_index]; } /// <summary> /// Get next entry for enumeration, -1 for missing /// </summary> internal int GetNext(int bucket) { return m_entries[bucket * 3 + slot_next] - 1; } } /// <summary> /// Virtual Dictionary<string, int> where strings are stored elsewhere, possibly in compressed form /// </summary> internal abstract class StringMap { int m_size; FixedHashTable m_map; internal StringMap(int size) { m_size = size; } internal abstract String GetString(int i); /// <summary> /// String(i).GetHashCode /// </summary> internal abstract int GetStringHash(int i); /// <summary> /// String(i) == name /// </summary> internal abstract bool IsStringEqual(string name, int i); /// <summary> /// Dictionary.TryGetValue(string) /// </summary> internal int FindString(string name) { if (m_map == null) { FixedHashTable map = new FixedHashTable(m_size); for (int i = 0; i < m_size; i++) { map.Add(GetStringHash(i), i); } m_map = map; } int hash = StringPool.StableStringHash(name); // Search hash table for (int slot = m_map.GetFirst(hash); slot >= 0; slot = m_map.GetNext(slot)) { int index = m_map.GetIndex(slot); if (IsStringEqual(name, index)) { return index; } } return -1; } } /// <summary> /// StringMap using 16-bit indices, for normal applications /// </summary> internal class StringMap16 : StringMap { StringPool m_pool; UInt16[] m_indices; internal StringMap16(StringPool pool, UInt16[] indices) : base(indices.Length) { m_pool = pool; m_indices = indices; } internal override string GetString(int i) { return m_pool.GetString(m_indices[i]); } internal override int GetStringHash(int i) { return m_pool.StableStringHash(m_indices[i]); } internal override bool IsStringEqual(string name, int i) { return m_pool.IsStringEqual(name, m_indices[i]); } } /// <summary> /// StringMap using 32-bit indices, for bigger applications /// </summary> internal class StringMap32 : StringMap { StringPool m_pool; UInt32[] m_indices; internal StringMap32(StringPool pool, UInt32[] indices) : base(indices.Length) { m_pool = pool; m_indices = indices; } internal override string GetString(int i) { return m_pool.GetString(m_indices[i]); } internal override int GetStringHash(int i) { return m_pool.StableStringHash(m_indices[i]); } internal override bool IsStringEqual(string name, int i) { return m_pool.IsStringEqual(name, m_indices[i]); } } /// <summary> /// Fixed Dictionary<RuntimeTypeHandle, int> using delegate Func<int, RuntimeTypeHandle> to provide data /// </summary> internal class RuntimeTypeHandleMap : FixedHashTable { Func<int, RuntimeTypeHandle> m_getHandle; internal RuntimeTypeHandleMap(int size, Func<int, RuntimeTypeHandle> getHandle) : base(size) { m_getHandle = getHandle; for (int i = 0; i < size; i++) { RuntimeTypeHandle handle = getHandle(i); if (!handle.Equals(McgModule.s_DependencyReductionTypeRemovedTypeHandle)) { Add(handle.GetHashCode(), i); } } } internal int Lookup(RuntimeTypeHandle handle) { for (int slot = GetFirst(handle.GetHashCode()); slot >= 0; slot = GetNext(slot)) { int index = GetIndex(slot); if (handle.Equals(m_getHandle(index))) { return index; } } return -1; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// HttpRedirects operations. /// </summary> public partial interface IHttpRedirects { /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsHead300Headers>> Head300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 300 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IList<string>,HttpRedirectsGet300Headers>> Get300WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsHead301Headers>> Head301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 301 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsGet301Headers>> Get301WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put true Boolean value in request returns 301. This request /// should not be automatically redirected, but should return the /// received 301 to the caller for evaluation /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsPut301Headers>> Put301WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsHead302Headers>> Head302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return 302 status code and redirect to /http/success/200 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsGet302Headers>> Get302WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Patch true Boolean value in request returns 302. This request /// should not be automatically redirected, but should return the /// received 302 to the caller for evaluation /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsPatch302Headers>> Patch302WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Post true Boolean value in request returns 303. This request /// should be automatically redirected usign a get, ultimately /// returning a 200 status code /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsPost303Headers>> Post303WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Redirect with 307, resulting in a 200 success /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsHead307Headers>> Head307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Redirect get with 307, resulting in a 200 success /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsGet307Headers>> Get307WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsPut307Headers>> Put307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Patch redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsPatch307Headers>> Patch307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Post redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsPost307Headers>> Post307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete redirected with 307, resulting in a 200 after redirect /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationHeaderResponse<HttpRedirectsDelete307Headers>> Delete307WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
//Original Scripts by IIColour (IIColour_Spectrum) using UnityEngine; using System.Collections; using UnityEngine.UI; using PokemonUnity.Monster; public class EvolutionHandler : MonoBehaviour { private DialogBoxHandlerNew dialog; private GUIParticleHandler particles; private int pokemonFrame = 0; private int evolutionFrame = 0; private Sprite[] pokemonSpriteAnimation; private Sprite[] evolutionSpriteAnimation; private Image pokemonSprite; private Image evolutionSprite; private Image topBorder; private Image bottomBorder; private Image glow; private Pokemon selectedPokemon; private string evolutionMethod; private int evolutionID; public AudioClip evolutionBGM, evolvingClip, evolvedClip, forgetMoveClip; public Sprite smokeParticle; private bool stopAnimations = false; private bool evolving = true; private bool evolved = false; //Evolution Animation Coroutines private Coroutine c_animateEvolution; private Coroutine c_pokemonGlow; private Coroutine c_glowGrow; private Coroutine c_pokemonPulsate; private Coroutine c_glowPulsate; void Awake() { dialog = transform.GetComponent<DialogBoxHandlerNew>(); particles = transform.GetComponent<GUIParticleHandler>(); pokemonSprite = transform.Find("PokemonSprite").GetComponent<Image>(); evolutionSprite = transform.Find("EvolutionSprite").GetComponent<Image>(); topBorder = transform.Find("TopBorder").GetComponent<Image>(); bottomBorder = transform.Find("BottomBorder").GetComponent<Image>(); glow = transform.Find("Glow").GetComponent<Image>(); } void Start() { gameObject.SetActive(false); } private IEnumerator animatePokemon() { pokemonFrame = 0; evolutionFrame = 0; while (true) { if (pokemonSpriteAnimation.Length > 0) { if (pokemonFrame < pokemonSpriteAnimation.Length - 1) { pokemonFrame += 1; } else { pokemonFrame = 0; } pokemonSprite.sprite = pokemonSpriteAnimation[pokemonFrame]; } if (evolutionSpriteAnimation.Length > 0) { if (evolutionFrame < evolutionSpriteAnimation.Length - 1) { evolutionFrame += 1; } else { evolutionFrame = 0; } evolutionSprite.sprite = evolutionSpriteAnimation[evolutionFrame]; } yield return new WaitForSeconds(0.08f); } } public IEnumerator control(Pokemon pokemonToEvolve, int index) { selectedPokemon = pokemonToEvolve; //evolutionMethod = method; //evolutionID = selectedPokemon.getEvolutionID(evolutionMethod); evolutionID = selectedPokemon.getEvolutionSpecieID(index); string selectedPokemonName = selectedPokemon.Name; pokemonSpriteAnimation = selectedPokemon.GetFrontAnim_(); evolutionSpriteAnimation = PokemonExtension.GetFrontAnimFromID_((PokemonUnity.Pokemons)evolutionID, selectedPokemon.Gender, selectedPokemon.IsShiny); pokemonSprite.sprite = pokemonSpriteAnimation[0]; evolutionSprite.sprite = evolutionSpriteAnimation[0]; StartCoroutine(animatePokemon()); pokemonSprite.rectTransform.sizeDelta = new Vector2(128, 128); evolutionSprite.rectTransform.sizeDelta = new Vector2(0, 0); pokemonSprite.color = new Color(0.5f, 0.5f, 0.5f, 0.5f); evolutionSprite.color = new Color(0.5f, 0.5f, 0.5f, 0.5f); topBorder.rectTransform.sizeDelta = new Vector2(342, 0); bottomBorder.rectTransform.sizeDelta = new Vector2(342, 0); glow.rectTransform.sizeDelta = new Vector2(0, 0); stopAnimations = false; StartCoroutine(ScreenFade.main.Fade(true, 1f)); yield return new WaitForSeconds(1f); dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("What?")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } yield return StartCoroutine(dialog.DrawText("\n" + selectedPokemon.Name + " is evolving!")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.UndrawDialogBox(); evolving = true; AudioClip cry = selectedPokemon.GetCry(); SfxHandler.Play(cry); yield return new WaitForSeconds(cry.length); BgmHandler.main.PlayOverlay(evolutionBGM, 753100); yield return new WaitForSeconds(0.4f); c_animateEvolution = StartCoroutine(animateEvolution()); SfxHandler.Play(evolvingClip); yield return new WaitForSeconds(0.4f); while (evolving) { if (Input.GetButtonDown("Back")) { evolving = false; //fadeTime = sceneTransition.FadeOut(); //yield return new WaitForSeconds(fadeTime); yield return StartCoroutine(ScreenFade.main.Fade(false, ScreenFade.defaultSpeed)); stopAnimateEvolution(); //fadeTime = sceneTransition.FadeIn(); //yield return new WaitForSeconds(fadeTime); yield return StartCoroutine(ScreenFade.main.Fade(true, ScreenFade.defaultSpeed)); dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("Huh?")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } yield return StartCoroutine(dialog.DrawText("\n" + selectedPokemon.Name + " stopped evolving.")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.UndrawDialogBox(); } yield return null; } if (evolved) { //selectedPokemon.evolve(evolutionMethod); selectedPokemon.evolve(index); yield return new WaitForSeconds(3.2f); cry = selectedPokemon.GetCry(); BgmHandler.main.PlayMFX(cry); yield return new WaitForSeconds(cry.length); AudioClip evoMFX = Resources.Load<AudioClip>("Audio/mfx/GetGreat"); BgmHandler.main.PlayMFXConsecutive(evoMFX); dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawTextSilent("Congratulations!")); yield return new WaitForSeconds(0.8f); StartCoroutine( dialog.DrawTextSilent("\nYour " + selectedPokemonName + " evolved into " + ((PokemonUnity.Pokemons)evolutionID).toString() + "!")); //wait for MFX to stop float extraTime = (evoMFX.length - 0.8f > 0) ? evoMFX.length - 0.8f : 0; yield return new WaitForSeconds(extraTime); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } PokemonUnity.Moves newMove = selectedPokemon.MoveLearnedAtLevel(selectedPokemon.Level); if (newMove != PokemonUnity.Moves.NONE && !selectedPokemon.hasMove(newMove)) { yield return StartCoroutine(LearnMove(selectedPokemon, newMove)); } dialog.UndrawDialogBox(); bool running = true; while (running) { if (Input.GetButtonDown("Select") || Input.GetButtonDown("Back")) { running = false; } yield return null; } yield return new WaitForSeconds(0.4f); } StartCoroutine(ScreenFade.main.Fade(false, 1f)); BgmHandler.main.ResumeMain(1.2f); yield return new WaitForSeconds(1.2f); this.gameObject.SetActive(false); } private void stopAnimateEvolution() { stopAnimations = true; StopCoroutine(c_animateEvolution); if (c_glowGrow != null) { StopCoroutine(c_glowGrow); } if (c_glowPulsate != null) { StopCoroutine(c_glowPulsate); } if (c_pokemonGlow != null) { StopCoroutine(c_pokemonGlow); } if (c_pokemonPulsate != null) { StopCoroutine(c_pokemonPulsate); } particles.cancelAllParticles(); glow.rectTransform.sizeDelta = new Vector2(0, 0); bottomBorder.rectTransform.sizeDelta = new Vector2(342, 0); topBorder.rectTransform.sizeDelta = new Vector2(342, 0); pokemonSprite.rectTransform.sizeDelta = new Vector2(128, 128); evolutionSprite.rectTransform.sizeDelta = new Vector2(0, 0); pokemonSprite.color = new Color(0.5f, 0.5f, 0.5f, 0.5f); BgmHandler.main.PlayOverlay(null, 0, 0.5f); } private IEnumerator animateEvolution() { StartCoroutine(smokeSpiral()); StartCoroutine(borderDescend()); yield return new WaitForSeconds(0.6f); c_pokemonGlow = StartCoroutine(pokemonGlow()); yield return new WaitForSeconds(0.4f); c_glowGrow = StartCoroutine(glowGrow()); yield return new WaitForSeconds(0.4f); evolutionSprite.color = new Color(1, 1, 1, 0.5f); c_pokemonPulsate = StartCoroutine(pokemonPulsate(19)); yield return new WaitForSeconds(0.4f); yield return c_glowPulsate = StartCoroutine(glowPulsate(7)); evolved = true; evolving = false; SfxHandler.Play(evolvedClip); StartCoroutine(glowDissipate()); StartCoroutine(brightnessExplosion()); StartCoroutine(borderRetract()); yield return new WaitForSeconds(0.4f); yield return StartCoroutine(evolutionUnglow()); yield return new WaitForSeconds(0.4f); } private IEnumerator brightnessExplosion() { //GlobalVariables.global.fadeTex = whiteTex; float speed = ScreenFade.slowedSpeed; StartCoroutine(ScreenFade.main.Fade(false, ScreenFade.slowedSpeed, Color.white)); float increment = 0f; while (increment < 1) { increment += (1f / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } yield return null; } StartCoroutine(ScreenFade.main.Fade(true, ScreenFade.slowedSpeed, Color.white)); //sceneTransition.FadeIn(1.2f); } private IEnumerator glowGrow() { float increment = 0f; float speed = 0.8f; float endSize = 96f; glow.color = new Color(0.8f, 0.8f, 0.5f, 0.2f); while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } glow.rectTransform.sizeDelta = new Vector2(endSize * increment, endSize * increment); yield return null; } } private IEnumerator glowDissipate() { float increment = 0f; float speed = 1.5f; float startSize = glow.rectTransform.sizeDelta.x; float sizeDifference = 280f - startSize; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } glow.rectTransform.sizeDelta = new Vector2(startSize + sizeDifference * increment, startSize + sizeDifference * increment); glow.color = new Color(glow.color.r, glow.color.g, glow.color.b, 0.2f - (0.2f * increment)); yield return null; } } private IEnumerator glowPulsate(int repetitions) { float increment = 0f; float speed = 0.9f; float maxSize = 160f; float minSize = 96f; float sizeDifference = maxSize - minSize; bool glowShrunk = true; for (int i = 0; i < repetitions; i++) { increment = 0f; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } if (glowShrunk) { glow.rectTransform.sizeDelta = new Vector2(minSize + sizeDifference * increment, minSize + sizeDifference * increment); } else { glow.rectTransform.sizeDelta = new Vector2(maxSize - sizeDifference * increment, maxSize - sizeDifference * increment); } yield return null; } if (glowShrunk) { glowShrunk = false; } else { glowShrunk = true; } } } private IEnumerator pokemonPulsate(int repetitions) { float increment = 0f; float baseSpeed = 1.2f; float speed = baseSpeed; Vector3 originalPosition = pokemonSprite.transform.localPosition; Vector3 centerPosition = new Vector3(0.5f, 0.47f, originalPosition.z); float distance = centerPosition.y - originalPosition.y; bool originalPokemonShrunk = false; for (int i = 0; i < repetitions; i++) { increment = 0f; speed *= 0.85f; while (increment < 1) { if (speed < 0.15f) { speed = 0.15f; } increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } if (originalPokemonShrunk) { pokemonSprite.rectTransform.sizeDelta = new Vector2(128f * increment, 128f * increment); pokemonSprite.transform.localPosition = new Vector3(originalPosition.x, centerPosition.y - (distance * increment), originalPosition.z); evolutionSprite.rectTransform.sizeDelta = new Vector2(128f - 128f * increment, 128f - 128f * increment); evolutionSprite.transform.localPosition = new Vector3(originalPosition.x, originalPosition.y + (distance * increment), originalPosition.z); } else { pokemonSprite.rectTransform.sizeDelta = new Vector2(128f - 128f * increment, 128f - 128f * increment); pokemonSprite.transform.localPosition = new Vector3(originalPosition.x, originalPosition.y + (distance * increment), originalPosition.z); evolutionSprite.rectTransform.sizeDelta = new Vector2(128f * increment, 128f * increment); evolutionSprite.transform.localPosition = new Vector3(originalPosition.x, centerPosition.y - (distance * increment), originalPosition.z); } yield return null; } if (originalPokemonShrunk) { originalPokemonShrunk = false; } else { originalPokemonShrunk = true; } } pokemonSprite.transform.localPosition = originalPosition; evolutionSprite.transform.localPosition = originalPosition; } private IEnumerator pokemonGlow() { float increment = 0f; float speed = 1.8f; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } pokemonSprite.color = new Color(0.5f + (0.5f * increment), 0.5f + (0.5f * increment), 0.5f + (0.5f * increment), 0.5f); yield return null; } } private IEnumerator evolutionUnglow() { float increment = 0f; float speed = 1.8f; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } evolutionSprite.color = new Color(1f - (0.5f * increment), 1f - (0.5f * increment), 1f - (0.5f * increment), 0.5f); yield return null; } } private IEnumerator borderDescend() { float increment = 0f; float speed = 0.4f; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } topBorder.rectTransform.sizeDelta = new Vector2(342, 40 * increment); bottomBorder.rectTransform.sizeDelta = new Vector2(342, 64 * increment); yield return null; } } private IEnumerator borderRetract() { float increment = 0f; float speed = 0.4f; while (increment < 1) { increment += (1 / speed) * Time.deltaTime; if (increment > 1) { increment = 1; } topBorder.rectTransform.sizeDelta = new Vector2(342, 40 - 40 * increment); bottomBorder.rectTransform.sizeDelta = new Vector2(342, 64 - 64 * increment); yield return null; } } private IEnumerator smokeSpiral() { StartCoroutine(smokeTrail(-1, 0.6f, 0.56f, 16f)); yield return new WaitForSeconds(0.08f); StartCoroutine(smokeTrail(1, 0.36f, 0.44f, 18f)); yield return new WaitForSeconds(0.2f); StartCoroutine(smokeTrail(-1, 0.6f, 0.36f, 16f)); yield return new WaitForSeconds(0.26f); StartCoroutine(smokeTrail(1, 0.36f, 0.54f, 16f)); yield return new WaitForSeconds(0.08f); StartCoroutine(smokeTrail(-1, 0.6f, 0.42f, 18f)); yield return new WaitForSeconds(0.2f); StartCoroutine(smokeTrail(1, 0.36f, 0.34f, 16f)); yield return new WaitForSeconds(0.26f); StartCoroutine(smokeTrail(-1, 0.6f, 0.52f, 16f)); yield return new WaitForSeconds(0.08f); StartCoroutine(smokeTrail(1, 0.36f, 0.4f, 18f)); yield return new WaitForSeconds(0.2f); StartCoroutine(smokeTrail(-1, 0.6f, 0.32f, 16f)); yield return new WaitForSeconds(0.26f); StartCoroutine(smokeTrail(-1, 0.6f, 0.5f, 16f)); yield return new WaitForSeconds(0.08f); StartCoroutine(smokeTrail(1, 0.36f, 0.38f, 18f)); yield return new WaitForSeconds(0.2f); StartCoroutine(smokeTrail(-1, 0.6f, 0.3f, 16f)); yield return new WaitForSeconds(0.26f); } private IEnumerator smokeTrail(int direction, float positionX, float positionY, float maxSize) { float positionYmodified; float sizeModified; for (int i = 0; i < 8; i++) { positionYmodified = positionY + Random.Range(-0.03f, 0.03f); sizeModified = (((float) i / 7f) * maxSize + maxSize) / 2f; if (!stopAnimations) { Image particle = particles.createParticle(smokeParticle, ScaleToScreen(positionX, positionYmodified), sizeModified, 0, 0.6f, ScaleToScreen(positionX + Random.Range(0.01f, 0.04f), positionYmodified - 0.02f), 0, sizeModified * 0.33f); if (particle != null) { particle.color = new Color((float) i / 7f * 0.7f, (float) i / 7f * 0.7f, (float) i / 7f * 0.7f, 0.3f + ((float) i / 7f * 0.3f)); } else { Debug.Log("Particle Discarded"); } } if (direction > 0) { positionX += 0.03f; } else { positionX -= 0.03f; } positionY -= 0.0025f; yield return new WaitForSeconds(0.05f); } } private Vector2 ScaleToScreen(float x, float y) { Vector2 vector = new Vector2(x * 342f - 171f, (1 - y) * 192f - 96f); return vector; } private IEnumerator LearnMove(Pokemon selectedPokemon, PokemonUnity.Moves move) { int chosenIndex = 1; if (chosenIndex == 1) { bool learning = true; while (learning) { //Moveset is full if (selectedPokemon.countMoves() == 4) { dialog.DrawDialogBox(); yield return StartCoroutine( dialog.DrawText(selectedPokemon.Name + " wants to learn the \nmove " + move + ".")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.DrawDialogBox(); yield return StartCoroutine( dialog.DrawText("However, " + selectedPokemon.Name + " already \nknows four moves.")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("Should a move be deleted and \nreplaced with " + move + "?")); // This function didn't show choice box yield return StartCoroutine(dialog.DrawChoiceBox()); chosenIndex = dialog.chosenIndex; dialog.UndrawChoiceBox(); if (chosenIndex == 1) { dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("Which move should \nbe forgotten?")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } yield return StartCoroutine(ScreenFade.main.Fade(false, ScreenFade.defaultSpeed)); //Set SceneSummary to be active so that it appears Scene.main.Summary.gameObject.SetActive(true); StartCoroutine(Scene.main.Summary.control(selectedPokemon, move)); //Start an empty loop that will only stop when SceneSummary is no longer active (is closed) while (Scene.main.Summary.gameObject.activeSelf) { yield return null; } string replacedMove = Scene.main.Summary.replacedMove; yield return StartCoroutine(ScreenFade.main.Fade(true, ScreenFade.defaultSpeed)); if (!string.IsNullOrEmpty(replacedMove)) { dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawTextSilent("1, ")); yield return new WaitForSeconds(0.4f); yield return StartCoroutine(dialog.DrawTextSilent("2, ")); yield return new WaitForSeconds(0.4f); yield return StartCoroutine(dialog.DrawTextSilent("and... ")); yield return new WaitForSeconds(0.4f); yield return StartCoroutine(dialog.DrawTextSilent("... ")); yield return new WaitForSeconds(0.4f); yield return StartCoroutine(dialog.DrawTextSilent("... ")); yield return new WaitForSeconds(0.4f); SfxHandler.Play(forgetMoveClip); yield return StartCoroutine(dialog.DrawTextSilent("Poof!")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.DrawDialogBox(); yield return StartCoroutine( dialog.DrawText(selectedPokemon.Name + " forgot how to \nuse " + replacedMove + ".")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("And...")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.DrawDialogBox(); AudioClip mfx = Resources.Load<AudioClip>("Audio/mfx/GetAverage"); BgmHandler.main.PlayMFX(mfx); StartCoroutine(dialog.DrawTextSilent(selectedPokemon.Name + " learned \n" + move + "!")); yield return new WaitForSeconds(mfx.length); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.UndrawDialogBox(); learning = false; } else { //give up? chosenIndex = 0; } } if (chosenIndex == 0) { //NOT ELSE because this may need to run after (chosenIndex == 1) runs dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText("Give up on learning the move \n" + move + "?")); yield return StartCoroutine(dialog.DrawChoiceBox()); chosenIndex = dialog.chosenIndex; dialog.UndrawChoiceBox(); if (chosenIndex == 1) { learning = false; chosenIndex = 0; } } } //Moveset is not full, can fit the new move easily else { selectedPokemon.addMove(move); dialog.DrawDialogBox(); AudioClip mfx = Resources.Load<AudioClip>("Audio/mfx/GetAverage"); BgmHandler.main.PlayMFX(mfx); StartCoroutine(dialog.DrawTextSilent(selectedPokemon.Name + " learned \n" + move + "!")); yield return new WaitForSeconds(mfx.length); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } dialog.UndrawDialogBox(); learning = false; } } } if (chosenIndex == 0) { //NOT ELSE because this may need to run after (chosenIndex == 1) runs //cancel learning loop dialog.DrawDialogBox(); yield return StartCoroutine(dialog.DrawText(selectedPokemon.Name + " did not learn \n" + move + ".")); while (!Input.GetButtonDown("Select") && !Input.GetButtonDown("Back")) { yield return null; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.GrainReferences; using Orleans.Metadata; using Orleans.Runtime; namespace Orleans { /// <summary> /// Factory for accessing grains. /// </summary> internal class GrainFactory : IInternalGrainFactory { private GrainReferenceRuntime grainReferenceRuntime; /// <summary> /// The cache of typed system target references. /// </summary> private readonly Dictionary<(GrainId, Type), ISystemTarget> typedSystemTargetReferenceCache = new Dictionary<(GrainId, Type), ISystemTarget>(); private readonly ImrGrainMethodInvokerProvider invokers; private readonly GrainReferenceActivator referenceActivator; private readonly GrainInterfaceTypeResolver interfaceTypeResolver; private readonly GrainInterfaceTypeToGrainTypeResolver interfaceTypeToGrainTypeResolver; private readonly IRuntimeClient runtimeClient; public GrainFactory( IRuntimeClient runtimeClient, GrainReferenceActivator referenceActivator, GrainInterfaceTypeResolver interfaceTypeResolver, GrainInterfaceTypeToGrainTypeResolver interfaceToTypeResolver, ImrGrainMethodInvokerProvider invokers) { this.runtimeClient = runtimeClient; this.referenceActivator = referenceActivator; this.interfaceTypeResolver = interfaceTypeResolver; this.interfaceTypeToGrainTypeResolver = interfaceToTypeResolver; this.invokers = invokers; } private GrainReferenceRuntime GrainReferenceRuntime => this.grainReferenceRuntime ??= (GrainReferenceRuntime)this.runtimeClient.GrainReferenceRuntime; /// <inheritdoc /> public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithGuidKey { var grainKey = GrainIdKeyExtensions.CreateGuidKey(primaryKey); return (TGrainInterface)GetGrain(typeof(TGrainInterface), grainKey, grainClassNamePrefix: grainClassNamePrefix); } /// <inheritdoc /> public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithIntegerKey { var grainKey = GrainIdKeyExtensions.CreateIntegerKey(primaryKey); return (TGrainInterface)GetGrain(typeof(TGrainInterface), grainKey, grainClassNamePrefix: grainClassNamePrefix); } /// <inheritdoc /> public TGrainInterface GetGrain<TGrainInterface>(string primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithStringKey { var grainKey = IdSpan.Create(primaryKey); return (TGrainInterface)GetGrain(typeof(TGrainInterface), grainKey, grainClassNamePrefix: grainClassNamePrefix); } /// <inheritdoc /> public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string keyExtension, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithGuidCompoundKey { GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension); var grainKey = GrainIdKeyExtensions.CreateGuidKey(primaryKey, keyExtension); return (TGrainInterface)GetGrain(typeof(TGrainInterface), grainKey, grainClassNamePrefix: grainClassNamePrefix); } /// <inheritdoc /> public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string keyExtension, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithIntegerCompoundKey { GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension); var grainKey = GrainIdKeyExtensions.CreateIntegerKey(primaryKey, keyExtension); return (TGrainInterface)GetGrain(typeof(TGrainInterface), grainKey, grainClassNamePrefix: grainClassNamePrefix); } /// <inheritdoc /> public Task<TGrainObserverInterface> CreateObjectReference<TGrainObserverInterface>(IGrainObserver obj) where TGrainObserverInterface : IGrainObserver { return Task.FromResult(this.CreateObjectReference<TGrainObserverInterface>((IAddressable)obj)); } /// <inheritdoc /> public Task DeleteObjectReference<TGrainObserverInterface>( IGrainObserver obj) where TGrainObserverInterface : IGrainObserver { this.runtimeClient.DeleteObjectReference(obj); return Task.CompletedTask; } /// <inheritdoc /> public TGrainObserverInterface CreateObjectReference<TGrainObserverInterface>(IAddressable obj) where TGrainObserverInterface : IAddressable { return (TGrainObserverInterface)this.CreateObjectReference(typeof(TGrainObserverInterface), obj); } /// <summary> /// Casts the provided <paramref name="grain"/> to the specified interface /// </summary> /// <typeparam name="TGrainInterface">The target grain interface type.</typeparam> /// <param name="grain">The grain reference being cast.</param> /// <returns> /// A reference to <paramref name="grain"/> which implements <typeparamref name="TGrainInterface"/>. /// </returns> public TGrainInterface Cast<TGrainInterface>(IAddressable grain) { var interfaceType = typeof(TGrainInterface); return (TGrainInterface)this.Cast(grain, interfaceType); } /// <summary> /// Casts the provided <paramref name="grain"/> to the provided <paramref name="interfaceType"/>. /// </summary> /// <param name="grain">The grain.</param> /// <param name="interfaceType">The resulting interface type.</param> /// <returns>A reference to <paramref name="grain"/> which implements <paramref name="interfaceType"/>.</returns> public object Cast(IAddressable grain, Type interfaceType) => this.GrainReferenceRuntime.Cast(grain, interfaceType); public TGrainInterface GetSystemTarget<TGrainInterface>(GrainType grainType, SiloAddress destination) where TGrainInterface : ISystemTarget { var grainId = SystemTargetGrainId.Create(grainType, destination); return this.GetSystemTarget<TGrainInterface>(grainId.GrainId); } /// <summary> /// Gets a reference to the specified system target. /// </summary> /// <typeparam name="TGrainInterface">The system target interface.</typeparam> /// <param name="grainId">The id of the target.</param> /// <returns>A reference to the specified system target.</returns> public TGrainInterface GetSystemTarget<TGrainInterface>(GrainId grainId) where TGrainInterface : ISystemTarget { ISystemTarget reference; ValueTuple<GrainId, Type> key = ValueTuple.Create(grainId, typeof(TGrainInterface)); lock (this.typedSystemTargetReferenceCache) { if (this.typedSystemTargetReferenceCache.TryGetValue(key, out reference)) { return (TGrainInterface)reference; } reference = this.GetGrain<TGrainInterface>(grainId); this.typedSystemTargetReferenceCache[key] = reference; return (TGrainInterface)reference; } } /// <inheritdoc /> public TGrainInterface GetGrain<TGrainInterface>(GrainId grainId) where TGrainInterface : IAddressable { return (TGrainInterface)this.CreateGrainReference(typeof(TGrainInterface), grainId); } /// <inheritdoc /> public IAddressable GetGrain(GrainId grainId) => this.referenceActivator.CreateReference(grainId, default); /// <inheritdoc /> public IGrain GetGrain(Type grainInterfaceType, Guid key) { var grainKey = GrainIdKeyExtensions.CreateGuidKey(key); return (IGrain)GetGrain(grainInterfaceType, grainKey, grainClassNamePrefix: null); } /// <inheritdoc /> public IGrain GetGrain(Type grainInterfaceType, long key) { var grainKey = GrainIdKeyExtensions.CreateIntegerKey(key); return (IGrain)GetGrain(grainInterfaceType, grainKey, grainClassNamePrefix: null); } /// <inheritdoc /> public IGrain GetGrain(Type grainInterfaceType, string key) { var grainKey = IdSpan.Create(key); return (IGrain)GetGrain(grainInterfaceType, grainKey, grainClassNamePrefix: null); } /// <inheritdoc /> public IGrain GetGrain(Type grainInterfaceType, Guid key, string keyExtension) { var grainKey = GrainIdKeyExtensions.CreateGuidKey(key, keyExtension); return (IGrain)GetGrain(grainInterfaceType, grainKey, grainClassNamePrefix: null); } /// <inheritdoc /> public IGrain GetGrain(Type grainInterfaceType, long key, string keyExtension) { var grainKey = GrainIdKeyExtensions.CreateIntegerKey(key, keyExtension); return (IGrain)GetGrain(grainInterfaceType, grainKey, grainClassNamePrefix: null); } private IAddressable GetGrain(Type interfaceType, IdSpan grainKey, string grainClassNamePrefix) { var grainInterfaceType = this.interfaceTypeResolver.GetGrainInterfaceType(interfaceType); GrainType grainType; if (!string.IsNullOrWhiteSpace(grainClassNamePrefix)) { grainType = this.interfaceTypeToGrainTypeResolver.GetGrainType(grainInterfaceType, grainClassNamePrefix); } else { grainType = this.interfaceTypeToGrainTypeResolver.GetGrainType(grainInterfaceType); } var grainId = GrainId.Create(grainType, grainKey); var grain = this.referenceActivator.CreateReference(grainId, grainInterfaceType); return grain; } public IAddressable GetGrain(GrainId grainId, GrainInterfaceType interfaceType) { return this.referenceActivator.CreateReference(grainId, interfaceType); } private object CreateGrainReference(Type interfaceType, GrainId grainId) { var grainInterfaceType = this.interfaceTypeResolver.GetGrainInterfaceType(interfaceType); return this.referenceActivator.CreateReference(grainId, grainInterfaceType); } private object CreateObjectReference(Type interfaceType, IAddressable obj) { if (!interfaceType.IsInterface) { throw new ArgumentException( $"The provided type parameter must be an interface. '{interfaceType.FullName}' is not an interface."); } if (!interfaceType.IsInstanceOfType(obj)) { throw new ArgumentException($"The provided object must implement '{interfaceType.FullName}'.", nameof(obj)); } var grainInterfaceType = this.interfaceTypeResolver.GetGrainInterfaceType(interfaceType); if (!this.invokers.TryGet(grainInterfaceType, out var invoker)) { throw new KeyNotFoundException($"Could not find an invoker for interface {grainInterfaceType}"); } return this.Cast(this.runtimeClient.CreateObjectReference(obj, invoker), interfaceType); } } }
using System; using System.Collections.Specialized; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using EmergeTk.Model; using EmergeTk.Model.Security; using SimpleJson; namespace EmergeTk.WebServices { public delegate void MessageEndPoint (MessageEndPointArguments arguments); public class WebServiceManager { private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(WebServiceManager)); public static WebServiceManager Manager = new WebServiceManager (); bool disableServiceSecurity; private WebServiceManager () { disableServiceSecurity = Setting.GetValueT<bool>("DisableServiceSecurity",false); } //a map of base paths for routing requests. Dictionary<string, RequestProcessor> routeMap = new Dictionary<string, RequestProcessor> (); //a map of the service objects handler objects themselves Dictionary<string, object> serviceMap = new Dictionary<string, object> (); Dictionary<Type,IRestServiceManager> restServiceManagers = new Dictionary<Type, IRestServiceManager>(); Dictionary<Type,RestTypeDescription> restTypeDescriptions = new Dictionary<Type, RestTypeDescription>(); Dictionary<string,Type> restNameMap = new Dictionary<string, Type> (); public Type GetTypeForRestService (string name) { if (restNameMap.ContainsKey (name)) return restNameMap[name]; return null; } public static bool DoAuth() { return !Manager.disableServiceSecurity && System.Web.HttpContext.Current != null && !User.IsRoot; } public IRestServiceManager GetRestServiceManager(Type recordType) { if( restServiceManagers.ContainsKey(recordType) ) { return restServiceManagers[recordType]; } return null; } public RestTypeDescription GetRestTypeDescription(Type recordType) { if( restTypeDescriptions.ContainsKey(recordType) ) { return restTypeDescriptions[recordType]; } return new RestTypeDescription(); } public Dictionary<string, RequestProcessor> RouteMap { get { return routeMap; } } static bool started = false; public void Startup () { if( started ) return; started = true; Attribute[] attributes; Type[] types = TypeLoader.GetTypesWithAttribute (typeof(WebServiceAttribute), true, out attributes); /* * for each type that matched above, we want to create a couple of objects: * 1. an instance of the web service type itself. * 2. a request processor. * 3. if the service manager type is different than the current type, a new instance of that service manager type. */ //first scan for all non-generic services. for (int i = 0; i < types.Length; i++) { try { Type type = types[i]; log.DebugFormat("initializing {0} generic? {1} attribute: {2}", type, type.IsGenericParameter, attributes[i]); //we don't automagically process generic typedefs. if (type.IsGenericTypeDefinition) continue; WebServiceAttribute att = (WebServiceAttribute)attributes[i]; object service = Activator.CreateInstance (type); IMessageServiceManager serviceManager = (IMessageServiceManager)Activator.CreateInstance(att.ServiceManager); RegisterWebService (type, service, att, serviceManager); } catch(Exception e) { log.Error(e); } } //next scan for all restful types and register an instance of our ModelServiceHandler for them. Attribute[] restAttributes; Type[] restTypes = TypeLoader.GetTypesWithAttribute (typeof(RestServiceAttribute), false, out restAttributes); for (int i = 0; i < restTypes.Length; i++) { try { RestServiceAttribute attribute = (RestServiceAttribute)restAttributes[i]; IRestServiceManager restServiceManager = (IRestServiceManager)Activator.CreateInstance(attribute.ServiceManager); List<RestTypeDescription> mangeableTypes = restServiceManager.GetTypeDescriptions(); if( mangeableTypes != null ) { foreach( RestTypeDescription description in mangeableTypes ) { TypeLoader.InvokeGenericMethod (typeof(WebServiceManager), "RegisterRestService", new Type[] { description.RestType }, this, new object[]{restServiceManager, description}); } } else { RestTypeDescription description = new RestTypeDescription() { ModelName = attribute.ModelName, ModelPluralName = attribute.ModelPluralName, RestType = restTypes[i], Verb = attribute.Verb }; TypeLoader.InvokeGenericMethod (typeof(WebServiceManager), "RegisterRestService", new Type[] { restTypes[i] }, this, new object[]{restServiceManager, description}); } } catch(Exception e) { log.Error(e); } } //load security types LoadSecurityServiceManagers(); } void LoadSecurityServiceManagers () { RegisterSecurityRestService<User>("user"); RegisterSecurityRestService<Role>("role"); RegisterSecurityRestService<Permission>("permission"); } private void RegisterSecurityRestService<T>(string modelName) where T : AbstractRecord, new() { AdministrativeServiceManager man = new AdministrativeServiceManager(); RestServiceAttribute attribute = new RestServiceAttribute() { ModelName = modelName }; RestTypeDescription description = new RestTypeDescription() { ModelName = attribute.ModelName, ModelPluralName = attribute.ModelPluralName, RestType = typeof(T), Verb = attribute.Verb }; WebServiceAttribute modelServiceHandlerAttribute = (WebServiceAttribute)typeof(ModelServiceHandler<T>).GetCustomAttributes (typeof(WebServiceAttribute), false)[0]; ModelServiceHandler<T> service = new ModelServiceHandler<T> (); service.RestDescription = description; modelServiceHandlerAttribute.BasePath += description.ModelName + '/'; service.ServiceManager = man; restServiceManagers[typeof(T)] = man; restTypeDescriptions[typeof(T)] = description; RegisterWebService (typeof(ModelServiceHandler<T>), service, modelServiceHandlerAttribute, service, description.ModelName, description.ModelPluralName); } public void RegisterRestService<T> (IRestServiceManager restServiceManager, RestTypeDescription description) where T : AbstractRecord, new() { log.Info("Registering rest service ", description.ToString() ); WebServiceAttribute modelServiceHandlerAttribute = (WebServiceAttribute)typeof(ModelServiceHandler<T>).GetCustomAttributes (typeof(WebServiceAttribute), false)[0]; ModelServiceHandler<T> service = new ModelServiceHandler<T> (); service.RestDescription = description; modelServiceHandlerAttribute.BasePath += description.ModelName + '/'; service.ServiceManager = restServiceManager; restServiceManagers[typeof(T)] = restServiceManager; restTypeDescriptions[typeof(T)] = description; restNameMap[description.ModelName] = typeof(T); RegisterWebService (typeof(ModelServiceHandler<T>), service, modelServiceHandlerAttribute, service, description.ModelName, description.ModelPluralName); } public void RegisterWebService (Type type, object service, WebServiceAttribute att, IMessageServiceManager serviceManager) { RegisterWebService(type,service,att,serviceManager,null,null); } private void RegisterWebService (Type type, object service, WebServiceAttribute att, IMessageServiceManager serviceManager, string modelName, string pluralName) { RequestProcessor processor = new RequestProcessor (att); processor.ServiceManager = serviceManager; MethodInfo[] methods = type.GetMethods (); foreach (MethodInfo method in methods) { object[] methodAttributes = method.GetCustomAttributes (typeof(MessageServiceEndPointAttribute), true); if (methodAttributes != null && methodAttributes.Length > 0) { MessageServiceEndPointAttribute messageAttribute = (MessageServiceEndPointAttribute)methodAttributes[0]; messageAttribute.Regex = new Regex (messageAttribute.Pattern); messageAttribute.EndPoint = (MessageEndPoint)Delegate.CreateDelegate(typeof(MessageEndPoint), service, method.Name); messageAttribute.MethodName = method.Name; object[] descAtts = method.GetCustomAttributes (typeof(MessageDescriptionAttribute), true); if( descAtts != null && descAtts.Length > 0 ) { MessageDescriptionAttribute descAttr = (MessageDescriptionAttribute)descAtts[0]; messageAttribute.Description = descAttr.Description; if( modelName != null ) { messageAttribute.Description = messageAttribute.Description.Replace("{ModelName}",modelName).Replace("{ModelPluralName}",pluralName); } } processor.AddMessageEndPoint (messageAttribute); //log.InfoFormat("creating endPoint '{0}' on service '{1}'", method.Name, service); } } log.InfoFormat("Registering web service '{0}' at '{1}'", service, att.BasePath); routeMap[att.BasePath] = processor; serviceMap[att.BasePath] = service; } public RequestProcessor GetRequestProcessor (string path) { string[] segs = path.TrimEnd('/').Split('/'); for( int i = 0; i < segs.Length; i++ ) segs[i] += '/'; return GetRequestProcessor(segs); } public RequestProcessor GetRequestProcessor (string[] segs) { string basePath = string.Empty; //reverse search to allow different handlers to implement sub-namespaces. //for (int i = 0; i < segs.Length; i++) { for( int i = segs.Length; i >= 0; i-- ) { basePath = string.Join("", segs, 0, i ); //log.Debug("looking for router for base path ", basePath); if (routeMap.ContainsKey (basePath)) { return routeMap[basePath]; } } return null; } } public class AdministrativeServiceManager : IRestServiceManager { private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(AdministrativeServiceManager)); #region IRestServiceManager implementation public string GetHelpText () { throw new System.NotImplementedException(); } public void Authorize (RestOperation operation, JsonObject recordNode, AbstractRecord record) { if ( operation != RestOperation.Get ) { if (User.Current != null && record != null && record.GetType() == typeof(User) && record == User.Current) return; log.Debug("Going to throw UnauthorizedAccessException: Record is only allowed operation of type 'Get'"); throw new UnauthorizedAccessException("Record is only allowed operation of type 'Get' for non-Root user."); } else { log.Debug("Authorize ok for non-Get"); } if ( User.Current == null ) { log.Debug("Going to throw UnauthorizedAccessException: No current user"); throw new UnauthorizedAccessException("No current user."); } else if ( record != null && record.GetType() == typeof(User) && record != User.Current ) { log.Debug("Going to throw UnauthorizedAccessException: Record does not match current user"); throw new UnauthorizedAccessException("Record does not match current user."); } else log.Debug("Authorize successful",operation,record); } public bool AuthorizeField (RestOperation op, AbstractRecord record, string property) { // TODO: if operation is put, and it's not the password field, then throw exception return true; } public AbstractRecord GenerateExampleRecord () { throw new System.NotImplementedException(); } public string GenerateExampleFields (string method) { throw new System.NotImplementedException(); } public List<RestTypeDescription> GetTypeDescriptions () { return null; } #endregion } }
using System.Diagnostics.CodeAnalysis; using Signum.Engine.Maps; using Signum.Utilities.Reflection; namespace Signum.Engine.Linq; internal class ChildProjectionFlattener : DbExpressionVisitor { SelectExpression? currentSource; readonly AliasGenerator aliasGenerator; private ChildProjectionFlattener(AliasGenerator aliasGenerator) { this.aliasGenerator = aliasGenerator; } static internal ProjectionExpression Flatten(ProjectionExpression proj, AliasGenerator aliasGenerator) { var result = (ProjectionExpression)new ChildProjectionFlattener(aliasGenerator).Visit(proj); if (result == proj) return result; Expression columnCleaned = UnusedColumnRemover.Remove(result); Expression subqueryCleaned = RedundantSubqueryRemover.Remove(columnCleaned); return (ProjectionExpression)subqueryCleaned; } public Type? inMList = null; protected internal override Expression VisitMListProjection(MListProjectionExpression mlp) { var oldInEntity = inMList; inMList = mlp.Type; var result = VisitProjection(mlp.Projection); inMList = oldInEntity; return result; } protected internal override Expression VisitProjection(ProjectionExpression proj) { if (currentSource == null) { currentSource = WithoutOrder(proj.Select); Expression projector = this.Visit(proj.Projector); if (projector != proj.Projector) proj = new ProjectionExpression(proj.Select, projector, proj.UniqueFunction, proj.Type); currentSource = null; return proj; } else { HashSet<ColumnExpression> columns = ExternalColumnGatherer.Gatherer(proj, currentSource.Alias); if (columns.Count == 0) { Expression projector = Visit(proj.Projector); ConstantExpression key = Expression.Constant(0); Type kvpType = typeof(KeyValuePair<,>).MakeGenericType(key.Type, projector.Type); ConstructorInfo ciKVP = kvpType.GetConstructor(new[] { key.Type, projector.Type })!; Type projType = proj.UniqueFunction == null ? typeof(IEnumerable<>).MakeGenericType(kvpType) : kvpType; var childProj = new ProjectionExpression(proj.Select, Expression.New(ciKVP, key, projector), proj.UniqueFunction, projType); return new ChildProjectionExpression(childProj, Expression.Constant(0), inMList != null, inMList ?? proj.Type, new LookupToken()); } else { SelectExpression external; IEnumerable<ColumnExpression> externalColumns; if (!IsKey(currentSource, columns)) { Alias aliasDistinct = aliasGenerator.GetUniqueAlias(currentSource.Alias.Name + "D"); ColumnGenerator generatorDistinct = new ColumnGenerator(); List<ColumnDeclaration> columnDistinct = columns.Select(ce => generatorDistinct.MapColumn(ce)).ToList(); external = new SelectExpression(aliasDistinct, true, null, columnDistinct, currentSource, null, null, null, 0); Dictionary<ColumnExpression, ColumnExpression> distinctReplacements = columnDistinct.ToDictionary( cd => (ColumnExpression)cd.Expression, cd => cd.GetReference(aliasDistinct)); proj = (ProjectionExpression)ColumnReplacer.Replace(proj, distinctReplacements); externalColumns = distinctReplacements.Values.ToHashSet(); } else { external = currentSource; externalColumns = columns; } ColumnGenerator generatorSM = new ColumnGenerator(); List<ColumnDeclaration> columnsSMExternal = externalColumns.Select(ce => generatorSM.MapColumn(ce)).ToList(); List<ColumnDeclaration> columnsSMInternal = proj.Select.Columns.Select(cd => generatorSM.MapColumn(cd.GetReference(proj.Select.Alias))).ToList(); SelectExpression @internal = ExtractOrders(proj.Select, out List<OrderExpression>? innerOrders); Alias aliasSM = aliasGenerator.GetUniqueAlias(@internal.Alias.Name + "SM"); SelectExpression selectMany = new SelectExpression(aliasSM, false, null, columnsSMExternal.Concat(columnsSMInternal), new JoinExpression(JoinType.CrossApply, external, @internal, null), null, innerOrders, null, 0); SelectExpression old = currentSource; currentSource = WithoutOrder(selectMany); var selectManyReplacements = selectMany.Columns.ToDictionary( cd => (ColumnExpression)cd.Expression, cd => cd.GetReference(aliasSM)); Expression projector = ColumnReplacer.Replace(proj.Projector, selectManyReplacements); projector = Visit(projector); currentSource = old; Expression key = TupleReflection.TupleChainConstructor(columnsSMExternal.Select(cd => MakeEquatable(cd.GetReference(aliasSM)))); Type kvpType = typeof(KeyValuePair<,>).MakeGenericType(key.Type, projector.Type); ConstructorInfo ciKVP = kvpType.GetConstructor(new[] { key.Type, projector.Type })!; Type projType = proj.UniqueFunction == null ? typeof(IEnumerable<>).MakeGenericType(kvpType) : kvpType; var childProj = new ProjectionExpression(selectMany, Expression.New(ciKVP, key, projector), proj.UniqueFunction, projType); return new ChildProjectionExpression(childProj, TupleReflection.TupleChainConstructor(columns.Select(a => MakeEquatable(a))), inMList != null, inMList ?? proj.Type, new LookupToken()); } } } public static Expression MakeEquatable(Expression expression) { if (expression.Type.IsArray) return Expression.New(typeof(ArrayBox<>).MakeGenericType(expression.Type.ElementType()!).GetConstructors().SingleEx(), expression); return expression.Nullify(); } private static SelectExpression WithoutOrder(SelectExpression sel) { if (sel.Top != null || (sel.OrderBy.Count == 0)) return sel; return new SelectExpression(sel.Alias, sel.IsDistinct, sel.Top, sel.Columns, sel.From, sel.Where, null, sel.GroupBy, sel.SelectOptions); } private static SelectExpression ExtractOrders(SelectExpression sel, out List<OrderExpression>? innerOrders) { if (sel.Top != null || (sel.OrderBy.Count == 0)) { innerOrders = null; return sel; } else { ColumnGenerator cg = new ColumnGenerator(sel.Columns); Dictionary<OrderExpression, ColumnDeclaration> newColumns = sel.OrderBy.ToDictionary(o => o, o => cg.NewColumn(o.Expression)); innerOrders = newColumns.Select(kvp => new OrderExpression(kvp.Key.OrderType, kvp.Value.GetReference(sel.Alias))).ToList(); return new SelectExpression(sel.Alias, sel.IsDistinct, sel.Top, sel.Columns.Concat(newColumns.Values), sel.From, sel.Where, null, sel.GroupBy, sel.SelectOptions); } } private static bool IsKey(SelectExpression source, HashSet<ColumnExpression> columns) { var keys = KeyFinder.Keys(source); return keys.All(k => k != null && columns.Contains(k)); } internal static class KeyFinder { public static IEnumerable<ColumnExpression?> Keys(SourceExpression source) { if (source is SelectExpression se) return KeysSelect(se); if (source is TableExpression te) return KeysTable(te); if(source is JoinExpression je) return KeysJoin(je); if (source is SetOperatorExpression soe) return KeysSet(soe); throw new InvalidOperationException("Unexpected source"); } private static IEnumerable<ColumnExpression?> KeysSet(SetOperatorExpression set) { return Keys(set.Left).Concat(Keys(set.Right)); } private static IEnumerable<ColumnExpression?> KeysJoin(JoinExpression join) { switch (join.JoinType) { case JoinType.SingleRowLeftOuterJoin: return Keys(join.Left); case JoinType.CrossApply: { var leftKeys = Keys(join.Left); var rightKeys = Keys(join.Right); var onlyLeftKey = leftKeys.Only(); if(onlyLeftKey != null && join.Right is SelectExpression r && r.Where is BinaryExpression b && b.NodeType == ExpressionType.Equal && b.Left is ColumnExpression cLeft && b.Right is ColumnExpression cRight) { if(cLeft.Equals(onlyLeftKey) ^ cRight.Equals(onlyLeftKey)) { var other = b.Left == onlyLeftKey ? b.Right : b.Left; if (other is ColumnExpression c && join.Right.KnownAliases.Contains(c.Alias)) return rightKeys; } } return leftKeys.Concat(rightKeys); } case JoinType.CrossJoin: case JoinType.InnerJoin: case JoinType.OuterApply: case JoinType.LeftOuterJoin: case JoinType.RightOuterJoin: case JoinType.FullOuterJoin: return Keys(join.Left).Concat(Keys(join.Right)); default: break; } throw new InvalidOperationException("Unexpected Join Type"); } private static IEnumerable<ColumnExpression> KeysTable(TableExpression table) { if (table.Table is Table t && t.IsView) return t.Columns.Values.Where(c => c.PrimaryKey).Select(c => new ColumnExpression(c.Type, table.Alias, c.Name)); else return new[] { new ColumnExpression(typeof(int), table.Alias, table.Table.PrimaryKey.Name) }; } private static IEnumerable<ColumnExpression?> KeysSelect(SelectExpression select) { if (select.GroupBy.Any()) return select.GroupBy.Select(ce => select.Columns.FirstOrDefault(cd => cd.Expression.Equals(ce) /*could be improved*/)?.Let(cd => cd.GetReference(select.Alias))).ToList(); IEnumerable<ColumnExpression?> inner = Keys(select.From!); var result = inner.Select(ce => select.Columns.FirstOrDefault(cd => cd.Expression.Equals(ce))?.Let(cd => cd.GetReference(select.Alias))).ToList(); if (!select.IsDistinct) return result; var result2 = select.Columns.Select(cd => (ColumnExpression?)cd.GetReference(select.Alias)).ToList(); if (result.Any(c => c == null)) return result2; if (result2.Any(c => c == null)) return result; return result.Count > result2.Count ? result2 : result; } } internal class ColumnReplacer : DbExpressionVisitor { readonly Dictionary<ColumnExpression, ColumnExpression> Replacements; public ColumnReplacer(Dictionary<ColumnExpression, ColumnExpression> replacements) { Replacements = replacements; } public static Expression Replace(Expression expression, Dictionary<ColumnExpression, ColumnExpression> replacements) { return new ColumnReplacer(replacements).Visit(expression); } protected internal override Expression VisitColumn(ColumnExpression column) { return Replacements.TryGetC(column) ?? base.VisitColumn(column); } protected internal override Expression VisitChildProjection(ChildProjectionExpression child) { return child; } } internal class ExternalColumnGatherer : DbExpressionVisitor { readonly Alias externalAlias; readonly HashSet<ColumnExpression> columns = new HashSet<ColumnExpression>(); public ExternalColumnGatherer(Alias externalAlias) { this.externalAlias = externalAlias; } public static HashSet<ColumnExpression> Gatherer(Expression source, Alias externalAlias) { ExternalColumnGatherer ap = new ExternalColumnGatherer(externalAlias); ap.Visit(source); return ap.columns; } protected internal override Expression VisitColumn(ColumnExpression column) { if (externalAlias == column.Alias) columns.Add(column); return base.VisitColumn(column); } } } class ArrayBox<T> : IEquatable<ArrayBox<T>> { readonly int hashCode; public readonly T[]? Array; public ArrayBox(T[]? array) { this.Array = array; this.hashCode = 0; if(array != null) { foreach (var item in array) { this.hashCode = (this.hashCode << 1) ^ (item == null ? 0 : item.GetHashCode()); } } } public override int GetHashCode() => hashCode; public override bool Equals(object? obj) => obj is ArrayBox<T> a && Equals(a); public bool Equals([AllowNull]ArrayBox<T> other) => other != null && Enumerable.SequenceEqual(Array!, other.Array!); }
using System; using System.Collections; using System.Text; using System.Collections.Generic; /* Based on the JSON parser from * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * I simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. */ /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable. /// All numbers are parsed to doubles. /// </summary> public class MiniJSON { private const int TOKEN_NONE = 0; private const int TOKEN_CURLY_OPEN = 1; private const int TOKEN_CURLY_CLOSE = 2; private const int TOKEN_SQUARED_OPEN = 3; private const int TOKEN_SQUARED_CLOSE = 4; private const int TOKEN_COLON = 5; private const int TOKEN_COMMA = 6; private const int TOKEN_STRING = 7; private const int TOKEN_NUMBER = 8; private const int TOKEN_TRUE = 9; private const int TOKEN_FALSE = 10; private const int TOKEN_NULL = 11; private const int BUILDER_CAPACITY = 2000; /// <summary> /// On decoding, this value holds the position at which the parse failed (-1 = no error). /// </summary> protected static int lastErrorIndex = -1; protected static string lastDecode = ""; /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns> public static object jsonDecode( string json ) { // save the string for debug information MiniJSON.lastDecode = json; if( json != null ) { char[] charArray = json.ToCharArray(); int index = 0; bool success = true; object value = MiniJSON.parseValue( charArray, ref index, ref success ); if( success ) MiniJSON.lastErrorIndex = -1; else MiniJSON.lastErrorIndex = index; return value; } else { return null; } } /// <summary> /// Converts a Hashtable / ArrayList / Dictionary(string,string) object into a JSON string /// </summary> /// <param name="json">A Hashtable / ArrayList</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string jsonEncode( object json ) { var builder = new StringBuilder( BUILDER_CAPACITY ); var success = MiniJSON.serializeValue( json, builder ); return ( success ? builder.ToString() : null ); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static bool lastDecodeSuccessful() { return ( MiniJSON.lastErrorIndex == -1 ); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static int getLastErrorIndex() { return MiniJSON.lastErrorIndex; } /// <summary> /// If a decoding error occurred, this function returns a piece of the JSON string /// at which the error took place. To ease debugging. /// </summary> /// <returns></returns> public static string getLastErrorSnippet() { if( MiniJSON.lastErrorIndex == -1 ) { return ""; } else { int startIndex = MiniJSON.lastErrorIndex - 5; int endIndex = MiniJSON.lastErrorIndex + 15; if( startIndex < 0 ) startIndex = 0; if( endIndex >= MiniJSON.lastDecode.Length ) endIndex = MiniJSON.lastDecode.Length - 1; return MiniJSON.lastDecode.Substring( startIndex, endIndex - startIndex + 1 ); } } #region Parsing protected static Hashtable parseObject( char[] json, ref int index ) { Hashtable table = new Hashtable(); int token; // { nextToken( json, ref index ); bool done = false; while( !done ) { token = lookAhead( json, index ); if( token == MiniJSON.TOKEN_NONE ) { return null; } else if( token == MiniJSON.TOKEN_COMMA ) { nextToken( json, ref index ); } else if( token == MiniJSON.TOKEN_CURLY_CLOSE ) { nextToken( json, ref index ); return table; } else { // name string name = parseString( json, ref index ); if( name == null ) { return null; } // : token = nextToken( json, ref index ); if( token != MiniJSON.TOKEN_COLON ) return null; // value bool success = true; object value = parseValue( json, ref index, ref success ); if( !success ) return null; table[name] = value; } } return table; } protected static ArrayList parseArray( char[] json, ref int index ) { ArrayList array = new ArrayList(); // [ nextToken( json, ref index ); bool done = false; while( !done ) { int token = lookAhead( json, index ); if( token == MiniJSON.TOKEN_NONE ) { return null; } else if( token == MiniJSON.TOKEN_COMMA ) { nextToken( json, ref index ); } else if( token == MiniJSON.TOKEN_SQUARED_CLOSE ) { nextToken( json, ref index ); break; } else { bool success = true; object value = parseValue( json, ref index, ref success ); if( !success ) return null; array.Add( value ); } } return array; } protected static object parseValue( char[] json, ref int index, ref bool success ) { switch( lookAhead( json, index ) ) { case MiniJSON.TOKEN_STRING: return parseString( json, ref index ); case MiniJSON.TOKEN_NUMBER: return parseNumber( json, ref index ); case MiniJSON.TOKEN_CURLY_OPEN: return parseObject( json, ref index ); case MiniJSON.TOKEN_SQUARED_OPEN: return parseArray( json, ref index ); case MiniJSON.TOKEN_TRUE: nextToken( json, ref index ); return Boolean.Parse( "TRUE" ); case MiniJSON.TOKEN_FALSE: nextToken( json, ref index ); return Boolean.Parse( "FALSE" ); case MiniJSON.TOKEN_NULL: nextToken( json, ref index ); return null; case MiniJSON.TOKEN_NONE: break; } success = false; return null; } protected static string parseString( char[] json, ref int index ) { string s = ""; char c; eatWhitespace( json, ref index ); // " c = json[index++]; bool complete = false; while( !complete ) { if( index == json.Length ) break; c = json[index++]; if( c == '"' ) { complete = true; break; } else if( c == '\\' ) { if( index == json.Length ) break; c = json[index++]; if( c == '"' ) { s += '"'; } else if( c == '\\' ) { s += '\\'; } else if( c == '/' ) { s += '/'; } else if( c == 'b' ) { s += '\b'; } else if( c == 'f' ) { s += '\f'; } else if( c == 'n' ) { s += '\n'; } else if( c == 'r' ) { s += '\r'; } else if( c == 't' ) { s += '\t'; } else if( c == 'u' ) { int remainingLength = json.Length - index; if( remainingLength >= 4 ) { char[] unicodeCharArray = new char[4]; Array.Copy( json, index, unicodeCharArray, 0, 4 ); // Drop in the HTML markup for the unicode character s += "&#x" + new string( unicodeCharArray ) + ";"; /* uint codePoint = UInt32.Parse(new string(unicodeCharArray), NumberStyles.HexNumber); // convert the integer codepoint to a unicode char and add to string s += Char.ConvertFromUtf32((int)codePoint); */ // skip 4 chars index += 4; } else { break; } } } else { s += c; } } if( !complete ) return null; return s; } protected static double parseNumber( char[] json, ref int index ) { eatWhitespace( json, ref index ); int lastIndex = getLastIndexOfNumber( json, index ); int charLength = ( lastIndex - index ) + 1; char[] numberCharArray = new char[charLength]; Array.Copy( json, index, numberCharArray, 0, charLength ); index = lastIndex + 1; return Double.Parse( new string( numberCharArray ) ); // , CultureInfo.InvariantCulture); } protected static int getLastIndexOfNumber( char[] json, int index ) { int lastIndex; for( lastIndex = index; lastIndex < json.Length; lastIndex++ ) if( "0123456789+-.eE".IndexOf( json[lastIndex] ) == -1 ) { break; } return lastIndex - 1; } protected static void eatWhitespace( char[] json, ref int index ) { for( ; index < json.Length; index++ ) if( " \t\n\r".IndexOf( json[index] ) == -1 ) { break; } } protected static int lookAhead( char[] json, int index ) { int saveIndex = index; return nextToken( json, ref saveIndex ); } protected static int nextToken( char[] json, ref int index ) { eatWhitespace( json, ref index ); if( index == json.Length ) { return MiniJSON.TOKEN_NONE; } char c = json[index]; index++; switch( c ) { case '{': return MiniJSON.TOKEN_CURLY_OPEN; case '}': return MiniJSON.TOKEN_CURLY_CLOSE; case '[': return MiniJSON.TOKEN_SQUARED_OPEN; case ']': return MiniJSON.TOKEN_SQUARED_CLOSE; case ',': return MiniJSON.TOKEN_COMMA; case '"': return MiniJSON.TOKEN_STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return MiniJSON.TOKEN_NUMBER; case ':': return MiniJSON.TOKEN_COLON; } index--; int remainingLength = json.Length - index; // false if( remainingLength >= 5 ) { if( json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e' ) { index += 5; return MiniJSON.TOKEN_FALSE; } } // true if( remainingLength >= 4 ) { if( json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e' ) { index += 4; return MiniJSON.TOKEN_TRUE; } } // null if( remainingLength >= 4 ) { if( json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l' ) { index += 4; return MiniJSON.TOKEN_NULL; } } return MiniJSON.TOKEN_NONE; } #endregion #region Serialization protected static bool serializeObjectOrArray( object objectOrArray, StringBuilder builder ) { if( objectOrArray is Hashtable ) { return serializeObject( (Hashtable)objectOrArray, builder ); } else if( objectOrArray is ArrayList ) { return serializeArray( (ArrayList)objectOrArray, builder ); } else { return false; } } protected static bool serializeObject( Hashtable anObject, StringBuilder builder ) { builder.Append( "{" ); IDictionaryEnumerator e = anObject.GetEnumerator(); bool first = true; while( e.MoveNext() ) { string key = e.Key.ToString(); object value = e.Value; if( !first ) { builder.Append( ", " ); } serializeString( key, builder ); builder.Append( ":" ); if( !serializeValue( value, builder ) ) { return false; } first = false; } builder.Append( "}" ); return true; } protected static bool serializeDictionary( Dictionary<string,string> dict, StringBuilder builder ) { builder.Append( "{" ); bool first = true; foreach( var kv in dict ) { if( !first ) builder.Append( ", " ); serializeString( kv.Key, builder ); builder.Append( ":" ); serializeString( kv.Value, builder ); first = false; } builder.Append( "}" ); return true; } protected static bool serializeArray( ArrayList anArray, StringBuilder builder ) { builder.Append( "[" ); bool first = true; for( int i = 0; i < anArray.Count; i++ ) { object value = anArray[i]; if( !first ) { builder.Append( ", " ); } if( !serializeValue( value, builder ) ) { return false; } first = false; } builder.Append( "]" ); return true; } protected static bool serializeValue( object value, StringBuilder builder ) { // Type t = value.GetType(); // Debug.Log("type: " + t.ToString() + " isArray: " + t.IsArray); if( value == null ) { builder.Append( "null" ); } else if( value.GetType().IsArray ) { serializeArray( new ArrayList( (ICollection)value ), builder ); } else if( value is string ) { serializeString( (string)value, builder ); } else if( value is Char ) { serializeString( Convert.ToString( (char)value ), builder ); } else if( value is Hashtable ) { serializeObject( (Hashtable)value, builder ); } else if( value is Dictionary<string,string> ) { serializeDictionary( (Dictionary<string,string>)value, builder ); } else if( value is ArrayList ) { serializeArray( (ArrayList)value, builder ); } else if( ( value is Boolean ) && ( (Boolean)value == true ) ) { builder.Append( "true" ); } else if( ( value is Boolean ) && ( (Boolean)value == false ) ) { builder.Append( "false" ); } else if( value.GetType().IsPrimitive ) { serializeNumber( Convert.ToDouble( value ), builder ); } else { return false; } return true; } protected static void serializeString( string aString, StringBuilder builder ) { builder.Append( "\"" ); char[] charArray = aString.ToCharArray(); for( int i = 0; i < charArray.Length; i++ ) { char c = charArray[i]; if( c == '"' ) { builder.Append( "\\\"" ); } else if( c == '\\' ) { builder.Append( "\\\\" ); } else if( c == '\b' ) { builder.Append( "\\b" ); } else if( c == '\f' ) { builder.Append( "\\f" ); } else if( c == '\n' ) { builder.Append( "\\n" ); } else if( c == '\r' ) { builder.Append( "\\r" ); } else if( c == '\t' ) { builder.Append( "\\t" ); } else { int codepoint = Convert.ToInt32( c ); if( ( codepoint >= 32 ) && ( codepoint <= 126 ) ) { builder.Append( c ); } else { builder.Append( "\\u" + Convert.ToString( codepoint, 16 ).PadLeft( 4, '0' ) ); } } } builder.Append( "\"" ); } protected static void serializeNumber( double number, StringBuilder builder ) { builder.Append( Convert.ToString( number ) ); // , CultureInfo.InvariantCulture)); } #endregion } #region Extension methods public static class MiniJsonExtensions { public static string toJson( this Hashtable obj ) { return MiniJSON.jsonEncode( obj ); } public static string toJson( this Dictionary<string,string> obj ) { return MiniJSON.jsonEncode( obj ); } public static ArrayList arrayListFromJson( this string json ) { return MiniJSON.jsonDecode( json ) as ArrayList; } public static Hashtable hashtableFromJson( this string json ) { return MiniJSON.jsonDecode( json ) as Hashtable; } } #endregion
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text; using System.IO; using System.Net; namespace WebsitePanel.AWStats.Viewer { public partial class Default : System.Web.UI.Page { private void Page_Load(object sender, EventArgs e) { string username = Request["username"]; string password = Request["password"]; if (Request.IsAuthenticated) { string identity = Context.User.Identity.Name; string domain = identity.Split('=')[0]; if (String.Compare(Request["config"], domain, true) != 0) { FormsAuthentication.SignOut(); domain = Request["domain"]; if (!String.IsNullOrEmpty(domain) && !String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password)) { // perform login txtUsername.Text = username; txtDomain.Text = domain; Login(domain, username, password); } else { Response.Redirect(Request.Url.AbsolutePath); } } Response.Clear(); string queryParams = Request.Url.Query; string awStatsUrl = AWStatsUrl; if (awStatsUrl.IndexOf(":") == -1) { string appUrl = Request.Url.ToString(); appUrl = appUrl.Substring(0, appUrl.LastIndexOf("/")); awStatsUrl = appUrl + awStatsUrl; } string awStatsPage = GetWebDocument(awStatsUrl + queryParams); // replace links awStatsPage = awStatsPage.Replace(AWStatsScript, Request.Url.AbsolutePath); Response.Write(awStatsPage); Response.End(); } else { lblMessage.Visible = false; if (!IsPostBack) { string domain = Request["domain"]; if (String.IsNullOrEmpty(domain)) domain = Request["config"]; txtDomain.Text = domain; if (!String.IsNullOrEmpty(username)) txtUsername.Text = username; // check for autologin if (!String.IsNullOrEmpty(domain) && !String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password)) { // perform login Login(domain, username, password); } } } } protected void btnView_Click(object sender, EventArgs e) { if (!Page.IsValid) return; // perform login Login(txtDomain.Text.Trim(), txtUsername.Text.Trim(), txtPassword.Text); } private void Login(string domain, string username, string password) { // check user AuthenticationResult result = AuthenticationProvider.Instance.AuthenticateUser(domain, username, password); if (result == AuthenticationResult.OK) { FormsAuthentication.SetAuthCookie(domain + "=" + username, false); Response.Redirect(Request.Url.AbsolutePath + "?config=" + domain); } // show error message lblMessage.Text = ConfigurationManager.AppSettings["AWStats.Message.DomainNotFound"]; if (result == AuthenticationResult.WrongUsername) lblMessage.Text = ConfigurationManager.AppSettings["AWStats.Message.WrongUsername"]; else if (result == AuthenticationResult.WrongPassword) lblMessage.Text = ConfigurationManager.AppSettings["AWStats.Message.WrongPassword"]; lblMessage.Visible = true; } #region Private Helpers private string GetWebDocument(string url) { HttpWebResponse result = null; StringBuilder sb = new StringBuilder(); try { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); string lang = Request.Headers["Accept-Language"]; req.Headers["Accept-Language"] = lang; string username = ConfigurationManager.AppSettings["AWStats.Username"]; if (username != null && username != "") { string password = ConfigurationManager.AppSettings["AWStats.Password"]; string domain = null; int sepIdx = username.IndexOf("\\"); if (sepIdx != -1) { domain = username.Substring(0, sepIdx); username = username.Substring(sepIdx + 1); } req.Credentials = new NetworkCredential(username, password, domain); } else { req.Credentials = CredentialCache.DefaultNetworkCredentials; } result = (HttpWebResponse)req.GetResponse(); Stream ReceiveStream = result.GetResponseStream(); string respEnc = !String.IsNullOrEmpty(result.ContentEncoding) ? result.ContentEncoding : "utf-8"; Encoding encode = System.Text.Encoding.GetEncoding(respEnc); StreamReader sr = new StreamReader(ReceiveStream, encode); Char[] read = new Char[256]; int count = sr.Read(read, 0, 256); while (count > 0) { String str = new String(read, 0, count); sb.Append(str); count = sr.Read(read, 0, 256); } } catch (WebException ex) { Response.Write("Error while opening '" + url + "': " + ex.Message); } catch (Exception ex) { Response.Write(ex.ToString()); } finally { if (result != null) { result.Close(); } } return sb.ToString(); } private string AWStatsUrl { get { return ConfigurationManager.AppSettings["AWStats.URL"]; } } private string AWStatsScript { get { int idx = AWStatsUrl.LastIndexOf("/"); return (idx == -1) ? AWStatsUrl : AWStatsUrl.Substring(idx + 1); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // This file isn't built into the .csproj in corefx but is consumed by Mono. namespace System.Drawing.Design { using System.Configuration.Assemblies; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.ComponentModel; using System.Diagnostics; using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.ComponentModel.Design; using Microsoft.Win32; using System.Drawing; using System.IO; using System.Text; using System.Security; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; using System.Runtime.Versioning; using DpiHelper = System.Windows.Forms.DpiHelper; /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem"]/*' /> /// <devdoc> /// <para> Provides a base implementation of a toolbox item.</para> /// </devdoc> [Serializable] public class ToolboxItem : ISerializable { private static TraceSwitch ToolboxItemPersist = new TraceSwitch("ToolboxPersisting", "ToolboxItem: write data"); private static object EventComponentsCreated = new object(); private static object EventComponentsCreating = new object(); private static bool isScalingInitialized = false; private const int ICON_DIMENSION = 16; private static int iconWidth = ICON_DIMENSION; private static int iconHeight = ICON_DIMENSION; private bool locked; private LockableDictionary properties; private ToolboxComponentsCreatedEventHandler componentsCreatedEvent; private ToolboxComponentsCreatingEventHandler componentsCreatingEvent; /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToolboxItem"]/*' /> /// <devdoc> /// Initializes a new instance of the ToolboxItem class. /// </devdoc> public ToolboxItem() { if (!isScalingInitialized) { if (DpiHelper.IsScalingRequired) { iconWidth = DpiHelper.LogicalToDeviceUnitsX(ICON_DIMENSION); iconHeight = DpiHelper.LogicalToDeviceUnitsY(ICON_DIMENSION); } isScalingInitialized = true; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToolboxItem1"]/*' /> /// <devdoc> /// Initializes a new instance of the ToolboxItem class using the specified type. /// </devdoc> public ToolboxItem(Type toolType) : this() { Initialize(toolType); } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToolboxItem2"]/*' /> /// <devdoc> /// Initializes a new instance of the <see cref='System.Drawing.Design.ToolboxItem'/> /// class using the specified serialization information. /// </devdoc> #pragma warning disable CA2229 // We don't care about serialization constructors. private ToolboxItem(SerializationInfo info, StreamingContext context) : this() #pragma warning restore CA2229 { Deserialize(info, context); } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.AssemblyName"]/*' /> /// <devdoc> /// The assembly name for this toolbox item. The assembly name describes the assembly /// information needed to load the toolbox item's type. /// </devdoc> public AssemblyName AssemblyName { get { return (AssemblyName)Properties["AssemblyName"]; } set { Properties["AssemblyName"] = value; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.AssemblyName"]/*' /> /// <devdoc> /// The assembly name for this toolbox item. The assembly name describes the assembly /// information needed to load the toolbox item's type. /// </devdoc> public AssemblyName[] DependentAssemblies { get { AssemblyName[] names = (AssemblyName[]) Properties["DependentAssemblies"]; if (names != null) { return (AssemblyName[]) names.Clone(); } return null; } set { Properties["DependentAssemblies"] = value.Clone(); } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Bitmap"]/*' /> /// <devdoc> /// Gets or sets the bitmap that will be used on the toolbox for this item. /// Use this property on the design surface as this bitmap is scaled according to the current the DPI setting. /// </devdoc> public Bitmap Bitmap { get { return (Bitmap)Properties["Bitmap"]; } set { Properties["Bitmap"] = value; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.OriginalBitmap"]/*' /> /// <devdoc> /// Gets or sets the original bitmap that will be used on the toolbox for this item. /// This bitmap should be 16x16 pixel and should be used in the Visual Studio toolbox, not on the design surface. /// </devdoc> public Bitmap OriginalBitmap { get { return (Bitmap)Properties["OriginalBitmap"]; } set { Properties["OriginalBitmap"] = value; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Company"]/*' /> /// <devdoc> /// Gets or sets the company name for this <see cref='System.Drawing.Design.ToolboxItem'/>. /// This defaults to the companyname attribute retrieved from type.Assembly, if set. /// </devdoc> public string Company { get { return (string)Properties["Company"]; } set { Properties["Company"] = value; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ComponentType"]/*' /> /// <devdoc> /// The Component Type is ".Net Component" -- unless otherwise specified by a derived toolboxitem /// </devdoc> public virtual string ComponentType { get { return SR.Format(SR.DotNET_ComponentType); } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Description"]/*' /> /// <devdoc> /// Description is a free-form, multiline capable text description that will be displayed in the tooltip /// for the toolboxItem. It defaults to the path of the assembly that contains the item, but can be overridden. /// </devdoc> public string Description { get { return (string)Properties["Description"]; } set { Properties["Description"] = value; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.DisplayName"]/*' /> /// <devdoc> /// Gets or sets the display name for this <see cref='System.Drawing.Design.ToolboxItem'/>. /// </devdoc> public string DisplayName { get { return (string)Properties["DisplayName"]; } set { Properties["DisplayName"] = value; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Filter"]/*' /> /// <devdoc> /// Gets or sets the filter for this toolbox item. The filter is a collection of /// ToolboxItemFilterAttribute objects. /// </devdoc> public ICollection Filter { get { return (ICollection)Properties["Filter"]; } set { Properties["Filter"] = value; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.IsTransient"]/*' /> /// <devdoc> /// If true, it indicates that this toolbox item should not be stored in /// any toolbox database when an application that is providing a toolbox /// closes down. This property defaults to false. /// </devdoc> public bool IsTransient { [SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")] get { return (bool)Properties["IsTransient"]; } set { Properties["IsTransient"] = value; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Locked"]/*' /> /// <devdoc> /// Determines if this toolbox item is locked. Once locked, a toolbox item will /// not accept any changes to its properties. /// </devdoc> public virtual bool Locked { get { return locked; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Properties"]/*' /> /// <devdoc> /// The properties dictionary is a set of name/value pairs. The keys are property /// names and the values are property values. This dictionary becomes read-only /// after the toolbox item has been locked. /// /// Values in the properties dictionary are validated through ValidateProperty /// and default values are obtained from GetDefalutProperty. /// </devdoc> public IDictionary Properties { get { if (properties == null) { properties = new LockableDictionary(this, 8 /* # of properties we have */); } return properties; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.TypeName"]/*' /> /// <devdoc> /// Gets or sets the fully qualified name of the type this toolbox item will create. /// </devdoc> public string TypeName { get { return (string)Properties["TypeName"]; } set { Properties["TypeName"] = value; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.DisplayName"]/*' /> /// <devdoc> /// Gets the version for this toolboxitem. It defaults to AssemblyName.Version unless /// overridden in a derived toolboxitem. This can be overridden to return an empty string /// to suppress its display in the toolbox tooltip. /// </devdoc> public virtual string Version { get { if (this.AssemblyName != null) { return this.AssemblyName.Version.ToString(); } return string.Empty; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ComponentsCreated"]/*' /> /// <devdoc> /// <para>Occurs when components are created.</para> /// </devdoc> public event ToolboxComponentsCreatedEventHandler ComponentsCreated { add { componentsCreatedEvent += value; } remove { componentsCreatedEvent -= value; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ComponentsCreating"]/*' /> /// <devdoc> /// <para>Occurs before components are created.</para> /// </devdoc> public event ToolboxComponentsCreatingEventHandler ComponentsCreating { add { componentsCreatingEvent += value; } remove { componentsCreatingEvent -= value; } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CheckUnlocked"]/*' /> /// <devdoc> /// This method checks that the toolbox item is currently unlocked (read-write) and /// throws an appropriate exception if it isn't. /// </devdoc> protected void CheckUnlocked() { if (Locked) throw new InvalidOperationException(SR.Format(SR.ToolboxItemLocked)); } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponents"]/*' /> /// <devdoc> /// Creates objects from the type contained in this toolbox item. /// </devdoc> public IComponent[] CreateComponents() { return CreateComponents(null); } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponents1"]/*' /> /// <devdoc> /// Creates objects from the type contained in this toolbox item. If designerHost is non-null /// this will also add them to the designer. /// </devdoc> public IComponent[] CreateComponents(IDesignerHost host) { OnComponentsCreating(new ToolboxComponentsCreatingEventArgs(host)); IComponent[] comps = CreateComponentsCore(host, new Hashtable()); if (comps != null && comps.Length > 0) { OnComponentsCreated(new ToolboxComponentsCreatedEventArgs(comps)); } return comps; } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponents2"]/*' /> /// <devdoc> /// Creates objects from the type contained in this toolbox item. If designerHost is non-null /// this will also add them to the designer. /// </devdoc> public IComponent[] CreateComponents(IDesignerHost host, IDictionary defaultValues) { OnComponentsCreating(new ToolboxComponentsCreatingEventArgs(host)); IComponent[] comps = CreateComponentsCore(host, defaultValues); if (comps != null && comps.Length > 0) { OnComponentsCreated(new ToolboxComponentsCreatedEventArgs(comps)); } return comps; } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponentsCore"]/*' /> /// <devdoc> /// Creates objects from the type contained in this toolbox item. If designerHost is non-null /// this will also add them to the designer. /// </devdoc> protected virtual IComponent[] CreateComponentsCore(IDesignerHost host) { ArrayList comps = new ArrayList(); Type createType = GetType(host, AssemblyName, TypeName, true); if (createType != null) { if (host != null) { comps.Add(host.CreateComponent(createType)); } else if (typeof(IComponent).IsAssignableFrom(createType)) { comps.Add(TypeDescriptor.CreateInstance(null, createType, null, null)); } } IComponent[] temp = new IComponent[comps.Count]; comps.CopyTo(temp, 0); return temp; } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponentsCore1"]/*' /> /// <devdoc> /// Creates objects from the type contained in this toolbox item. If designerHost is non-null /// this will also add them to the designer. /// </devdoc> protected virtual IComponent[] CreateComponentsCore(IDesignerHost host, IDictionary defaultValues) { IComponent[] components = CreateComponentsCore(host); if (host != null) { for (int i = 0; i < components.Length; i++) { IComponentInitializer init = host.GetDesigner(components[i]) as IComponentInitializer; if (init != null) { bool removeComponent = true; try { init.InitializeNewComponent(defaultValues); removeComponent = false; } finally { if (removeComponent) { for (int index = 0; index < components.Length; index++) { host.DestroyComponent(components[index]); } } } } } } return components; } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Deserialize"]/*' /> /// <devdoc> /// <para>Loads the state of this <see cref='System.Drawing.Design.ToolboxItem'/> /// from the stream.</para> /// </devdoc> protected virtual void Deserialize(SerializationInfo info, StreamingContext context) { // Do this in a couple of passes -- first pass, try to pull // out our dictionary of property names. We need to do this // for backwards compatibilty because if we throw everything // into the property dictionary we'll duplicate stuff people // have serialized by hand. string[] propertyNames = null; foreach (SerializationEntry entry in info) { if (entry.Name.Equals("PropertyNames")) { propertyNames = entry.Value as string[]; break; } } if (propertyNames == null) { // For backwards compat, here are the default property // names we use propertyNames = new string[] { "AssemblyName", "Bitmap", "DisplayName", "Filter", "IsTransient", "TypeName" }; } foreach (SerializationEntry entry in info) { // Check to see if this name is in our // propertyNames array. foreach(string validName in propertyNames) { if (validName.Equals(entry.Name)) { Properties[entry.Name] = entry.Value; break; } } } // Always do "Locked" last (otherwise we can't do the others!) bool isLocked = info.GetBoolean("Locked"); if (isLocked) { Lock(); } } /// <devdoc> /// Check if two AssemblyName instances are equivalent /// </devdoc> private static bool AreAssemblyNamesEqual(AssemblyName name1, AssemblyName name2) { return name1 == name2 || (name1 != null && name2 != null && name1.FullName == name2.FullName); } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Equals"]/*' /> /// <internalonly/> public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj.GetType() == this.GetType())) { return false; } ToolboxItem otherItem = (ToolboxItem)obj; return TypeName == otherItem.TypeName && AreAssemblyNamesEqual(AssemblyName, otherItem.AssemblyName) && DisplayName == otherItem.DisplayName; } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.GetHashCode"]/*' /> /// <internalonly/> public override int GetHashCode() { string typeName = TypeName; int hash = (typeName != null) ? typeName.GetHashCode() : 0; return unchecked(hash ^ DisplayName.GetHashCode()); } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.FilterPropertyValue"]/*' /> /// <devdoc> /// Filters a property value before returning it. This allows a property to always clone values, /// or to provide a default value when none exists. /// </devdoc> protected virtual object FilterPropertyValue(string propertyName, object value) { switch (propertyName) { case "AssemblyName": if (value != null) value = ((AssemblyName)value).Clone(); break; case "DisplayName": case "TypeName": if (value == null) value = string.Empty; break; case "Filter": if (value == null) value = Array.Empty<ToolboxItemFilterAttribute>(); break; case "IsTransient": if (value == null) value = false; break; } return value; } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.GetType1"]/*' /> /// <devdoc> /// Allows access to the type associated with the toolbox item. /// The designer host is used to access an implementation of ITypeResolutionService. /// However, the loaded type is not added to the list of references in the designer host. /// </devdoc> public Type GetType(IDesignerHost host) { return GetType(host, AssemblyName, TypeName, false); } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.GetType"]/*' /> /// <devdoc> /// This utility function can be used to load a type given a name. AssemblyName and /// designer host can be null, but if they are present they will be used to help /// locate the type. If reference is true, the given assembly name will be added /// to the designer host's set of references. /// </devdoc> [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] protected virtual Type GetType(IDesignerHost host, AssemblyName assemblyName, string typeName, bool reference) { ITypeResolutionService ts = null; Type type = null; if (typeName == null) { throw new ArgumentNullException(nameof(typeName)); } if (host != null) { ts = (ITypeResolutionService)host.GetService(typeof(ITypeResolutionService)); } if (ts != null) { if (reference) { if (assemblyName != null) { ts.ReferenceAssembly(assemblyName); type = ts.GetType(typeName); } else { // Just try loading the type. If we succeed, then use this as the // reference. type = ts.GetType(typeName); if (type == null) { type = Type.GetType(typeName); } if (type != null) { ts.ReferenceAssembly(type.Assembly.GetName()); } } } else { if (assemblyName != null) { Assembly a = ts.GetAssembly(assemblyName); if (a != null) { type = a.GetType(typeName); } } if (type == null) { type = ts.GetType(typeName); } } } else { if (!string.IsNullOrEmpty(typeName)) { if (assemblyName != null) { Assembly a = null; try { a = Assembly.Load(assemblyName); } catch (FileNotFoundException) { } catch (BadImageFormatException) { } catch (IOException) { } if (a == null && assemblyName.CodeBase != null && assemblyName.CodeBase.Length > 0) { try { a = Assembly.LoadFrom(assemblyName.CodeBase); } catch (FileNotFoundException) { } catch (BadImageFormatException) { } catch (IOException) { } } if (a != null) { type = a.GetType(typeName); } } if (type == null) { type = Type.GetType(typeName, false); } } } return type; } /// <devdoc> /// Given an assemblyname and type, this method searches referenced assemblies from t.Assembly /// looking for a similar name. /// </devdoc> private AssemblyName GetNonRetargetedAssemblyName(Type type, AssemblyName policiedAssemblyName) { if (type == null || policiedAssemblyName == null) return null; //if looking for myself, just return it. (not a reference) if (type.Assembly.FullName == policiedAssemblyName.FullName) { return policiedAssemblyName; } //first search for an exact match -- we prefer this over a partial match. foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) { if (name.FullName == policiedAssemblyName.FullName) return name; } //next search for a partial match -- we just compare the Name portions (ignore version and publickey) foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) { if (name.Name == policiedAssemblyName.Name) return name; } //finally, the most expensive -- its possible that retargeting policy is on an assembly whose name changes // an example of this is the device System.Windows.Forms.Datagrid.dll // in this case, we need to try to load each device assemblyname through policy to see if it results // in assemblyname. foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) { Assembly a = null; try { a = Assembly.Load(name); if (a != null && a.FullName == policiedAssemblyName.FullName) return name; } catch { //ignore all exceptions and just fall through if it fails (it shouldn't, but who knows). } } return null; } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Initialize"]/*' /> /// <devdoc> /// Initializes a toolbox item with a given type. A locked toolbox item cannot be initialized. /// </devdoc> public virtual void Initialize(Type type) { CheckUnlocked(); if (type != null) { TypeName = type.FullName; AssemblyName assemblyName = type.Assembly.GetName(true); if (type.Assembly.GlobalAssemblyCache) { assemblyName.CodeBase = null; } Dictionary<string, AssemblyName> parents = new Dictionary<string, AssemblyName>(); Type parentType = type; while (parentType != null) { AssemblyName policiedname = parentType.Assembly.GetName(true); AssemblyName aname = GetNonRetargetedAssemblyName(type, policiedname); if (aname != null && !parents.ContainsKey(aname.FullName)) { parents[aname.FullName] = aname; } parentType = parentType.BaseType; } AssemblyName[] parentAssemblies = new AssemblyName[parents.Count]; int i = 0; foreach(AssemblyName an in parents.Values) { parentAssemblies[i++] = an; } this.DependentAssemblies = parentAssemblies; AssemblyName = assemblyName; DisplayName = type.Name; //if the Type is a reflectonly type, these values must be set through a config object or manually //after construction. if (!type.Assembly.ReflectionOnly) { object[] companyattrs = type.Assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true); if (companyattrs != null && companyattrs.Length > 0) { AssemblyCompanyAttribute company = companyattrs[0] as AssemblyCompanyAttribute; if (company != null && company.Company != null) { Company = company.Company; } } //set the description based off the description attribute of the given type. DescriptionAttribute descattr = (DescriptionAttribute)TypeDescriptor.GetAttributes(type)[typeof(DescriptionAttribute)]; if (descattr != null) { this.Description = descattr.Description; } ToolboxBitmapAttribute attr = (ToolboxBitmapAttribute)TypeDescriptor.GetAttributes(type)[typeof(ToolboxBitmapAttribute)]; if (attr != null) { Bitmap itemBitmap = attr.GetImage(type, false) as Bitmap; if (itemBitmap != null) { // Original bitmap is used when adding the item to the Visual Studio toolbox // if running on a machine with HDPI scaling enabled. OriginalBitmap = attr.GetOriginalBitmap(); if ((itemBitmap.Width != iconWidth || itemBitmap.Height != iconHeight)) { itemBitmap = new Bitmap(itemBitmap, new Size(iconWidth, iconHeight)); } } Bitmap = itemBitmap; } bool filterContainsType = false; ArrayList array = new ArrayList(); foreach (Attribute a in TypeDescriptor.GetAttributes(type)) { ToolboxItemFilterAttribute ta = a as ToolboxItemFilterAttribute; if (ta != null) { if (ta.FilterString.Equals(TypeName)) { filterContainsType = true; } array.Add(ta); } } if (!filterContainsType) { array.Add(new ToolboxItemFilterAttribute(TypeName)); } Filter = (ToolboxItemFilterAttribute[])array.ToArray(typeof(ToolboxItemFilterAttribute)); } } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Lock"]/*' /> /// <devdoc> /// Locks this toolbox item. Locking a toolbox item makes it read-only and /// prevents any changes to its properties. /// </devdoc> public virtual void Lock() { locked = true; } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.OnComponentsCreated"]/*' /> /// <devdoc> /// <para>Raises the OnComponentsCreated event. This /// will be called when this <see cref='System.Drawing.Design.ToolboxItem'/> creates a component.</para> /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] //full trust anyway protected virtual void OnComponentsCreated(ToolboxComponentsCreatedEventArgs args) { if (componentsCreatedEvent != null) { componentsCreatedEvent(this, args); } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.OnComponentsCreating"]/*' /> /// <devdoc> /// <para>Raises the OnCreateComponentsInvoked event. This /// will be called before this <see cref='System.Drawing.Design.ToolboxItem'/> creates a component.</para> /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] //full trust anyway protected virtual void OnComponentsCreating(ToolboxComponentsCreatingEventArgs args) { if (componentsCreatingEvent != null) { componentsCreatingEvent(this, args); } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Serialize"]/*' /> /// <devdoc> /// <para>Saves the state of this <see cref='System.Drawing.Design.ToolboxItem'/> to /// the specified serialization info.</para> /// </devdoc> [SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")] protected virtual void Serialize(SerializationInfo info, StreamingContext context) { if (ToolboxItemPersist.TraceVerbose) { Debug.WriteLine("Persisting: " + GetType().Name); Debug.WriteLine("\tDisplay Name: " + DisplayName); } info.AddValue("Locked", Locked); ArrayList propertyNames = new ArrayList(Properties.Count); foreach (DictionaryEntry de in Properties) { propertyNames.Add(de.Key); info.AddValue((string)de.Key, de.Value); } info.AddValue("PropertyNames", (string[])propertyNames.ToArray(typeof(string))); } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToString"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override string ToString() { return this.DisplayName; } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ValidatePropertyType"]/*' /> /// <devdoc> /// Called as a helper to ValidatePropertyValue to validate that an object /// is of a given type. /// </devdoc> protected void ValidatePropertyType(string propertyName, object value, Type expectedType, bool allowNull) { if (value == null) { if (!allowNull) { throw new ArgumentNullException(nameof(value)); } } else { if (!expectedType.IsInstanceOfType(value)) { throw new ArgumentException(SR.Format(SR.ToolboxItemInvalidPropertyType, propertyName, expectedType.FullName), nameof(value)); } } } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ValidatePropertyValue"]/*' /> /// <devdoc> /// This is called whenever a value is set in the property dictionary. It gives you a chance /// to change the value of an object before comitting it, our reject it by throwing an /// exception. /// </devdoc> protected virtual object ValidatePropertyValue(string propertyName, object value) { switch (propertyName) { case "AssemblyName": ValidatePropertyType(propertyName, value, typeof(AssemblyName), true); break; case "Bitmap": ValidatePropertyType(propertyName, value, typeof(Bitmap), true); break; case "OriginalBitmap": ValidatePropertyType(propertyName, value, typeof(Bitmap), true); break; case "Company": case "Description": case "DisplayName": case "TypeName": ValidatePropertyType(propertyName, value, typeof(string), true); if (value == null) value = string.Empty; break; case "Filter": ValidatePropertyType(propertyName, value, typeof(ICollection), true); int filterCount = 0; ICollection col = (ICollection)value; if (col != null) { foreach (object f in col) { if (f is ToolboxItemFilterAttribute) { filterCount++; } } } ToolboxItemFilterAttribute[] filter = new ToolboxItemFilterAttribute[filterCount]; if (col != null) { filterCount = 0; foreach (object f in col) { ToolboxItemFilterAttribute tfa = f as ToolboxItemFilterAttribute; if (tfa != null) { filter[filterCount++] = tfa; } } } value = filter; break; case "IsTransient": ValidatePropertyType(propertyName, value, typeof(bool), false); break; } return value; } /// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ISerializable.GetObjectData"]/*' /> /// <internalonly/> // SECREVIEW NOTE: we do not put the linkdemand that should be here, because the one on the type is a superset of this one [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { IntSecurity.UnmanagedCode.Demand(); Serialize(info, context); } /// <devdoc> /// This is a simple IDictionary that supports locking so /// changing values are not allowed after the toolbox /// item has been locked. /// </devdoc> private class LockableDictionary : Hashtable { private ToolboxItem _item; internal LockableDictionary(ToolboxItem item, int capacity) : base(capacity) { _item = item; } public override bool IsFixedSize { get { return _item.Locked; } } public override bool IsReadOnly { get { return _item.Locked; } } public override object this[object key] { get { string propertyName = GetPropertyName(key); object value = base[propertyName]; return _item.FilterPropertyValue(propertyName, value); } set { string propertyName = GetPropertyName(key); value = _item.ValidatePropertyValue(propertyName, value); CheckSerializable(value); _item.CheckUnlocked(); base[propertyName] = value; } } public override void Add(object key, object value) { string propertyName = GetPropertyName(key); value = _item.ValidatePropertyValue(propertyName, value); CheckSerializable(value); _item.CheckUnlocked(); base.Add(propertyName, value); } private void CheckSerializable(object value) { if (value != null && !value.GetType().IsSerializable) { throw new ArgumentException(SR.Format(SR.ToolboxItemValueNotSerializable, value.GetType().FullName)); } } public override void Clear() { _item.CheckUnlocked(); base.Clear(); } private string GetPropertyName(object key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } string propertyName = key as string; if (propertyName == null || propertyName.Length == 0) { throw new ArgumentException(SR.Format(SR.ToolboxItemInvalidKey), nameof(key)); } return propertyName; } public override void Remove(object key) { _item.CheckUnlocked(); base.Remove(key); } } } }
using System; using System.Collections.Generic; using System.IO; using Mono.Options; namespace CppSharp { class CLI { private static OptionSet optionSet = new OptionSet(); private static Options options = new Options(); static bool ParseCommandLineArgs(string[] args, List<string> messages, ref bool helpShown) { var showHelp = false; optionSet.Add("I=", "the {PATH} of a folder to search for include files", (i) => { AddIncludeDirs(i, messages); }); optionSet.Add("l=", "{LIBRARY} that that contains the symbols of the generated code", l => options.Libraries.Add(l) ); optionSet.Add("L=", "the {PATH} of a folder to search for additional libraries", l => options.LibraryDirs.Add(l) ); optionSet.Add("D:", "additional define with (optional) value to add to be used while parsing the given header files", (n, v) => AddDefine(n, v, messages) ); optionSet.Add("o=|output=", "the {PATH} for the generated bindings file (doesn't need the extension since it will depend on the generator)", v => HandleOutputArg(v, messages) ); optionSet.Add("on=|outputnamespace=", "the {NAMESPACE} that will be used for the generated code", on => options.OutputNamespace = on ); optionSet.Add("iln=|inputlibraryname=", "the {NAME} of the shared library that contains the symbols of the generated code", iln => options.InputLibraryName = iln ); optionSet.Add("g=|gen=|generator=", "the {TYPE} of generated code: 'chsarp' or 'cli' ('cli' supported only for Windows)", g => { GetGeneratorKind(g, messages); } ); optionSet.Add("p=|platform=", "the {PLATFORM} that the generated code will target: 'win', 'osx' or 'linux'", p => { GetDestinationPlatform(p, messages); } ); optionSet.Add("a=|arch=", "the {ARCHITECTURE} that the generated code will target: 'x86' or 'x64'", a => { GetDestinationArchitecture(a, messages); } ); optionSet.Add("c++11", "enables GCC C++ 11 compilation (valid only for Linux platform)", cpp11 => { options.Cpp11ABI = (cpp11 != null); } ); optionSet.Add("cs|checksymbols", "enable the symbol check for the generated code", cs => { options.CheckSymbols = (cs != null); } ); optionSet.Add("ub|unitybuild", "enable unity build", ub => { options.UnityBuild = (ub != null); } ); optionSet.Add("h|help", "shows the help", hl => { showHelp = (hl != null); }); List<string> additionalArguments = null; try { additionalArguments = optionSet.Parse(args); } catch (OptionException e) { Console.WriteLine(e.Message); return false; } if (showHelp || additionalArguments != null && additionalArguments.Count == 0) { helpShown = true; ShowHelp(); return false; } foreach(string s in additionalArguments) HandleAdditionalArgument(s, messages); return true; } static void ShowHelp() { string appName = Platform.IsWindows ? "CppSharp.CLI.exe" : "CppSharp.CLI"; Console.WriteLine(); Console.WriteLine("Usage: {0} [OPTIONS]+ [FILES]+", appName); Console.WriteLine("Generates target language bindings to interop with unmanaged code."); Console.WriteLine(); Console.WriteLine("Options:"); optionSet.WriteOptionDescriptions(Console.Out); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Useful informations:"); Console.WriteLine(" - to specify a file to generate bindings from you just have to add their path without any option flag, just like you"); Console.WriteLine(" would do with GCC compiler. You can specify a path to a single file (local or absolute) or a path to a folder with"); Console.WriteLine(" a search query."); Console.WriteLine(" e.g.: '{0} [OPTIONS]+ my_header.h' will generate the bindings for the file my_header.h", appName); Console.WriteLine(" e.g.: '{0} [OPTIONS]+ include/*.h' will generate the bindings for all the '.h' files inside the include folder", appName); Console.WriteLine(" - the options 'iln' (same as 'inputlibraryname') and 'l' have a similar meaning. Both of them are used to tell"); Console.WriteLine(" the generator which library has to be used to P/Invoke the functions from your native code."); Console.WriteLine(" The difference is that if you want to generate the bindings for more than one library within a single managed"); Console.WriteLine(" file you need to use the 'l' option to specify the names of all the libraries that contain the symbols to be loaded"); Console.WriteLine(" and you MUST set the 'cs' ('checksymbols') flag to let the generator automatically understand which library"); Console.WriteLine(" to use to P/Invoke. This can be also used if you plan to generate the bindings for only one library."); Console.WriteLine(" If you specify the 'iln' (or 'inputlibraryname') options, this option's value will be used for all the P/Invokes"); Console.WriteLine(" that the generator will create."); Console.WriteLine(" - If you specify the 'unitybuild' option then the generator will output a file for each given header file that will"); Console.WriteLine(" contain only the bindings for that header file."); } static void AddIncludeDirs(string dir, List<string> messages) { if (Directory.Exists(dir)) options.IncludeDirs.Add(dir); else messages.Add(string.Format("Directory {0} doesn't exist. Not adding as include directory.", dir)); } static void HandleOutputArg(string arg, List<string> messages) { try { string dir = Path.GetDirectoryName(arg); string file = Path.GetFileNameWithoutExtension(arg); options.OutputDir = dir; options.OutputFileName = file; } catch(Exception e) { messages.Add(e.Message); options.OutputDir = ""; options.OutputFileName = ""; } } static void AddDefine(string name, string value, List<string> messages) { if (name == null) messages.Add("Invalid definition name for option -D."); else options.Defines.Add(name, value); } static void HandleAdditionalArgument(string args, List<string> messages) { if (!Path.IsPathRooted(args)) args = Path.Combine(Directory.GetCurrentDirectory(), args); try { bool searchQuery = args.IndexOf('*') >= 0 || args.IndexOf('?') >= 0; bool isDirectory = searchQuery || (File.GetAttributes(args) & FileAttributes.Directory) == FileAttributes.Directory; if (isDirectory) GetFilesFromPath(args, messages); else if (File.Exists(args)) options.HeaderFiles.Add(args); else { messages.Add(string.Format("File {0} doesn't exist. Not adding to the list of files to generate bindings from.", args)); } } catch(Exception) { messages.Add(string.Format("Error while looking for files inside path {0}. Ignoring.", args)); } } static void GetFilesFromPath(string path, List<string> messages) { path = path.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); string searchPattern = string.Empty; int lastSeparatorPosition = path.LastIndexOf(Path.AltDirectorySeparatorChar); if (lastSeparatorPosition >= 0) { if (path.IndexOf('*', lastSeparatorPosition) >= lastSeparatorPosition || path.IndexOf('?', lastSeparatorPosition) >= lastSeparatorPosition) { searchPattern = path.Substring(lastSeparatorPosition + 1); path = path.Substring(0, lastSeparatorPosition); } } try { if (!string.IsNullOrEmpty(searchPattern)) { string[] files = Directory.GetFiles(path, searchPattern); foreach (string s in files) options.HeaderFiles.Add(s); } else { string[] files = Directory.GetFiles(path); foreach (string s in files) options.HeaderFiles.Add(s); } } catch (Exception) { messages.Add(string.Format("Error while looking for files inside path {0}. Ignoring.", path)); } } static void GetGeneratorKind(string generator, List<string> messages) { switch (generator.ToLower()) { case "csharp": options.Kind = CppSharp.Generators.GeneratorKind.CSharp; return; case "cli": options.Kind = CppSharp.Generators.GeneratorKind.CLI; return; } messages.Add(string.Format("Unknown generator kind: {0}. Defaulting to {1}", generator, options.Kind.ToString())); } static void GetDestinationPlatform(string platform, List<string> messages) { switch (platform.ToLower()) { case "win": options.Platform = TargetPlatform.Windows; return; case "osx": options.Platform = TargetPlatform.MacOS; return; case "linux": options.Platform = TargetPlatform.Linux; return; } messages.Add(string.Format("Unknown target platform: {0}. Defaulting to {1}", platform, options.Platform.ToString())); } static void GetDestinationArchitecture(string architecture, List<string> messages) { switch (architecture.ToLower()) { case "x86": options.Architecture = TargetArchitecture.x86; return; case "x64": options.Architecture = TargetArchitecture.x64; return; } messages.Add(string.Format("Unknown target architecture: {0}. Defaulting to {1}", architecture, options.Architecture.ToString())); } static void PrintMessages(List<string> messages) { foreach (string m in messages) Console.WriteLine(m); } static void Main(string[] args) { List<string> messages = new List<string>(); bool helpShown = false; try { if (!ParseCommandLineArgs(args, messages, ref helpShown)) { PrintMessages(messages); // Don't need to show the help since if ParseCommandLineArgs returns false the help has already been shown return; } Generator gen = new Generator(options); bool validOptions = gen.ValidateOptions(messages); PrintMessages(messages); if (validOptions) gen.Run(); else if (!helpShown) ShowHelp(); } catch (Exception ex) { PrintMessages(messages); Console.WriteLine(ex.Message); } } } }
using System.Collections.Generic; using System.Text.RegularExpressions; using Aspose.Cells.Translation.Internal; using Aspose.Cells.Translation.Internal.RequestHandlers; using Aspose.Cells.Translation.Models; using Aspose.Cells.Translation.Models.Requests; using Newtonsoft.Json; using FileInfo = Aspose.Cells.Translation.Internal.FileInfo; using TextInfo = System.Globalization.TextInfo; namespace Aspose.Cells.Translation.Api { public class TranslationApi { private readonly ApiInvoker _apiInvoker; private readonly TranslationConfiguration _configuration; public TranslationApi(string apiKey, string appSid) : this(new TranslationConfiguration {ClientSecret = apiKey, ClientId = appSid}) { } public TranslationApi(string jwtToken) : this(new TranslationConfiguration {JwtToken = jwtToken, ApiVersion = ApiVersion.V1, AuthType = AuthType.JWT}) { } public TranslationApi(TranslationConfiguration configuration) { _configuration = configuration; var requestHandlers = new List<IRequestHandler>(); if (_configuration.AuthType == AuthType.JWT) requestHandlers.Add(new JwtRequestHandler(_configuration)); requestHandlers.Add(new DebugLogRequestHandler(_configuration)); requestHandlers.Add(new ApiExceptionRequestHandler()); _apiInvoker = new ApiInvoker(requestHandlers); } public TranslateDocumentRequest CreateDocumentRequest( string name, string folder, string pair, string format, string outformat, string storage, string savefile, string savepath, bool masters, List<int> elements ) { var info = new Models.FileInfo { Folder = folder, Format = format, OutFormat = outformat, Name = name, Pair = pair, SaveFile = savefile, SavePath = savepath, Storage = storage, Masters = masters, Elements = elements }; var userRequest = $"'[{JsonConvert.SerializeObject(info)}]'"; var request = new TranslateDocumentRequest(userRequest); return request; } public TranslateTextRequest CreateTextRequest(string pair, string text) { var textInfo = new Models.TextInfo {Pair = pair, Text = text}; var userRequest = $"'[{JsonConvert.SerializeObject(textInfo, Formatting.None, new JsonSerializerSettings {StringEscapeHandling = StringEscapeHandling.EscapeHtml})}]'"; var request = new TranslateTextRequest(userRequest); return request; } public TranslationResponse RunTranslationTask(TranslateDocumentRequest request) { if (request.UserRequest == null) { throw new ApiException(400, "Empty request"); } var resourcePath = _configuration.GetApiRootUrl() + "/document"; resourcePath = Regex .Replace(resourcePath, "\\*", string.Empty) .Replace("&amp;", "&") .Replace("/?", "?"); try { var response = _apiInvoker.InvokeApi( resourcePath, "POST", request.UserRequest); if (response != null) { return (TranslationResponse) SerializationHelper.Deserialize(response, typeof(TranslationResponse)); } return null; } catch (ApiException ex) { if (ex.ErrorCode == 404) { return null; } throw; } } public TextResponse RunTranslationTextTask(TranslateTextRequest request) { if (request.UserRequest == null) { throw new ApiException(400, "Empty request"); } var resourcePath = _configuration.GetApiRootUrl() + "/text"; resourcePath = Regex .Replace(resourcePath, "\\*", string.Empty) .Replace("&amp;", "&") .Replace("/?", "?"); try { var response = _apiInvoker.InvokeApi( resourcePath, "POST", request.UserRequest); if (response != null) { return (TextResponse) SerializationHelper.Deserialize(response, typeof(TextResponse)); } return null; } catch (ApiException ex) { if (ex.ErrorCode == 404) { return null; } throw; } } public TranslationResponse RunHealthCheck() { var resourcePath = _configuration.GetApiRootUrl() + "/hc"; resourcePath = Regex .Replace(resourcePath, "\\*", string.Empty) .Replace("&amp;", "&") .Replace("/?", "?"); try { var response = _apiInvoker.InvokeApi( resourcePath, "GET"); if (response != null) { return (TranslationResponse) SerializationHelper.Deserialize(response, typeof(TranslationResponse)); } return null; } catch (ApiException ex) { if (ex.ErrorCode == 404) { return null; } throw; } } public Models.FileInfo GetDocumentRequestStructure() { var resourcePath = _configuration.GetApiRootUrl() + "/info/document"; resourcePath = Regex .Replace(resourcePath, "\\*", string.Empty) .Replace("&amp;", "&") .Replace("/?", "?"); try { var response = _apiInvoker.InvokeApi( resourcePath, "GET"); if (response != null) { return (Models.FileInfo) SerializationHelper.Deserialize(response, typeof(FileInfo)); } return null; } catch (ApiException ex) { if (ex.ErrorCode == 404) { return null; } throw; } } public TextInfo GetTextRequestStructure() { var resourcePath = _configuration.GetApiRootUrl() + "/info/text"; resourcePath = Regex .Replace(resourcePath, "\\*", string.Empty) .Replace("&amp;", "&") .Replace("/?", "?"); try { var response = _apiInvoker.InvokeApi( resourcePath, "GET"); if (response != null) { return (TextInfo) SerializationHelper.Deserialize(response, typeof(TextInfo)); } return null; } catch (ApiException ex) { if (ex.ErrorCode == 404) { return null; } throw; } } public Dictionary<string, string[]> GetLanguagePairs() { var resourcePath = _configuration.GetApiRootUrl() + "/info/pairs"; resourcePath = Regex .Replace(resourcePath, "\\*", string.Empty) .Replace("&amp;", "&") .Replace("/?", "?"); try { var response = _apiInvoker.InvokeApi( resourcePath, "GET"); if (response != null) { return (Dictionary<string, string[]>) SerializationHelper.Deserialize(response, typeof(Dictionary<string, string[]>)); } return null; } catch (ApiException ex) { if (ex.ErrorCode == 404) { return null; } throw; } } } }
using Loon.Core.Graphics.Opengl; using Loon.Core.Geom; using System; using Loon.Core; using Loon.Utils; namespace Loon.Action.Sprite.Node { public class LNSprite : LNNode { private BlendState blendState = BlendState.NonPremultiplied; private float rotation; protected internal LTexture _texture; private float[] pos, scale; protected internal LNAnimation _ans; protected internal bool _flipX = false, _flipY = false; protected internal System.Collections.Generic.Dictionary<string, LNAnimation> _anims; public LNSprite(RectBox rect):base(rect) { this._ans = null; base._anchor = new Vector2f(0f, 0f); } public LNSprite(int x, int y, int w, int h):base(x,y,w,h) { this._ans = null; base._anchor = new Vector2f(0f, 0f); } public LNSprite(string fsName) : base() { this._ans = null; LNFrameStruct struc0 = LNDataCache.GetFrameStruct(fsName); if (struc0 == null) { throw new Exception(""); } this._texture = struc0._texture; base._left = struc0._textCoords.X(); base._top = struc0._textCoords.Y(); base._orig_width = struc0._orig_width; base._orig_height = struc0._orig_height; base.SetNodeSize(struc0._size_width, struc0._size_height); base._anchor.Set(struc0._anchor); blendState = struc0._state; if (!struc0._place.Equals(0, 0)) { SetPosition(struc0._place); } } public LNSprite():this(LSystem.screenRect) { } public static LNSprite GInitWithTexture(LTexture tex2d) { LNSprite sprite = new LNSprite(); sprite.InitWithTexture(tex2d); return sprite; } public static LNSprite GInitWithFilename(string file) { LNSprite sprite = new LNSprite(); sprite.InitWithFilename(file); return sprite; } public static LNSprite GInitWithFrameStruct(LNFrameStruct fs) { LNSprite sprite = new LNSprite(); sprite.InitWithFrameStruct(fs); return sprite; } public static LNSprite GInitWithFrameStruct(string fsName) { return GInitWithFrameStruct(LNDataCache.GetFrameStruct(fsName)); } public static LNSprite GInitWithAnimation(LNAnimation ans) { LNSprite sprite = new LNSprite(); sprite.InitWithAnimation(ans, 0); return sprite; } public override void Draw(SpriteBatch batch) { if (base._visible && (this._texture != null)) { pos = base.ConvertToWorldPos(); if (_screenRect.Intersects(pos[0], pos[1], GetWidth(), GetHeight()) || _screenRect.Contains(pos[0], pos[1])) { if (_parent != null) { rotation = ConvertToWorldRot(); scale = ConvertToWorldScale(); } else { rotation = _rotation; scale[0] = _scale.x; scale[1] = _scale.y; } batch.SetColor(base._color.r, base._color.g, base._color.b, base._alpha); if (rotation == 0) { batch.Draw(_texture, pos[0], pos[1], base._size_width * scale[0], base._size_height * scale[1], base._left, base._top, base._orig_width, base._orig_height, _flipX, _flipY); } else { batch.Draw(_texture, pos[0], pos[1], _anchor.x, _anchor.y, base._size_width, base._size_height, scale[0], scale[1], MathUtils.ToDegrees(rotation), base._left, base._top, base._orig_width, base._orig_height, _flipX, _flipY); } batch.ResetColor(); BlendState oldState = batch.GetBlendState(); if (blendState != oldState) { batch.Flush(blendState); batch.SetBlendState(oldState); } } } } public void InitWithTexture(LTexture tex2d) { this._texture = tex2d; base._left = 0; base._top = 0; base.SetNodeSize(_texture.GetWidth(),_texture.GetHeight()); base._anchor.Set(base.GetWidth() / 2f, base.GetHeight() / 2f); } public void InitWithFilename(string filename) { this._texture = LTextures.LoadTexture(filename, Loon.Core.Graphics.Opengl.LTexture.Format.LINEAR); base._left = 0; base._top = 0; base.SetNodeSize(_texture.GetWidth(),_texture.GetHeight()); base._anchor.Set(base.GetWidth() / 2f, base.GetHeight() / 2f); } public void InitWithFrameStruct(LNFrameStruct fs) { this._texture = fs._texture; blendState = fs._state; base._left = fs._textCoords.X(); base._top = fs._textCoords.Y(); base._orig_width = fs._orig_width; base._orig_height = fs._orig_height; base.SetNodeSize(fs._size_width,fs._size_height); base._anchor.Set(fs._anchor); } public void InitWithAnimation(LNAnimation ans, int idx) { if (ans != null) { if (this._anims == null) { this._anims = new System.Collections.Generic.Dictionary<string, LNAnimation>(); } this._ans = ans; InitWithFrameStruct(this._ans.GetFrame(idx)); CollectionUtils.Put(_anims,ans.GetName(),ans); } } public void AddAnimation(LNAnimation anim) { InitWithAnimation(anim, 0); } public void SetFrame(string animName, int index) { if (this._anims == null) { this._anims = new System.Collections.Generic.Dictionary<string, LNAnimation>(); } if (this._anims.ContainsKey(animName)) { this._ans = (LNAnimation)CollectionUtils.Get(this._anims,animName); InitWithAnimation(this._ans, index); } } public void SetFrame(int idx) { if (_ans != null) { InitWithFrameStruct(_ans.GetFrame(idx)); } } public void SetFrameTime(float time) { if (_ans != null) { InitWithFrameStruct(_ans.GetFrameByTime(time)); } } public LTexture GetFrameTexture() { return this._texture; } public LNAnimation GetAnimation() { return this._ans; } public void SetAnimation(LNAnimation ans) { this._ans = ans; this.InitWithTexture(this._ans.GetFrame(0)._texture); } public bool IsFlipX() { return _flipX; } public void SetFlipX(bool flipX) { this._flipX = flipX; } public bool IsFlipY() { return _flipY; } public void SetFlipY(bool flipY) { this._flipY = flipY; } public BlendState GetBlendState() { return blendState; } public void SetBlendState(BlendState blendState) { this.blendState = blendState; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Text; using System.IO; using System.Xml; using System.Net; using System.Management.Automation; using System.ComponentModel; using System.Reflection; using System.Globalization; using System.Management.Automation.Runspaces; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Security; using System.Security.Principal; using System.Resources; using System.Threading; using System.Diagnostics.CodeAnalysis; using Microsoft.Powershell.Commands.GetCounter.PdhNative; using Microsoft.PowerShell.Commands.GetCounter; using Microsoft.PowerShell.Commands.Diagnostics.Common; namespace Microsoft.PowerShell.Commands { /// /// Class that implements the Get-Counter cmdlet. /// [Cmdlet(VerbsData.Export, "Counter", DefaultParameterSetName = "ExportCounterSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=138337")] public sealed class ExportCounterCommand : PSCmdlet { // // Path parameter // [Parameter( Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, HelpMessageBaseName = "GetEventResources")] [Alias("PSPath")] public string Path { get { return _path; } set { _path = value; } } private string _path; private string _resolvedPath; // // Format parameter. // Valid strings are "blg", "csv", "tsv" (case-insensitive). // [Parameter( Mandatory = false, ValueFromPipeline = false, ValueFromPipelineByPropertyName = false, HelpMessageBaseName = "GetEventResources")] [ValidateNotNull] [ValidateSet("blg", "csv", "tsv")] public string FileFormat { get { return _format; } set { _format = value; } } private string _format = "blg"; // // MaxSize parameter // Maximum output file size, in megabytes. // [Parameter( HelpMessageBaseName = "GetEventResources")] public UInt32 MaxSize { get { return _maxSize; } set { _maxSize = value; } } private UInt32 _maxSize = 0; // // InputObject parameter // [Parameter( Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessageBaseName = "GetEventResources")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", Target = "Microsoft.PowerShell.Commands.ExportCounterCommand.InputObject", Justification = "A PerformanceCounterSampleSet[] is required here because Powershell supports arrays natively.")] public PerformanceCounterSampleSet[] InputObject { get { return _counterSampleSets; } set { _counterSampleSets = value; } } private PerformanceCounterSampleSet[] _counterSampleSets = new PerformanceCounterSampleSet[0]; // // Force switch // [Parameter( HelpMessageBaseName = "GetEventResources")] public SwitchParameter Force { get { return _force; } set { _force = value; } } private SwitchParameter _force; // // Circular switch // [Parameter( HelpMessageBaseName = "GetEventResources")] public SwitchParameter Circular { get { return _circular; } set { _circular = value; } } private SwitchParameter _circular; private ResourceManager _resourceMgr = null; private PdhHelper _pdhHelper = null; private bool _stopping = false; private bool _queryInitialized = false; private PdhLogFileType _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY; // // BeginProcessing() is invoked once per pipeline // protected override void BeginProcessing() { #if CORECLR if (Platform.IsIoT) { // IoT does not have the '$env:windir\System32\pdh.dll' assembly which is required by this cmdlet. throw new PlatformNotSupportedException(); } // PowerShell Core requires at least Windows 7, // so no version test is needed _pdhHelper = new PdhHelper(false); #else // // Determine the OS version: this cmdlet requires Windows 7 // because it uses new Pdh functionality. // Version osVersion = System.Environment.OSVersion.Version; if (osVersion.Major < 6 || (osVersion.Major == 6 && osVersion.Minor < 1)) { string msg = _resourceMgr.GetString("ExportCtrWin7Required"); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "ExportCtrWin7Required", ErrorCategory.NotImplemented, null)); } _pdhHelper = new PdhHelper(osVersion.Major < 6); #endif _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager(); // // Set output format (log file type) // SetOutputFormat(); if (Circular.IsPresent && _maxSize == 0) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterCircularNoMaxSize")); Exception exc = new Exception(msg); WriteError(new ErrorRecord(exc, "CounterCircularNoMaxSize", ErrorCategory.InvalidResult, null)); } uint res = _pdhHelper.ConnectToDataSource(); if (res != 0) { ReportPdhError(res, true); } res = _pdhHelper.OpenQuery(); if (res != 0) { ReportPdhError(res, true); } } // // EndProcessing() is invoked once per pipeline // protected override void EndProcessing() { _pdhHelper.Dispose(); } /// /// Handle Control-C /// protected override void StopProcessing() { _stopping = true; _pdhHelper.Dispose(); } // // ProcessRecord() override. // This is the main entry point for the cmdlet. // When counter data comes from the pipeline, this gets invoked for each pipelined object. // When it's passed in as an argument, ProcessRecord() is called once for the entire _counterSampleSets array. // protected override void ProcessRecord() { Debug.Assert(_counterSampleSets.Length != 0 && _counterSampleSets[0] != null); ResolvePath(); uint res = 0; if (!_queryInitialized) { if (_format.ToLowerInvariant().Equals("blg")) { res = _pdhHelper.AddRelogCounters(_counterSampleSets[0]); } else { res = _pdhHelper.AddRelogCountersPreservingPaths(_counterSampleSets[0]); } if (res != 0) { ReportPdhError(res, true); } res = _pdhHelper.OpenLogForWriting(_resolvedPath, _outputFormat, Force.IsPresent, _maxSize * 1024 * 1024, Circular.IsPresent, null); if (res == PdhResults.PDH_FILE_ALREADY_EXISTS) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterFileExists"), _resolvedPath); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "CounterFileExists", ErrorCategory.InvalidResult, null)); } else if (res == PdhResults.PDH_LOG_FILE_CREATE_ERROR) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("FileCreateFailed"), _resolvedPath); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "FileCreateFailed", ErrorCategory.InvalidResult, null)); } else if (res == PdhResults.PDH_LOG_FILE_OPEN_ERROR) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("FileOpenFailed"), _resolvedPath); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "FileOpenFailed", ErrorCategory.InvalidResult, null)); } else if (res != 0) { ReportPdhError(res, true); } _queryInitialized = true; } foreach (PerformanceCounterSampleSet set in _counterSampleSets) { _pdhHelper.ResetRelogValues(); foreach (PerformanceCounterSample sample in set.CounterSamples) { bool bUnknownKey = false; res = _pdhHelper.SetCounterValue(sample, out bUnknownKey); if (bUnknownKey) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterExportSampleNotInInitialSet"), sample.Path, _resolvedPath); Exception exc = new Exception(msg); WriteError(new ErrorRecord(exc, "CounterExportSampleNotInInitialSet", ErrorCategory.InvalidResult, null)); } else if (res != 0) { ReportPdhError(res, true); } } res = _pdhHelper.WriteRelogSample(set.Timestamp); if (res != 0) { ReportPdhError(res, true); } if (_stopping) { break; } } } // Determines Log File Type based on FileFormat parameter // private void SetOutputFormat() { switch (_format.ToLowerInvariant()) { case "csv": _outputFormat = PdhLogFileType.PDH_LOG_TYPE_CSV; break; case "tsv": _outputFormat = PdhLogFileType.PDH_LOG_TYPE_TSV; break; default: // By default file format is blg _outputFormat = PdhLogFileType.PDH_LOG_TYPE_BINARY; break; } } private void ResolvePath() { try { Collection<PathInfo> result = null; result = SessionState.Path.GetResolvedPSPathFromPSPath(_path); if (result.Count > 1) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ExportDestPathAmbiguous"), _path); Exception exc = new Exception(msg); ThrowTerminatingError(new ErrorRecord(exc, "ExportDestPathAmbiguous", ErrorCategory.InvalidArgument, null)); } foreach (PathInfo currentPath in result) { _resolvedPath = currentPath.ProviderPath; } } catch (ItemNotFoundException pathNotFound) { // // This is an expected condition - we will be creating a new file // _resolvedPath = pathNotFound.ItemName; } } private void ReportPdhError(uint res, bool bTerminate) { string msg; uint formatRes = CommonUtilities.FormatMessageFromModule(res, "pdh.dll", out msg); if (formatRes != 0) { msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("CounterApiError"), res); } Exception exc = new Exception(msg); if (bTerminate) { ThrowTerminatingError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); } else { WriteError(new ErrorRecord(exc, "CounterApiError", ErrorCategory.InvalidResult, null)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Threading.Tasks; using Fiken.Net.HalClient.Http; using Fiken.Net.HalClient.Models; using Tavis.UriTemplates; namespace Fiken.Net.HalClient { /// <summary> /// A lightweight fluent .NET client for navigating and consuming HAL APIs. /// </summary> public class HalClient : IHalClient { private readonly IJsonHttpClient _client; private readonly IEnumerable<MediaTypeFormatter> _formatters; private IEnumerable<IResource> _current = Enumerable.Empty<IResource>(); private static readonly ICollection<MediaTypeFormatter> _defaultFormatters = new[] {new HalJsonMediaTypeFormatter()}; /// <summary> /// Creates an instance of the <see cref="HalClient"/> class. /// </summary> /// <param name="client">The <see cref="System.Net.Http.HttpClient"/> to use.</param> /// <param name="formatters"> /// Specifies the list of <see cref="MediaTypeFormatter"/>s to use. /// Default is <see cref="HalJsonMediaTypeFormatter"/>. /// </param> public HalClient( HttpClient client, ICollection<MediaTypeFormatter> formatters) { _client = new JsonHttpClient(client); _formatters = formatters == null || !formatters.Any() ? _defaultFormatters : formatters; } /// <summary> /// Creates an instance of the <see cref="HalClient"/> class. /// </summary> /// <param name="client">The <see cref="System.Net.Http.HttpClient"/> to use.</param> public HalClient( HttpClient client) : this(client, _defaultFormatters) { } /// <summary> /// Creates an instance of the <see cref="HalClient"/> class. /// Uses a default instance of <see cref="System.Net.Http.HttpClient"/>. /// </summary> public HalClient() : this(new HttpClient()) { } /// <summary> /// Creates an instance of the <see cref="HalClient"/> class. /// </summary> /// <param name="client">The implementation of <see cref="IJsonHttpClient"/> to use.</param> /// <param name="formatters"> /// Specifies the list of <see cref="MediaTypeFormatter"/>s to use. /// Default is <see cref="HalJsonMediaTypeFormatter"/>. /// </param> public HalClient( IJsonHttpClient client, ICollection<MediaTypeFormatter> formatters) { _client = client; _formatters = formatters == null || !formatters.Any() ? _defaultFormatters : formatters; } /// <summary> /// Creates an instance of the <see cref="HalClient"/> class. /// </summary> /// <param name="client">The implementation of <see cref="IJsonHttpClient"/> to use.</param> public HalClient( IJsonHttpClient client) : this(client, _defaultFormatters) { } /// <summary> /// Gets the instance of <see cref="System.Net.Http.HttpClient"/> used by the <see cref="HalClient"/>. /// </summary> public HttpClient HttpClient => _client.HttpClient; /// <summary> /// Returns the most recently navigated resource of the specified type. /// </summary> /// <typeparam name="T">The type of the resource to return.</typeparam> /// <returns>The most recent navigated resource of the specified type.</returns> /// <exception cref="NoActiveResource" /> public IResource<T> Item<T>() where T : class, new() => Convert<T>(Latest); /// <summary> /// Returns the list of embedded resources in the most recently navigated resource. /// </summary> /// <typeparam name="T">The type of the resource to return.</typeparam> /// <returns>The list of embedded resources in the most recently navigated resource.</returns> /// <exception cref="NoActiveResource" /> public IEnumerable<IResource<T>> Items<T>() where T : class, new() => _current.Select(Convert<T>); /// <summary> /// Makes a HTTP GET request to the default URI and stores the returned resource. /// </summary> /// <returns>The updated <see cref="IHalClient"/>.</returns> public IHalClient Root() => Execute(string.Empty, uri => _client.GetAsync(uri)); /// <summary> /// Makes a HTTP GET request to the given URL and stores the returned resource. /// </summary> /// <param name="href">The URI to request.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> public IHalClient Root(string href) => Execute(href, uri => _client.GetAsync(uri)); /// <summary> /// Navigates the given link relation and stores the the returned resource(s). /// </summary> /// <param name="rel">The link relation to follow.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> public IHalClient Get(string rel) => Get(rel, null, null); /// <summary> /// Navigates the given link relation and stores the the returned resource(s). /// </summary> /// <param name="rel">The link relation to follow.</param> /// <param name="curie">The curie of the link relation.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> public IHalClient Get(string rel, string curie) => Get(rel, null, curie); /// <summary> /// Navigates the given templated link relation and stores the the returned resource(s). /// </summary> /// <param name="rel">The templated link relation to follow.</param> /// <param name="parameters">An anonymous object containing the template parameters to apply.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> /// <exception cref="TemplateParametersAreRequired" /> public IHalClient Get(string rel, object parameters) => Get(rel, parameters, null); /// <summary> /// Navigates the given templated link relation and stores the the returned resource(s). /// </summary> /// <param name="rel">The templated link relation to follow.</param> /// <param name="parameters">An anonymous object containing the template parameters to apply.</param> /// <param name="curie">The curie of the link relation.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> /// <exception cref="TemplateParametersAreRequired" /> public IHalClient Get(string rel, object parameters, string curie) { var relationship = Relationship(rel, curie); var embedded = _current.FirstOrDefault(r => r.Embedded.Any(e => e.Rel == relationship)); if (embedded != null) { _current = embedded.Embedded.Where(e => e.Rel == relationship); return this; } return BuildAndExecute(relationship, parameters, uri => _client.GetAsync(uri)); } /// <summary> /// Makes a HTTP POST request to the given link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The link relation to follow.</param> /// <param name="value">The payload to POST.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> public IHalClient Post(string rel, object value) => Post(rel, value, null, null); /// <summary> /// Makes a HTTP POST request to the given link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The link relation to follow.</param> /// <param name="value">The payload to POST.</param> /// <param name="curie">The curie of the link relation.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> public IHalClient Post(string rel, object value, string curie) => Post(rel, value, null, curie); /// <summary> /// Makes a HTTP POST request to the given templated link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The templated link relation to follow.</param> /// <param name="value">The payload to POST.</param> /// <param name="parameters">An anonymous object containing the template parameters to apply.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> /// <exception cref="TemplateParametersAreRequired" /> public IHalClient Post(string rel, object value, object parameters) => Post(rel, value, parameters, null); /// <summary> /// Makes a HTTP POST request to the given templated link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The templated link relation to follow.</param> /// <param name="value">The payload to POST.</param> /// <param name="parameters">An anonymous object containing the template parameters to apply.</param> /// <param name="curie">The curie of the link relation.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> /// <exception cref="TemplateParametersAreRequired" /> public IHalClient Post(string rel, object value, object parameters, string curie) { var relationship = Relationship(rel, curie); return BuildAndExecute(relationship, parameters, uri => _client.PostAsync(uri, value)); } /// <summary> /// Makes a HTTP PUT request to the given templated link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The templated link relation to follow.</param> /// <param name="value">The payload to PUT.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> public IHalClient Put(string rel, object value) => Put(rel, value, null, null); /// <summary> /// Makes a HTTP PUT request to the given link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The link relation to follow.</param> /// <param name="value">The payload to PUT.</param> /// <param name="curie">The curie of the link relation.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> public IHalClient Put(string rel, object value, string curie) => Put(rel, value, null, curie); /// <summary> /// Makes a HTTP PUT request to the given templated link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The templated link relation to follow.</param> /// <param name="value">The payload to PUT.</param> /// <param name="parameters">An anonymous object containing the template parameters to apply.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> /// <exception cref="TemplateParametersAreRequired" /> public IHalClient Put(string rel, object value, object parameters) => Put(rel, value, parameters, null); /// <summary> /// Makes a HTTP PUT request to the given templated link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The templated link relation to follow.</param> /// <param name="value">The payload to PUT.</param> /// <param name="parameters">An anonymous object containing the template parameters to apply.</param> /// <param name="curie">The curie of the link relation.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> /// <exception cref="TemplateParametersAreRequired" /> public IHalClient Put(string rel, object value, object parameters, string curie) { var relationship = Relationship(rel, curie); return BuildAndExecute(relationship, parameters, uri => _client.PutAsync(uri, value)); } /// <summary> /// Makes a HTTP DELETE request to the given link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The link relation to follow.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> public IHalClient Delete(string rel) => Delete(rel, null, null); /// <summary> /// Makes a HTTP DELETE request to the given link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The link relation to follow.</param> /// <param name="curie">The curie of the link relation.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> public IHalClient Delete(string rel, string curie) => Delete(rel, null, curie); /// <summary> /// Makes a HTTP DELETE request to the given templated link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The templated link relation to follow.</param> /// <param name="parameters">An anonymous object containing the template parameters to apply.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> /// <exception cref="TemplateParametersAreRequired" /> public IHalClient Delete(string rel, object parameters) => Delete(rel, parameters, null); /// <summary> /// Makes a HTTP DELETE request to the given templated link relation on the most recently navigated resource. /// </summary> /// <param name="rel">The templated link relation to follow.</param> /// <param name="parameters">An anonymous object containing the template parameters to apply.</param> /// <param name="curie">The curie of the link relation.</param> /// <returns>The updated <see cref="IHalClient"/>.</returns> /// <exception cref="FailedToResolveRelationship" /> /// <exception cref="TemplateParametersAreRequired" /> public IHalClient Delete(string rel, object parameters, string curie) { var relationship = Relationship(rel, curie); return BuildAndExecute(relationship, parameters, uri => _client.DeleteAsync(uri)); } /// <summary> /// Determines whether the most recently navigated resource contains the given link relation. /// </summary> /// <param name="rel">The link relation to look for.</param> /// <returns>Whether or not the link relation exists.</returns> public bool Has(string rel) => Has(rel, null); /// <summary> /// Determines whether the most recently navigated resource contains the given link relation. /// </summary> /// <param name="rel">The link relation to look for.</param> /// <param name="curie">The curie of the link relation.</param> /// <returns>Whether or not the link relation exists.</returns> public bool Has(string rel, string curie) { var relationship = Relationship(rel, curie); return _current.Any(r => r.Embedded.Any(e => e.Rel == relationship)) || _current.Any(r => r.Links.Any(l => l.Rel == relationship)); } private IHalClient BuildAndExecute(string relationship, object parameters, Func<string, Task<HttpResponseMessage>> command) { var resource = _current.FirstOrDefault(r => r.Links.Any(l => l.Rel == relationship)); if (resource == null) throw new FailedToResolveRelationship(relationship); var link = resource.Links.FirstOrDefault(l => l.Rel == relationship); return Execute(Construct(link, parameters), command); } private IHalClient Execute(string uri, Func<string, Task<HttpResponseMessage>> command) { var result = command(uri).Result; var headers = result.Headers; if (headers.Contains("Location")) { result = _client.GetAsync(headers.Location.AbsolutePath).Result; } AssertSuccessfulStatusCode(result); _current = new[] { result.Content == null ? new Resource() : result.Content.ReadAsAsync<Resource>(_formatters).Result }; return this; } private static string Construct(ILink link, object parameters) { if (!link.Templated) return link.Href; if (parameters == null) throw new TemplateParametersAreRequired(link); var template = new UriTemplate(link.Href, caseInsensitiveParameterNames: true); template.AddParameters(parameters); return template.Resolve(); } private static IResource<T> Convert<T>(IResource resource) where T : class, new() => new Resource<T> { Rel = resource.Rel, Href = resource.Href, Name = resource.Name, Data = resource.Data<T>(), Links = resource.Links, Embedded = resource.Embedded }; private static void AssertSuccessfulStatusCode(HttpResponseMessage result) { if (!result.IsSuccessStatusCode) throw new HttpRequestException($"HTTP request returned non-successful HTTP status code:{result.StatusCode}"); } private IResource Latest { get { if (_current == null || !_current.Any()) throw new NoActiveResource(); return _current.Last(); } } private static string Relationship(string rel, string curie) => curie == null ? rel : $"{curie}:{rel}"; } }
/* ** SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) ** Copyright (C) 2011 Silicon Graphics, Inc. ** All Rights Reserved. ** ** 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 including the dates of first publication and either this ** permission notice or a reference to http://oss.sgi.com/projects/FreeB/ 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 SILICON GRAPHICS, INC. ** 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. ** ** Except as contained in this notice, the name of Silicon Graphics, Inc. shall not ** be used in advertising or otherwise to promote the sale, use or other dealings in ** this Software without prior written authorization from Silicon Graphics, Inc. */ /* ** Original Author: Eric Veach, July 1994. ** libtess2: Mikko Mononen, http://code.google.com/p/libtess2/. ** LibTessDotNet: Remi Gillig, https://github.com/speps/LibTessDotNet */ using System; using System.Diagnostics; namespace UnityEngine.Experimental.Rendering.LWRP { #if DOUBLE namespace LibTessDotNet.Double #else namespace LibTessDotNet #endif { internal struct PQHandle { public static readonly int Invalid = 0x0fffffff; internal int _handle; } internal class PriorityHeap<TValue> where TValue : class { public delegate bool LessOrEqual(TValue lhs, TValue rhs); protected class HandleElem { internal TValue _key; internal int _node; } private LessOrEqual _leq; private int[] _nodes; private HandleElem[] _handles; private int _size, _max; private int _freeList; private bool _initialized; public bool Empty { get { return _size == 0; } } public PriorityHeap(int initialSize, LessOrEqual leq) { _leq = leq; _nodes = new int[initialSize + 1]; _handles = new HandleElem[initialSize + 1]; _size = 0; _max = initialSize; _freeList = 0; _initialized = false; _nodes[1] = 1; _handles[1] = new HandleElem { _key = null }; } private void FloatDown(int curr) { int child; int hCurr, hChild; hCurr = _nodes[curr]; while (true) { child = curr << 1; if (child < _size && _leq(_handles[_nodes[child + 1]]._key, _handles[_nodes[child]]._key)) { ++child; } Debug.Assert(child <= _max); hChild = _nodes[child]; if (child > _size || _leq(_handles[hCurr]._key, _handles[hChild]._key)) { _nodes[curr] = hCurr; _handles[hCurr]._node = curr; break; } _nodes[curr] = hChild; _handles[hChild]._node = curr; curr = child; } } private void FloatUp(int curr) { int parent; int hCurr, hParent; hCurr = _nodes[curr]; while (true) { parent = curr >> 1; hParent = _nodes[parent]; if (parent == 0 || _leq(_handles[hParent]._key, _handles[hCurr]._key)) { _nodes[curr] = hCurr; _handles[hCurr]._node = curr; break; } _nodes[curr] = hParent; _handles[hParent]._node = curr; curr = parent; } } public void Init() { for (int i = _size; i >= 1; --i) { FloatDown(i); } _initialized = true; } public PQHandle Insert(TValue value) { int curr = ++_size; if ((curr * 2) > _max) { _max <<= 1; Array.Resize(ref _nodes, _max + 1); Array.Resize(ref _handles, _max + 1); } int free; if (_freeList == 0) { free = curr; } else { free = _freeList; _freeList = _handles[free]._node; } _nodes[curr] = free; if (_handles[free] == null) { _handles[free] = new HandleElem { _key = value, _node = curr }; } else { _handles[free]._node = curr; _handles[free]._key = value; } if (_initialized) { FloatUp(curr); } Debug.Assert(free != PQHandle.Invalid); return new PQHandle { _handle = free }; } public TValue ExtractMin() { Debug.Assert(_initialized); int hMin = _nodes[1]; TValue min = _handles[hMin]._key; if (_size > 0) { _nodes[1] = _nodes[_size]; _handles[_nodes[1]]._node = 1; _handles[hMin]._key = null; _handles[hMin]._node = _freeList; _freeList = hMin; if (--_size > 0) { FloatDown(1); } } return min; } public TValue Minimum() { Debug.Assert(_initialized); return _handles[_nodes[1]]._key; } public void Remove(PQHandle handle) { Debug.Assert(_initialized); int hCurr = handle._handle; Debug.Assert(hCurr >= 1 && hCurr <= _max && _handles[hCurr]._key != null); int curr = _handles[hCurr]._node; _nodes[curr] = _nodes[_size]; _handles[_nodes[curr]]._node = curr; if (curr <= --_size) { if (curr <= 1 || _leq(_handles[_nodes[curr >> 1]]._key, _handles[_nodes[curr]]._key)) { FloatDown(curr); } else { FloatUp(curr); } } _handles[hCurr]._key = null; _handles[hCurr]._node = _freeList; _freeList = hCurr; } } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace BooksOnline.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.0-rc2-20901"); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("WebApplication.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("WebApplication.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace _3D_Radical_Racer { public class RadicalRacerMissionControl : Microsoft.Xna.Framework.Game { public enum GameState { mainMenu, raceStartCountDown, running, raceFinished, paused, gameOver } public GameState gameState; public GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteFont basicFont, HUDfont, raceResultsFont, countDownFont; Texture2D startScreenImage, winImage, podiumImage; //private int luckyBoxTimer = 0; private int slickTimer = 0; private int colorAreaToCheck_Width = 2; private int colorAreaToCheck_Height = 2; private RenderTarget2D trackRender; // allows to make use of your own back buffer (double buffering is used normally allow fluid game motion) good explaination -> http://geekswithblogs.net/mikebmcl/archive/2011/02/18/xna-rendertarget2d-sample.aspx private Color cp2blue = new Color (0, 0, 255, 255); private Color cp3green = new Color(0, 255, 0, 255); private Color cp1yellow = new Color(255, 255, 0, 255); private int myX , myZ; // used for finding checkpoints before race starts private Rectangle rect1; private bool CheckPointsTestedForAndFound = false; private float mappedModelX, mappedModelZ; private float mapXNASize = 402.312988281250000f; private bool canAssignPoints; private bool canFillRemainingPositions; // for use if player car finished before others private bool startCountDown = true; private int countDown = 3; private int countDownTickTimer; private String driverStandingAsAsString = ""; private bool sortAndExtractDriversChampionshipStandings = true; // sort only needs to happen once private Video splashVideo; private VideoPlayer myPlayer; private Texture2D videoSplashTexture; private bool playAgain = true; public RadicalRacerMissionControl() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // http://msdn.microsoft.com/en-us/library/bb195024.aspx //this.graphics.PreferredBackBufferWidth = 480; //this.graphics.PreferredBackBufferHeight = 800; //this.graphics.IsFullScreen = true; //Console.WriteLine(GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height); //Console.WriteLine(GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width); //Console.WriteLine(Window.ClientBounds.Height); //Console.WriteLine(Window.ClientBounds.Width); gameState = GameState.mainMenu; rect1 = new Rectangle(0, 0, colorAreaToCheck_Width, colorAreaToCheck_Height); } /// <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() { // TODO: Add your initialization logic here // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); GlobalGameData.currentTrackModel = new Track(this, graphics, spriteBatch); GlobalGameData.currentTestTexture = Content.Load<Texture2D>("Textures\\track1trackonly"); GlobalGameData.cpuCarList = new List<CPUCar>(); //GlobalGameData.carList = new List<Car>(); // for sorting track positions GlobalGameData.playerCar = new PlayerCar("Player One" ,this, graphics, spriteBatch); // Car 1 GlobalGameData.playerCar.position = new Vector3(-213, 0, 0); //GameData.carList.Add(GameData.playerCar); GlobalGameData.playerCarSteerLeft = new PlayerCarSteerLeft(this, graphics, spriteBatch); GlobalGameData.playerCarSteerLeft.position = new Vector3(-213, 0, 0); GlobalGameData.playerCarSteerRight = new PlayerCarSteerRight(this, graphics, spriteBatch); GlobalGameData.playerCarSteerRight.position = new Vector3(-213, 0, 0); GlobalGameData.cpuCar = new CPUCar("Car 2", this, graphics, spriteBatch, new Vector3(-213, 0, 30)); GlobalGameData.cpuCarList.Add(GlobalGameData.cpuCar); GlobalGameData.cpuCar = new CPUCar("Car 3", this, graphics, spriteBatch, new Vector3(-246, 0, 45)); GlobalGameData.cpuCarList.Add(GlobalGameData.cpuCar); GlobalGameData.cpuCar = new CPUCar("Car 4", this, graphics, spriteBatch, new Vector3(-246, 0, 19)); GlobalGameData.cpuCarList.Add(GlobalGameData.cpuCar); Hoarding hoarding = new Hoarding(this, graphics, spriteBatch); Horizon horizon = new Horizon(this, graphics, spriteBatch); StartFinishSignage startFinishSignage = new StartFinishSignage(this, graphics, spriteBatch); Shed shed = new Shed(this, graphics, spriteBatch); GlobalGameData.luckybox = new LuckyBox(this, graphics, spriteBatch); GlobalGameData.slick = new Obstacle(this, graphics, spriteBatch); GlobalGameData.checkPoint1 = new BoundingSphere(Vector3.Zero, 40f); GlobalGameData.checkPoint2 = new BoundingSphere(Vector3.Zero, 40f); GlobalGameData.checkPoint3 = new BoundingSphere(Vector3.Zero, 40f); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // TODO: use this.Content to load your game content here basicFont = Content.Load<SpriteFont>("LapsCompletes"); HUDfont = Content.Load<SpriteFont>("HUDfont"); raceResultsFont = Content.Load<SpriteFont>("ResultsFont"); countDownFont = Content.Load<SpriteFont>("CountDownFont"); startScreenImage = Content.Load<Texture2D>("Textures\\racingStartScreen"); winImage = Content.Load<Texture2D>("Textures\\winner"); podiumImage = Content.Load<Texture2D>("Textures\\podium"); trackRender = new RenderTarget2D(graphics.GraphicsDevice, colorAreaToCheck_Width, colorAreaToCheck_Height, false, SurfaceFormat.Color, DepthFormat.Depth24); splashVideo = Content.Load<Video>("Textures\\introSplash"); //introVideo = Content.Load<Video>("Textures\\introVideo"); myPlayer = new VideoPlayer(); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { //if (gameTime.IsRunningSlowly) Console.WriteLine("slow"); // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape)) this.Exit(); // TODO: Add your update logic here if (gameState == GameState.running) { UpdateGameRunning(); base.Update(gameTime); } else if (gameState == GameState.mainMenu) { UpdateGameMainMenu(); } else if (gameState == GameState.raceFinished) { UpdateGameRaceFinished(); } else if (gameState == GameState.gameOver) { // Nothing to do here but leave in place anyway } } private void UpdateGameRaceFinished() { FillRemainingPositions(); AssignPoints(); if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) { if (GlobalGameData.nextTrack == 4) { gameState = GameState.gameOver; //GameData.playerCar.numberOfLapsCompletedOnCurrentTrack = 0; } else { GoToNextTrack(); } } } private void UpdateGameMainMenu() { if (CheckPointsTestedForAndFound == false) { FindCheckPoints(); CheckPointsTestedForAndFound = true; } if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Enter)) { gameState = GameState.running; AllowCarsToMove(true); } // myPlayer.Play(introVideo); if (myPlayer.State == MediaState.Stopped && playAgain == true) { myPlayer.IsLooped = false; myPlayer.Play(splashVideo); playAgain = false; } } private void UpdateGameRunning() { GlobalGameData.luckybox.generatePosition(); GlobalGameData.slick.generatePosition(); ManageOilSlickObstaclePositioning(); StartCountdown(); CheckForRaceOver(); canFillRemainingPositions = true; canAssignPoints = true; //myPlayer.Stop(); //stop the video } private void GoToNextTrack() { CheckPointsTestedForAndFound = false; LoadNextTrack(); if (CheckPointsTestedForAndFound == false) { FindCheckPoints(); CheckPointsTestedForAndFound = true; } ResetAllCars(); AllowCarsToMove(true); //GameData.lb.generatePosition(); GlobalGameData.racePosition.Clear(); gameState = GameState.running; } private void ManageOilSlickObstaclePositioning() { // Every 600 cycles the Oil slick is positioned to // a different position on the track. if (slickTimer > 600) { slickTimer = 0; GlobalGameData.slick.xPos = 0; GlobalGameData.slick.zPos = 0; GlobalGameData.slick.generatePosition(); } slickTimer++; } private void StartCountdown() { //Start the race countdown if (startCountDown == true) { AllowCarsToMove(false); countDownTickTimer++; if (countDownTickTimer > 60) { countDown--; countDownTickTimer = 0; } if (countDown < 0) { startCountDown = false; countDown = 3; countDownTickTimer = 0; AllowCarsToMove(true); } } } private void AllowCarsToMove( Boolean yesNo ) { // This method is used to set the cars to be able to move or not GlobalGameData.playerCar.allowedToMove = yesNo; GlobalGameData.cpuCarList[0].allowedToMove = yesNo; GlobalGameData.cpuCarList[1].allowedToMove = yesNo; GlobalGameData.cpuCarList[2].allowedToMove = yesNo; } private void CheckForRaceOver() { // checks if any of the cars have completed the required number of laps and if so // determines their actions and updates the game state if (GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.playerCar.numberOfLapsCompletedOnCurrentTrack || GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.cpuCarList[0].numberOfLapsCompletedOnCurrentTrack || GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.cpuCarList[1].numberOfLapsCompletedOnCurrentTrack || GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.cpuCarList[2].numberOfLapsCompletedOnCurrentTrack) { if (GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.playerCar.numberOfLapsCompletedOnCurrentTrack) { GlobalGameData.playerCar.velocity = Vector3.Zero; GlobalGameData.playerCar.allowedToMove = false; } if (GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.cpuCarList[0].numberOfLapsCompletedOnCurrentTrack) { GlobalGameData.cpuCarList[0].velocity = Vector3.Zero; GlobalGameData.cpuCarList[0].allowedToMove = false; } if (GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.cpuCarList[1].numberOfLapsCompletedOnCurrentTrack) { GlobalGameData.cpuCarList[1].velocity = Vector3.Zero; GlobalGameData.cpuCarList[1].allowedToMove = false; } if (GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.cpuCarList[2].numberOfLapsCompletedOnCurrentTrack) { GlobalGameData.cpuCarList[2].velocity = Vector3.Zero; GlobalGameData.cpuCarList[2].allowedToMove = false; } } // wait for P1 (you) to finish before moving on. if ((GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.playerCar.numberOfLapsCompletedOnCurrentTrack && GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.cpuCarList[0].numberOfLapsCompletedOnCurrentTrack && GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.cpuCarList[1].numberOfLapsCompletedOnCurrentTrack && GlobalGameData.currentTrackModel.numberOfLaps == GlobalGameData.cpuCarList[2].numberOfLapsCompletedOnCurrentTrack) || (GlobalGameData.playerCar.numberOfLapsCompletedOnCurrentTrack == GlobalGameData.currentTrackModel.numberOfLaps) ) { gameState = GameState.raceFinished; GlobalGameData.nextTrack++; } } //checkForRaceOver private void FillRemainingPositions() { // This method is a cheat really, rather than wait for each other car to // finish, if player finishes before all other cars have finished then // populate the list with other cars that have not finished yet randomly. if (GlobalGameData.racePosition.Count != 4 && canFillRemainingPositions == true) { //Its going to contain player car for sure //so populate the rest with random cpu cars //taking car to avoid duplicates int positionsToBeFilled = 4 - GlobalGameData.racePosition.Count; for (int i = GlobalGameData.racePosition.Count; i < 4; i++) { Random random = new Random(); Car temp = GlobalGameData.cpuCarList[random.Next(0, 3)]; while (GlobalGameData.racePosition.Contains(temp)) { temp = GlobalGameData.cpuCarList[random.Next(0, 3)]; } GlobalGameData.racePosition.Add(temp); } } canFillRemainingPositions = false; } //fillRemainingPositions private void LoadNextTrack() { if (GlobalGameData.nextTrack == 2) { GlobalGameData.currentTestTexture = Content.Load<Texture2D>("Textures\\track2trackonly"); GlobalGameData.playerCar.numberOfLapsCompletedOnCurrentTrack = 0; GlobalGameData.currentTrackModel.RemoveTrack(); Track track = new Track(this, graphics, spriteBatch); GlobalGameData.currentTrackModel = track; } else if (GlobalGameData.nextTrack == 3) { GlobalGameData.playerCar.numberOfLapsCompletedOnCurrentTrack = 0; GlobalGameData.currentTrackModel.RemoveTrack(); GlobalGameData.currentTestTexture = Content.Load<Texture2D>("Textures\\track3trackonly"); GlobalGameData.currentTrackModel = new Track(this, graphics, spriteBatch); } } // Load Next Track protected void ResetAllCars() { // reset car positions here GlobalGameData.playerCar.position = new Vector3(-213, 0, 0); GlobalGameData.playerCar.forward = new Vector3(0, 0, 1); GlobalGameData.playerCar.right = Vector3.Right; GlobalGameData.playerCar.velocity = Vector3.Zero; GlobalGameData.playerCar.currentSpeed = 0.0f; GlobalGameData.playerCarSteerLeft.position = new Vector3(-213, 0, 0); GlobalGameData.playerCarSteerLeft.right = Vector3.Right; GlobalGameData.playerCarSteerLeft.forward = new Vector3(0, 0, 1); GlobalGameData.playerCarSteerRight.position = new Vector3(-213, 0, 0); GlobalGameData.playerCarSteerRight.right = Vector3.Right; GlobalGameData.playerCarSteerRight.forward = new Vector3(0, 0, 1); GlobalGameData.cpuCarList[0].position = new Vector3(-213, 0, 30); GlobalGameData.cpuCarList[0].forward = new Vector3(0, 0, 1); GlobalGameData.cpuCarList[0].velocity = Vector3.Zero; GlobalGameData.cpuCarList[0].currentSpeed = 0.0f; GlobalGameData.cpuCarList[0].right = Vector3.Right; GlobalGameData.cpuCarList[1].position = new Vector3(-246, 0, 45); GlobalGameData.cpuCarList[1].forward = new Vector3(0, 0, 1); GlobalGameData.cpuCarList[1].velocity = Vector3.Zero; GlobalGameData.cpuCarList[1].currentSpeed = 0.0f; GlobalGameData.cpuCarList[1].right = Vector3.Right; GlobalGameData.cpuCarList[2].position = new Vector3(-246, 0, 19); GlobalGameData.cpuCarList[2].forward = new Vector3(0, 0, 1); GlobalGameData.cpuCarList[2].velocity = Vector3.Zero; GlobalGameData.cpuCarList[2].currentSpeed = 0.0f; GlobalGameData.cpuCarList[2].right = Vector3.Right; foreach (CPUCar c in GlobalGameData.cpuCarList) { c.checkPoint1Yellow = false; c.checkPoint2Blue = false; c.checkPoint3Green = false; c.checkPointCounter = 0; c.numberOfLapsCompletedOnCurrentTrack = 0; c.whiteHit = 0; c.whiteCounter = 0; } GlobalGameData.playerCar.checkPoint1Yellow = false; GlobalGameData.playerCar.checkPoint2Blue = false; GlobalGameData.playerCar.checkPoint3Green = false; GlobalGameData.playerCar.checkPointCounter = 0; GlobalGameData.playerCar.numberOfLapsCompletedOnCurrentTrack = 0; GlobalGameData.playerCar.whiteHit = 0; GlobalGameData.playerCar.whiteCounter = 0; startCountDown = true; } // reset all cars private void FindCheckPoints() { // runs before the start of each race. // start at 0 0 (top left) and sweep to end (bottom right) of texture // and find check point locations and place a bounding sphere there, // to improve performance, track texture is divided up into hops // of 128 which reduces the call to the color checking method. int i = 0; while ((myX + 128) <= 1024 && (myZ + 128) <= 1024) { Console.WriteLine("X = " + myX + " Y = " + myZ); if (CheckPointFound(myX, myZ) == true) { Console.WriteLine("Found @ " + myX + ", " + myZ); mappedModelX = ((float)myX / 1.28f); mappedModelX = (mappedModelX * -1f) + mapXNASize; mappedModelZ = ((float)myZ / 1.28f); if (mappedModelZ >= 0 && mappedModelZ <= mapXNASize) mappedModelZ = mapXNASize - mappedModelZ; else mappedModelZ = (mappedModelZ * -1f) + mapXNASize; Console.WriteLine("Mapped X " + mappedModelX + "\nMapped Z " + mappedModelZ); switch (i) { case 0: GlobalGameData.checkPoint1.Center = new Vector3(mappedModelX, 0, mappedModelZ); break; case 1: GlobalGameData.checkPoint2.Center = new Vector3(mappedModelX, 0, mappedModelZ); break; case 2: GlobalGameData.checkPoint3.Center = new Vector3(mappedModelX, 0, mappedModelZ); break; } i++; myX = myX + 128; } else { myX = myX + 128; } if ((myX + 128) == 1024 && (myZ + 128) != 1024) { myZ = myZ + 128; myX = 0; } } // while i = 0; myX = 0; myZ = 0; } //-------------------Modified Method from "The Road not taken"------------------- //http://www.xnadevelopment.com/tutorials/theroadnottaken/theroadnottaken.shtml internal bool CheckPointFound(int x, int z) { /* This method samples a patch of the texture determines if it contains a * user defined color */ //Create a texture of the area i am testing by passing my new co-ords and applying scale //so that it corresponds correctly to the texture I am testing. Texture2D aCollisionCheck = CreateCollisonTexture(x, z); //Use GetData to fill in an array with all of the colors of the Pixels in the area of the collison Texture int numberOfPixelsToStore = colorAreaToCheck_Width * colorAreaToCheck_Height; Color[] myColors = new Color[numberOfPixelsToStore]; aCollisionCheck.GetData<Color>(0, rect1, myColors, 0, numberOfPixelsToStore); // Interate thru array and test for off track colors, in my case alpha. bool aCollisonOccurred = false; foreach (Color pixel in myColors) { if (pixel == cp1yellow || pixel == cp2blue || pixel == cp3green) { aCollisonOccurred = true; break; } } return aCollisonOccurred; } //-------------------Modified Method from "The Road not taken"------------------- //http://www.xnadevelopment.com/tutorials/theroadnottaken/theroadnottaken.shtml private Texture2D CreateCollisonTexture(float x, float z) { /*This method complements the previous method in that it is here that * the texture sample is created. */ //Grab a square of the Track image that is around the car graphics.GraphicsDevice.SetRenderTarget(trackRender); graphics.GraphicsDevice.Clear(ClearOptions.Target, Color.Red, 0, 0); spriteBatch.Begin(); spriteBatch.Draw( GlobalGameData.currentTestTexture, //A texture. new Rectangle(0, 0, colorAreaToCheck_Width, colorAreaToCheck_Height), //A rectangle that specifies (in screen coordinates) //the destination for drawing the sprite. If this rectangle is not the same size as the source rectangle, the sprite will be scaled to fit. new Rectangle((int)(x - (colorAreaToCheck_Height / 2)), (int)(z - (colorAreaToCheck_Width / 2)), colorAreaToCheck_Width + (colorAreaToCheck_Width / 2), colorAreaToCheck_Height + (colorAreaToCheck_Height / 2)), //A rectangle that specifies (in texels) //the source texels from a texture. Use null to draw the entire texture. Color.White); //The color to tint a sprite. Use Color.White for full color with no tinting. spriteBatch.End(); GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; graphics.GraphicsDevice.SetRenderTarget(null); return trackRender; } //-------------------------------END----------------------------------- protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Add your drawing code here if (gameState == GameState.running) { base.Draw(gameTime); DrawGameRunning(); } else if (gameState == GameState.mainMenu) { DrawGameMainMenu(); } else if (gameState == GameState.raceFinished) { DrawGameRaceFinished(); } else if (gameState == GameState.gameOver) { DrawGameOver(); } } // Draw private void DrawGameOver() { GraphicsDevice.Clear(Color.Black); spriteBatch.Begin(); spriteBatch.Draw(podiumImage, new Vector2((Window.ClientBounds.Width / 2) - (startScreenImage.Width / 2), (Window.ClientBounds.Height / 2) - (startScreenImage.Height / 2)), Color.White); spriteBatch.DrawString(basicFont, "GAME OVER", new Vector2(100, 100), Color.White); spriteBatch.DrawString(basicFont, "Drivers Championship\n" + DisplayDriversTable(), new Vector2(100, 120), Color.White); spriteBatch.End(); GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; } private void DrawGameRaceFinished() { GraphicsDevice.Clear(Color.Black); spriteBatch.Begin(); spriteBatch.Draw(winImage, new Vector2((Window.ClientBounds.Width / 2) - (startScreenImage.Width / 2), (Window.ClientBounds.Height / 2) - (startScreenImage.Height / 2)), Color.White); spriteBatch.DrawString(raceResultsFont, "Race Finished, " + GlobalGameData.racePosition[0].carName + " won that one, Hit enter to continue to race " + GlobalGameData.nextTrack, new Vector2(100, 70), Color.Yellow); spriteBatch.DrawString(raceResultsFont, "Race Results\n" + RacePosition(), new Vector2(100, 90), Color.Yellow); spriteBatch.End(); GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; } private void DrawGameMainMenu() { GraphicsDevice.Clear(Color.Black); videoSplashTexture = myPlayer.GetTexture(); Rectangle screen = new Rectangle(GraphicsDevice.Viewport.X, GraphicsDevice.Viewport.Y, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); spriteBatch.Begin(); spriteBatch.Draw(videoSplashTexture, screen, Color.White); //spriteBatch.Draw(startScreenImage, new Vector2((Window.ClientBounds.Width / 2) - (startScreenImage.Width / 2), (Window.ClientBounds.Height / 2) //- (startScreenImage.Height / 2)), Color.White); //spriteBatch.DrawString(raceResultsFont, "Press enter to start", new Vector2(100, 70), Color.Yellow); spriteBatch.End(); GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; } private void DrawGameRunning() { // Draw text with a sprite tutorial http://msdn.microsoft.com/en-us/library/bb447673.aspx //then 2d followed by resetting some values spriteBatch.Begin(); if (startCountDown == true && countDown > 0) spriteBatch.DrawString(countDownFont, "" + countDown, new Vector2((Window.ClientBounds.Width / 2) - 50, (Window.ClientBounds.Height / 2) - 100), Color.Red); if (startCountDown == true && countDown == 0) spriteBatch.DrawString(countDownFont, "GO!", new Vector2((Window.ClientBounds.Width / 2) - 50, (Window.ClientBounds.Height / 2) - 100), Color.Green); spriteBatch.DrawString(HUDfont, "Laps Completed " + GlobalGameData.playerCar.numberOfLapsCompletedOnCurrentTrack, new Vector2(10, 10), Color.Black); spriteBatch.DrawString(HUDfont, "Bonus Item: " + GlobalGameData.playerCar.currentBonusItem, new Vector2(10, 30), Color.Black); spriteBatch.DrawString(HUDfont, "Current Speed: " + GlobalGameData.playerCar.currentSpeed.ToString("#.#"), new Vector2(10, 50), Color.Black); spriteBatch.DrawString(HUDfont, "km/h", new Vector2(170, 50), Color.Black); if (GlobalGameData.racePosition.Count == 0) spriteBatch.DrawString(basicFont, "Track positions for lap\n" + RacePosition(), new Vector2(10, 70), Color.Black); else spriteBatch.DrawString(basicFont, "Track positions for lap " + GlobalGameData.racePosition[0].numberOfLapsCompletedOnCurrentTrack + "\n" + RacePosition(), new Vector2(10, 70), Color.Black); spriteBatch.End(); //mixing 2d with 3d causes model to be drawn incorrectly, to fix this implement the following //solution from http://blogs.msdn.com/b/shawnhar/archive/2010/06/18/spritebatch-and-renderstates-in-xna-game-studio-4-0.aspx GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default; } private string DisplayDriversTable() { if (sortAndExtractDriversChampionshipStandings == true) { int index = 1; //http://blog.codewrench.net/2009/04/14/sorting-a-generic-list-on-arbitrary-property/ //var sortedCarList = from p in GlobalGameData.racePosition // orderby p.driverPoints descending // select p; //foreach (var car in sortedCarList) //{ // driverStandingAsAsString = driverStandingAsAsString + index + ". " + car.carName + ": " + car.driverPoints + "\n"; // index++; //} // Replaced above code with a sort and custom comparator class GlobalGameData.racePosition.Sort(new CompareDriversPoints()); foreach (Car c in GlobalGameData.racePosition) { driverStandingAsAsString = driverStandingAsAsString + index + ". " + c.carName + ": " + c.driverPoints + "\n"; index++; } sortAndExtractDriversChampionshipStandings = false; } return driverStandingAsAsString; } // Once race is over assign points to drivers private void AssignPoints() { if (GlobalGameData.racePosition.Count > 0 && canAssignPoints == true) { foreach (Car c in GlobalGameData.racePosition) { switch (GlobalGameData.racePosition.IndexOf(c)) { case 0: c.driverPoints = c.driverPoints + 10; break; case 1: c.driverPoints = c.driverPoints + 8; break; case 2: c.driverPoints = c.driverPoints + 7; break; case 3: c.driverPoints = c.driverPoints + 6; break; } } } canAssignPoints = false; } private String RacePosition() { /* * Used for building string that will display the cars in order of their position */ if (GlobalGameData.racePosition.Count > 0) { String racePositionAsString = ""; foreach (Car c in GlobalGameData.racePosition) { racePositionAsString = racePositionAsString + (GlobalGameData.racePosition.IndexOf(c) + 1) + ". " + c.carName + "\n"; } return racePositionAsString; } else return ""; } } }
namespace XenAdmin.Controls.NetworkingTab { partial class NetworkList { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NetworkList)); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.AddNetworkButton = new System.Windows.Forms.Button(); this.EditButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.EditNetworkButton = new System.Windows.Forms.Button(); this.RemoveButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.RemoveNetworkButton = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.toolTipContainerActivateToggle = new XenAdmin.Controls.ToolTipContainer(); this.buttonActivateToggle = new System.Windows.Forms.Button(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.addToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.removeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.propertiesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.NetworksGridView = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.ImageColumn = new System.Windows.Forms.DataGridViewImageColumn(); this.NameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.DescriptionColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.NicColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.VlanColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.AutoColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.LinkStatusColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.NetworkMacColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.VifMacColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.DeviceColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.LimitColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.NetworkColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.IpColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ActiveColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.MtuColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.NetworkSriovColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.flowLayoutPanel1.SuspendLayout(); this.EditButtonContainer.SuspendLayout(); this.RemoveButtonContainer.SuspendLayout(); this.toolTipContainerActivateToggle.SuspendLayout(); this.contextMenuStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.NetworksGridView)).BeginInit(); this.SuspendLayout(); // // flowLayoutPanel1 // this.flowLayoutPanel1.BackColor = System.Drawing.Color.Transparent; this.flowLayoutPanel1.Controls.Add(this.AddNetworkButton); this.flowLayoutPanel1.Controls.Add(this.EditButtonContainer); this.flowLayoutPanel1.Controls.Add(this.RemoveButtonContainer); this.flowLayoutPanel1.Controls.Add(this.groupBox1); this.flowLayoutPanel1.Controls.Add(this.toolTipContainerActivateToggle); resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; // // AddNetworkButton // resources.ApplyResources(this.AddNetworkButton, "AddNetworkButton"); this.AddNetworkButton.Name = "AddNetworkButton"; this.AddNetworkButton.UseVisualStyleBackColor = true; this.AddNetworkButton.Click += new System.EventHandler(this.AddNetworkButton_Click); // // EditButtonContainer // this.EditButtonContainer.Controls.Add(this.EditNetworkButton); resources.ApplyResources(this.EditButtonContainer, "EditButtonContainer"); this.EditButtonContainer.Name = "EditButtonContainer"; // // EditNetworkButton // resources.ApplyResources(this.EditNetworkButton, "EditNetworkButton"); this.EditNetworkButton.Name = "EditNetworkButton"; this.EditNetworkButton.UseVisualStyleBackColor = true; this.EditNetworkButton.Click += new System.EventHandler(this.EditNetworkButton_Click); // // RemoveButtonContainer // resources.ApplyResources(this.RemoveButtonContainer, "RemoveButtonContainer"); this.RemoveButtonContainer.Controls.Add(this.RemoveNetworkButton); this.RemoveButtonContainer.Name = "RemoveButtonContainer"; // // RemoveNetworkButton // resources.ApplyResources(this.RemoveNetworkButton, "RemoveNetworkButton"); this.RemoveNetworkButton.Name = "RemoveNetworkButton"; this.RemoveNetworkButton.UseVisualStyleBackColor = true; this.RemoveNetworkButton.Click += new System.EventHandler(this.RemoveNetworkButton_Click); // // groupBox1 // resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Name = "groupBox1"; this.groupBox1.TabStop = false; // // toolTipContainerActivateToggle // this.toolTipContainerActivateToggle.Controls.Add(this.buttonActivateToggle); resources.ApplyResources(this.toolTipContainerActivateToggle, "toolTipContainerActivateToggle"); this.toolTipContainerActivateToggle.Name = "toolTipContainerActivateToggle"; // // buttonActivateToggle // resources.ApplyResources(this.buttonActivateToggle, "buttonActivateToggle"); this.buttonActivateToggle.Name = "buttonActivateToggle"; this.buttonActivateToggle.UseVisualStyleBackColor = true; this.buttonActivateToggle.Click += new System.EventHandler(this.buttonActivateToggle_Click); // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.copyToolStripMenuItem, this.addToolStripMenuItem, this.removeToolStripMenuItem, this.propertiesToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; resources.ApplyResources(this.contextMenuStrip1, "contextMenuStrip1"); this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Image = global::XenAdmin.Properties.Resources.copy_16; this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; resources.ApplyResources(this.copyToolStripMenuItem, "copyToolStripMenuItem"); this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click); // // addToolStripMenuItem // this.addToolStripMenuItem.Name = "addToolStripMenuItem"; resources.ApplyResources(this.addToolStripMenuItem, "addToolStripMenuItem"); this.addToolStripMenuItem.Click += new System.EventHandler(this.AddMenuItemHandler); // // removeToolStripMenuItem // this.removeToolStripMenuItem.Name = "removeToolStripMenuItem"; resources.ApplyResources(this.removeToolStripMenuItem, "removeToolStripMenuItem"); this.removeToolStripMenuItem.Click += new System.EventHandler(this.RemoveMenuItemHandler); // // propertiesToolStripMenuItem // this.propertiesToolStripMenuItem.Name = "propertiesToolStripMenuItem"; resources.ApplyResources(this.propertiesToolStripMenuItem, "propertiesToolStripMenuItem"); this.propertiesToolStripMenuItem.Click += new System.EventHandler(this.EditMenuItemHandler); // // NetworksGridView // this.NetworksGridView.AdjustColorsForClassic = false; resources.ApplyResources(this.NetworksGridView, "NetworksGridView"); this.NetworksGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells; this.NetworksGridView.BackgroundColor = System.Drawing.SystemColors.Window; this.NetworksGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.NetworksGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.NetworksGridView.ContextMenuStrip = this.contextMenuStrip1; this.NetworksGridView.Name = "NetworksGridView"; this.NetworksGridView.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.NetworksGridView_CellValueChanged); this.NetworksGridView.SelectionChanged += new System.EventHandler(this.NetworksGridView_SelectionChanged); this.NetworksGridView.SortCompare += new System.Windows.Forms.DataGridViewSortCompareEventHandler(this.NetworksGridView_SortCompare); // // ImageColumn // this.ImageColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ImageColumn, "ImageColumn"); this.ImageColumn.Name = "ImageColumn"; // // NameColumn // this.NameColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.NameColumn, "NameColumn"); this.NameColumn.Name = "NameColumn"; // // DescriptionColumn // this.DescriptionColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.DescriptionColumn, "DescriptionColumn"); this.DescriptionColumn.Name = "DescriptionColumn"; this.DescriptionColumn.Resizable = System.Windows.Forms.DataGridViewTriState.False; // // NicColumn // this.NicColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.NicColumn, "NicColumn"); this.NicColumn.Name = "NicColumn"; // // VlanColumn // this.VlanColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.VlanColumn, "VlanColumn"); this.VlanColumn.Name = "VlanColumn"; // // AutoColumn // this.AutoColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.AutoColumn, "AutoColumn"); this.AutoColumn.Name = "AutoColumn"; // // LinkStatusColumn // this.LinkStatusColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.LinkStatusColumn, "LinkStatusColumn"); this.LinkStatusColumn.Name = "LinkStatusColumn"; // // NetworkMacColumn // this.NetworkMacColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.NetworkMacColumn, "NetworkMacColumn"); this.NetworkMacColumn.Name = "NetworkMacColumn"; // // VifMacColumn // this.VifMacColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.VifMacColumn, "VifMacColumn"); this.VifMacColumn.Name = "VifMacColumn"; // // DeviceColumn // this.DeviceColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.DeviceColumn, "DeviceColumn"); this.DeviceColumn.Name = "DeviceColumn"; // // LimitColumn // this.LimitColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.LimitColumn, "LimitColumn"); this.LimitColumn.Name = "LimitColumn"; // // NetworkColumn // this.NetworkColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.NetworkColumn, "NetworkColumn"); this.NetworkColumn.Name = "NetworkColumn"; this.NetworkColumn.Resizable = System.Windows.Forms.DataGridViewTriState.False; // // IpColumn // this.IpColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.IpColumn, "IpColumn"); this.IpColumn.Name = "IpColumn"; this.IpColumn.Resizable = System.Windows.Forms.DataGridViewTriState.False; // // ActiveColumn // this.ActiveColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.ActiveColumn, "ActiveColumn"); this.ActiveColumn.Name = "ActiveColumn"; // // MtuColumn // this.MtuColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.MtuColumn, "MtuColumn"); this.MtuColumn.Name = "MtuColumn"; // // NetworkSriovColumn // this.NetworkSriovColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells; resources.ApplyResources(this.NetworkSriovColumn, "NetworkSriovColumn"); this.NetworkSriovColumn.Name = "NetworkSriovColumn"; // // NetworkList // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.Controls.Add(this.flowLayoutPanel1); this.Controls.Add(this.NetworksGridView); this.Name = "NetworkList"; this.flowLayoutPanel1.ResumeLayout(false); this.EditButtonContainer.ResumeLayout(false); this.RemoveButtonContainer.ResumeLayout(false); this.toolTipContainerActivateToggle.ResumeLayout(false); this.contextMenuStrip1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.NetworksGridView)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private ToolTipContainer RemoveButtonContainer; private System.Windows.Forms.Button RemoveNetworkButton; private ToolTipContainer EditButtonContainer; private System.Windows.Forms.Button EditNetworkButton; private System.Windows.Forms.Button AddNetworkButton; private XenAdmin.Controls.DataGridViewEx.DataGridViewEx NetworksGridView; private System.Windows.Forms.DataGridViewImageColumn ImageColumn; private System.Windows.Forms.DataGridViewTextBoxColumn NameColumn; private System.Windows.Forms.DataGridViewTextBoxColumn DescriptionColumn; private System.Windows.Forms.DataGridViewTextBoxColumn NicColumn; private System.Windows.Forms.DataGridViewTextBoxColumn VlanColumn; private System.Windows.Forms.DataGridViewTextBoxColumn AutoColumn; private System.Windows.Forms.DataGridViewTextBoxColumn LinkStatusColumn; private System.Windows.Forms.DataGridViewTextBoxColumn NetworkMacColumn; private System.Windows.Forms.DataGridViewTextBoxColumn VifMacColumn; private System.Windows.Forms.DataGridViewTextBoxColumn DeviceColumn; private System.Windows.Forms.DataGridViewTextBoxColumn LimitColumn; private System.Windows.Forms.DataGridViewTextBoxColumn NetworkColumn; private System.Windows.Forms.DataGridViewTextBoxColumn IpColumn; private System.Windows.Forms.DataGridViewTextBoxColumn ActiveColumn; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem addToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem removeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem propertiesToolStripMenuItem; private ToolTipContainer toolTipContainerActivateToggle; private System.Windows.Forms.Button buttonActivateToggle; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.DataGridViewTextBoxColumn MtuColumn; private System.Windows.Forms.DataGridViewTextBoxColumn NetworkSriovColumn; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/language/v1beta2/language_service.proto // Original file comments: // Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace Google.Cloud.Language.V1 { /// <summary> /// Provides text analysis operations such as sentiment analysis and entity /// recognition. /// </summary> public static partial class LanguageService { static readonly string __ServiceName = "google.cloud.language.v1beta2.LanguageService"; static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeSentimentRequest> __Marshaller_AnalyzeSentimentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSentimentRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> __Marshaller_AnalyzeSentimentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSentimentResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest> __Marshaller_AnalyzeEntitiesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> __Marshaller_AnalyzeEntitiesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest> __Marshaller_AnalyzeEntitySentimentRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse> __Marshaller_AnalyzeEntitySentimentResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest> __Marshaller_AnalyzeSyntaxRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> __Marshaller_AnalyzeSyntaxResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnnotateTextRequest> __Marshaller_AnnotateTextRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnnotateTextRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Language.V1.AnnotateTextResponse> __Marshaller_AnnotateTextResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Language.V1.AnnotateTextResponse.Parser.ParseFrom); static readonly grpc::Method<global::Google.Cloud.Language.V1.AnalyzeSentimentRequest, global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> __Method_AnalyzeSentiment = new grpc::Method<global::Google.Cloud.Language.V1.AnalyzeSentimentRequest, global::Google.Cloud.Language.V1.AnalyzeSentimentResponse>( grpc::MethodType.Unary, __ServiceName, "AnalyzeSentiment", __Marshaller_AnalyzeSentimentRequest, __Marshaller_AnalyzeSentimentResponse); static readonly grpc::Method<global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest, global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> __Method_AnalyzeEntities = new grpc::Method<global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest, global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse>( grpc::MethodType.Unary, __ServiceName, "AnalyzeEntities", __Marshaller_AnalyzeEntitiesRequest, __Marshaller_AnalyzeEntitiesResponse); static readonly grpc::Method<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest, global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse> __Method_AnalyzeEntitySentiment = new grpc::Method<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest, global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse>( grpc::MethodType.Unary, __ServiceName, "AnalyzeEntitySentiment", __Marshaller_AnalyzeEntitySentimentRequest, __Marshaller_AnalyzeEntitySentimentResponse); static readonly grpc::Method<global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest, global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> __Method_AnalyzeSyntax = new grpc::Method<global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest, global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse>( grpc::MethodType.Unary, __ServiceName, "AnalyzeSyntax", __Marshaller_AnalyzeSyntaxRequest, __Marshaller_AnalyzeSyntaxResponse); static readonly grpc::Method<global::Google.Cloud.Language.V1.AnnotateTextRequest, global::Google.Cloud.Language.V1.AnnotateTextResponse> __Method_AnnotateText = new grpc::Method<global::Google.Cloud.Language.V1.AnnotateTextRequest, global::Google.Cloud.Language.V1.AnnotateTextResponse>( grpc::MethodType.Unary, __ServiceName, "AnnotateText", __Marshaller_AnnotateTextRequest, __Marshaller_AnnotateTextResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Language.V1.LanguageServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of LanguageService</summary> public abstract partial class LanguageServiceBase { /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> AnalyzeSentiment(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> AnalyzeEntities(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes /// sentiment associated with each entity and its mentions. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse> AnalyzeEntitySentiment(global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> AnalyzeSyntax(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// A convenience method that provides all syntax, sentiment, and entity /// features in one call. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Language.V1.AnnotateTextResponse> AnnotateText(global::Google.Cloud.Language.V1.AnnotateTextRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for LanguageService</summary> public partial class LanguageServiceClient : grpc::ClientBase<LanguageServiceClient> { /// <summary>Creates a new client for LanguageService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public LanguageServiceClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for LanguageService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public LanguageServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected LanguageServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected LanguageServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Language.V1.AnalyzeSentimentResponse AnalyzeSentiment(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AnalyzeSentiment(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Language.V1.AnalyzeSentimentResponse AnalyzeSentiment(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AnalyzeSentiment, null, options, request); } /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> AnalyzeSentimentAsync(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AnalyzeSentimentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Analyzes the sentiment of the provided text. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSentimentResponse> AnalyzeSentimentAsync(global::Google.Cloud.Language.V1.AnalyzeSentimentRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AnalyzeSentiment, null, options, request); } /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse AnalyzeEntities(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AnalyzeEntities(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse AnalyzeEntities(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AnalyzeEntities, null, options, request); } /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AnalyzeEntitiesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Finds named entities (currently proper names and common nouns) in the text /// along with entity types, salience, mentions for each entity, and /// other properties. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(global::Google.Cloud.Language.V1.AnalyzeEntitiesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AnalyzeEntities, null, options, request); } /// <summary> /// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes /// sentiment associated with each entity and its mentions. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse AnalyzeEntitySentiment(global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AnalyzeEntitySentiment(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes /// sentiment associated with each entity and its mentions. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse AnalyzeEntitySentiment(global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AnalyzeEntitySentiment, null, options, request); } /// <summary> /// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes /// sentiment associated with each entity and its mentions. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse> AnalyzeEntitySentimentAsync(global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AnalyzeEntitySentimentAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Finds entities, similar to [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text and analyzes /// sentiment associated with each entity and its mentions. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeEntitySentimentResponse> AnalyzeEntitySentimentAsync(global::Google.Cloud.Language.V1.AnalyzeEntitySentimentRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AnalyzeEntitySentiment, null, options, request); } /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse AnalyzeSyntax(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AnalyzeSyntax(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse AnalyzeSyntax(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AnalyzeSyntax, null, options, request); } /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AnalyzeSyntaxAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Analyzes the syntax of the text and provides sentence boundaries and /// tokenization along with part of speech tags, dependency trees, and other /// properties. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(global::Google.Cloud.Language.V1.AnalyzeSyntaxRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AnalyzeSyntax, null, options, request); } /// <summary> /// A convenience method that provides all syntax, sentiment, and entity /// features in one call. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Language.V1.AnnotateTextResponse AnnotateText(global::Google.Cloud.Language.V1.AnnotateTextRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AnnotateText(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A convenience method that provides all syntax, sentiment, and entity /// features in one call. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Language.V1.AnnotateTextResponse AnnotateText(global::Google.Cloud.Language.V1.AnnotateTextRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AnnotateText, null, options, request); } /// <summary> /// A convenience method that provides all syntax, sentiment, and entity /// features in one call. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnnotateTextResponse> AnnotateTextAsync(global::Google.Cloud.Language.V1.AnnotateTextRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AnnotateTextAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// A convenience method that provides all syntax, sentiment, and entity /// features in one call. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Language.V1.AnnotateTextResponse> AnnotateTextAsync(global::Google.Cloud.Language.V1.AnnotateTextRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AnnotateText, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override LanguageServiceClient NewInstance(ClientBaseConfiguration configuration) { return new LanguageServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(LanguageServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_AnalyzeSentiment, serviceImpl.AnalyzeSentiment) .AddMethod(__Method_AnalyzeEntities, serviceImpl.AnalyzeEntities) .AddMethod(__Method_AnalyzeEntitySentiment, serviceImpl.AnalyzeEntitySentiment) .AddMethod(__Method_AnalyzeSyntax, serviceImpl.AnalyzeSyntax) .AddMethod(__Method_AnnotateText, serviceImpl.AnnotateText).Build(); } } } #endregion
// Copyright (c) 2015 Alachisoft // // 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; using System.Collections; using System.Threading; using Alachisoft.NCache.Caching.Statistics; using Alachisoft.NCache.Common.DataStructures; using Alachisoft.NCache.Common.Monitoring; using Alachisoft.NCache.Common.Util; using Alachisoft.NCache.Common.Threading; namespace Alachisoft.NCache.Caching.Topologies.Clustered { #region Queue replicator public class AsyncItemReplicator : IDisposable { CacheRuntimeContext _context = null; TimeSpan _interval = new TimeSpan(0, 0, 2); Thread runner = null; OptimizedQueue _queue = new OptimizedQueue(); private Hashtable _updateIndexKeys = Hashtable.Synchronized(new Hashtable()); private long _uniqueKeyNumber; private int _updateIndexMoveThreshhold = 200; private int _moveCount; private bool stopped = true; private int _bulkKeysToReplicate = 300; internal AsyncItemReplicator(CacheRuntimeContext context, TimeSpan interval) { if (System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.BulkItemsToReplicate"] != null) { _bulkKeysToReplicate = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.BulkItemsToReplicate"]); } this._context = context; this._interval = interval; } /// <summary> /// Creates a new Thread and Starts it. /// </summary> public void Start() { if (stopped) { stopped = false; runner = new Thread(new ThreadStart(Run)); runner.IsBackground = true; runner.Name = "AsyncItemReplicationThread"; runner.Start(); } } /// <summary> /// An operation to update an index on the replica node is queued to be /// replicate. These operations are send in bulk to the replica node. /// </summary> /// <param name="key"></param> public void AddUpdateIndexKey(object key) { lock (_updateIndexKeys.SyncRoot) { _updateIndexKeys[key] = null; _context.PerfStatsColl.IncrementSlidingIndexQueueSizeStats(_updateIndexKeys.Count); } } public void RemoveUpdateIndexKey(object key) { lock (_updateIndexKeys.SyncRoot) { _updateIndexKeys.Remove(key); _context.PerfStatsColl.IncrementSlidingIndexQueueSizeStats(_updateIndexKeys.Count); } } /// <summary> /// Add the key and entry in teh Hashtable for Invalidation by preodic thread. /// </summary> /// <param name="key">The key of the item to invalidate.</param> /// <param name="entry">CacheEntry to Invalidate.</param> internal void EnqueueOperation(object key, ReplicationOperation operation) { try { if (key == null) key = System.Guid.NewGuid().ToString() + Interlocked.Increment(ref _uniqueKeyNumber); _queue.Enqueue(key, operation); if (ServerMonitor.MonitorActivity) ServerMonitor.LogClientActivity("AsyncReplicator.Enque", "queue_size :" + _queue.Count); _context.PerfStatsColl.IncrementMirrorQueueSizeStats(_queue.Count); } catch (Exception e) { if (_context.NCacheLog.IsErrorEnabled) _context.NCacheLog.Error("AsyncItemReplicator", string.Format("Exception: {0}", e.ToString())); } } /// <summary> /// Clears the Queue of any keys for replication. /// </summary> public void Clear() { //keysQue.Clear(); _queue.Clear(); _context.PerfStatsColl.IncrementMirrorQueueSizeStats(_queue.Count); } /// <summary> /// Clears the Queue of any keys for replication. /// </summary> internal void EnqueueClear(ReplicationOperation operation) { //keysQue.Clear(); _queue.Clear(); this.EnqueueOperation("NcAcHe$Cl@Ea%R", operation); } private object[] GetIndexOperations() { object[] keys = null; lock (_updateIndexKeys.SyncRoot) { _moveCount++; if (_updateIndexKeys.Count >= _updateIndexMoveThreshhold || _moveCount > 2) { if (_updateIndexKeys.Count > 0) { keys = new object[_updateIndexKeys.Count]; IDictionaryEnumerator ide = _updateIndexKeys.GetEnumerator(); int index = 0; while (ide.MoveNext()) { keys[index] = ide.Key; index++; } } _moveCount = 0; _updateIndexKeys.Clear(); } } return keys; } /// <summary> /// replication thread function. /// note: While replicating operations, a dummy '0' sequence id is passed. /// this sequence id is totally ignored by asynchronous POR, but we are keeping it /// to maintain the symmetry in API. /// </summary> public void Run() { ArrayList opCodesToBeReplicated = new ArrayList(_bulkKeysToReplicate); ArrayList infoToBeReplicated = new ArrayList(_bulkKeysToReplicate); ArrayList compilationInfo = new ArrayList(_bulkKeysToReplicate); ArrayList userPayLoad = new ArrayList(); try { while (!stopped || _queue.Count > 0) { DateTime startedAt = DateTime.Now; DateTime finishedAt = DateTime.Now; try { for (int i = 0; _queue.Count > 0 && i < _bulkKeysToReplicate; i++) { IOptimizedQueueOperation operation = null; operation = _queue.Dequeue(); DictionaryEntry entry = (DictionaryEntry)operation.Data; opCodesToBeReplicated.Add(entry.Key); infoToBeReplicated.Add(entry.Value); if (operation.UserPayLoad != null) { for (int j = 0; j < operation.UserPayLoad.Length; j++) { userPayLoad.Add(operation.UserPayLoad.GetValue(j)); } } compilationInfo.Add(operation.PayLoadSize); } object[] updateIndexKeys = GetIndexOperations(); if (!stopped) { if (opCodesToBeReplicated.Count > 0 || updateIndexKeys != null) { if (updateIndexKeys != null) { opCodesToBeReplicated.Add((int)ClusterCacheBase.OpCodes.UpdateIndice); infoToBeReplicated.Add(updateIndexKeys); } _context.CacheImpl.ReplicateOperations(opCodesToBeReplicated.ToArray(), infoToBeReplicated.ToArray(), userPayLoad.ToArray(), compilationInfo, _context.CacheImpl.OperationSequenceId, _context.CacheImpl.CurrentViewId); } } if (!stopped && _context.PerfStatsColl != null) _context.PerfStatsColl.IncrementMirrorQueueSizeStats(_queue.Count); } catch (Exception e) { if (e.Message.IndexOf("operation timeout", StringComparison.OrdinalIgnoreCase) >= 0) { _context.NCacheLog.CriticalInfo("AsyncReplicator.Run", "Bulk operation timedout. Retrying the operation."); try { if (!stopped) { _context.CacheImpl.ReplicateOperations(opCodesToBeReplicated.ToArray(), infoToBeReplicated.ToArray(), userPayLoad.ToArray(), compilationInfo, 0, 0); _context.NCacheLog.CriticalInfo("AsyncReplicator.Run", "RETRY is successfull."); } } catch (Exception ex) { if (_context.NCacheLog.IsErrorEnabled) _context.NCacheLog.Error( "AsyncReplicator.RUN", "Error occured while retrying operation. " + ex.ToString()); } } else if (_context.NCacheLog.IsErrorEnabled) _context.NCacheLog.Error( "AsyncReplicator.RUN", e.ToString()); } finally { opCodesToBeReplicated.Clear(); infoToBeReplicated.Clear(); compilationInfo.Clear(); userPayLoad.Clear(); finishedAt = DateTime.Now; } if (_queue.Count > 0) continue; if ((finishedAt.Ticks - startedAt.Ticks) < _interval.Ticks) Thread.Sleep(_interval.Subtract(finishedAt.Subtract(startedAt))); else Thread.Sleep(_interval); } } catch (ThreadAbortException ta) { } catch (ThreadInterruptedException ti) { } catch (NullReferenceException) { } catch (Exception e) { if (!stopped) _context.NCacheLog.Error("AsyncReplicator.RUN", "Async replicator stopped. " + e.ToString()); } } /// <summary> /// Stops and disposes the Repliaction thread. The thread can be started using Start method. /// <param name="gracefulStop">If true then operations pending in the queue are performed /// on the passive node, otherwise stopped instantly </param> /// </summary> public void Stop(bool gracefulStop) { stopped = true; if (runner != null && runner.IsAlive) { if (gracefulStop) runner.Join(); else { try { if (runner.IsAlive) { _context.NCacheLog.Flush(); runner.Abort(); } } catch (Exception) { } } try { Clear(); } catch { } } } /// <summary> /// Returns the number of operations in the queue. /// </summary> public long QueueCount { get { return _queue.Count; } } #region IDisposable Members /// <summary> /// Terminates the replciation thread and Disposes the instance. /// </summary> public void Dispose() { Stop(false); runner = null; } #endregion } #endregion /* // Summary: // Defines a ReplicationEntry with OperationCode and information that can be set or retrieved. public struct ReplicationEntry { private int _opCode; private object _info; // // Summary: // Initializes an instance of the Alachisoft.NCache.Caching.Topologies.Clustered.ReplicationEntry type with // the specified opCode and Inforamtion. // // Parameters: // Information: // The Information associated with key. // // opcode: // The operation code for the type of operation to perform on the key. // // Exceptions: // System.ArgumentNullException: // opCode is null and the .NET Framework version is 1.0 or 1.1. public ReplicationEntry(int opCode, object info) { _opCode = opCode; _info = info; } // // Summary: // Gets or sets the value in the ReplicationEntry. // // Returns: // The Information in the ReplicationEntry. public object Info { get { return _info; } set { _info = value; } } // // Summary: // Gets or sets the Operation Code in the inforamtion box. // // Returns: // The operation code for this key. public int OpCode { get { return _opCode; } set { _opCode = value; } } } */ }
using UnityEngine; using UnityEditor; using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.Reflection; using Model = UnityEngine.AssetGraph.DataModel.Version2; namespace UnityEngine.AssetGraph { public class BuildTargetUtility { public const BuildTargetGroup DefaultTarget = BuildTargetGroup.Unknown; /** * from build target to human friendly string for display purpose. */ public static string TargetToHumaneString (UnityEditor.BuildTarget t) { switch (t) { case BuildTarget.Android: return "Android"; case BuildTarget.iOS: return "iOS"; case BuildTarget.PS4: return "PlayStation 4"; case BuildTarget.PSP2: return "PlayStation Vita"; #if !UNITY_2017_3_OR_NEWER case BuildTarget.SamsungTV: return "Samsung TV"; #endif case BuildTarget.StandaloneLinux: return "Linux Standalone"; case BuildTarget.StandaloneLinux64: return "Linux Standalone(64-bit)"; case BuildTarget.StandaloneLinuxUniversal: return "Linux Standalone(Universal)"; #if UNITY_2017_3_OR_NEWER case BuildTarget.StandaloneOSX: #else case BuildTarget.StandaloneOSXIntel: return "OSX Standalone"; case BuildTarget.StandaloneOSXIntel64: return "OSX Standalone(64-bit)"; case BuildTarget.StandaloneOSXUniversal: #endif return "OSX Standalone(Universal)"; case BuildTarget.StandaloneWindows: return "Windows Standalone"; case BuildTarget.StandaloneWindows64: return "Windows Standalone(64-bit)"; case BuildTarget.Tizen: return "Tizen"; case BuildTarget.tvOS: return "tvOS"; case BuildTarget.WebGL: return "WebGL"; #if !UNITY_2018_1_OR_NEWER case BuildTarget.WiiU: return "Wii U"; #endif case BuildTarget.WSAPlayer: return "Windows Store Apps"; case BuildTarget.XboxOne: return "Xbox One"; #if !UNITY_5_5_OR_NEWER case BuildTarget.Nintendo3DS: return "Nintendo 3DS"; case BuildTarget.PS3: return "PlayStation 3"; case BuildTarget.XBOX360: return "Xbox 360"; #endif #if UNITY_5_5_OR_NEWER case BuildTarget.N3DS: return "Nintendo 3DS"; #endif #if UNITY_5_6 || UNITY_5_6_OR_NEWER case BuildTarget.Switch: return "Nintendo Switch"; #endif default: return t.ToString () + "(deprecated)"; } } public enum PlatformNameType { Default, TextureImporter, AudioImporter, VideoClipImporter } public static string TargetToAssetBundlePlatformName (BuildTargetGroup g, PlatformNameType pnt = PlatformNameType.Default) { return TargetToAssetBundlePlatformName (GroupToTarget (g), pnt); } //returns the same value defined in AssetBundleManager public static string TargetToAssetBundlePlatformName (BuildTarget t, PlatformNameType pnt = PlatformNameType.Default) { switch (t) { case BuildTarget.Android: return "Android"; case BuildTarget.iOS: switch (pnt) { case PlatformNameType.TextureImporter: return "iPhone"; } return "iOS"; case BuildTarget.PS4: return "PS4"; case BuildTarget.PSP2: switch (pnt) { case PlatformNameType.AudioImporter: return "PSP2"; case PlatformNameType.TextureImporter: return "PSP2"; case PlatformNameType.VideoClipImporter: return "PSP2"; } return "PSVita"; #if !UNITY_2017_3_OR_NEWER case BuildTarget.SamsungTV: return "Samsung TV"; #endif case BuildTarget.StandaloneLinux: case BuildTarget.StandaloneLinux64: case BuildTarget.StandaloneLinuxUniversal: return "Linux"; #if UNITY_2017_3_OR_NEWER case BuildTarget.StandaloneOSX: #else case BuildTarget.StandaloneOSXIntel: case BuildTarget.StandaloneOSXIntel64: case BuildTarget.StandaloneOSXUniversal: #endif return "OSX"; case BuildTarget.StandaloneWindows: case BuildTarget.StandaloneWindows64: switch (pnt) { case PlatformNameType.AudioImporter: return "Standalone"; case PlatformNameType.TextureImporter: return "Standalone"; case PlatformNameType.VideoClipImporter: return "Standalone"; } return "Windows"; case BuildTarget.Tizen: return "Tizen"; case BuildTarget.tvOS: return "tvOS"; case BuildTarget.WebGL: return "WebGL"; #if !UNITY_2018_1_OR_NEWER case BuildTarget.WiiU: return "WiiU"; #endif case BuildTarget.WSAPlayer: switch (pnt) { case PlatformNameType.AudioImporter: return "WSA"; case PlatformNameType.VideoClipImporter: return "WSA"; } return "WindowsStoreApps"; case BuildTarget.XboxOne: return "XboxOne"; #if !UNITY_5_5_OR_NEWER case BuildTarget.Nintendo3DS: return "N3DS"; case BuildTarget.PS3: return "PS3"; case BuildTarget.XBOX360: return "Xbox360"; #endif #if UNITY_5_5_OR_NEWER case BuildTarget.N3DS: return "N3DS"; #endif #if UNITY_5_6 || UNITY_5_6_OR_NEWER case BuildTarget.Switch: return "Switch"; #endif default: return t.ToString () + "(deprecated)"; } } /** * from build target group to human friendly string for display purpose. */ public static string GroupToHumaneString (UnityEditor.BuildTargetGroup g) { switch (g) { case BuildTargetGroup.Android: return "Android"; case BuildTargetGroup.iOS: return "iOS"; case BuildTargetGroup.PS4: return "PlayStation 4"; case BuildTargetGroup.PSP2: return "PlayStation Vita"; #if !UNITY_2017_3_OR_NEWER case BuildTargetGroup.SamsungTV: return "Samsung TV"; #endif case BuildTargetGroup.Standalone: return "PC/Mac/Linux Standalone"; case BuildTargetGroup.Tizen: return "Tizen"; case BuildTargetGroup.tvOS: return "tvOS"; case BuildTargetGroup.WebGL: return "WebGL"; #if !UNITY_2018_1_OR_NEWER case BuildTargetGroup.WiiU: return "Wii U"; #endif case BuildTargetGroup.WSA: return "Windows Store Apps"; case BuildTargetGroup.XboxOne: return "Xbox One"; case BuildTargetGroup.Unknown: return "Unknown"; #if !UNITY_5_5_OR_NEWER case BuildTargetGroup.Nintendo3DS: return "Nintendo 3DS"; case BuildTargetGroup.PS3: return "PlayStation 3"; case BuildTargetGroup.XBOX360: return "Xbox 360"; #endif #if UNITY_5_5_OR_NEWER case BuildTargetGroup.N3DS: return "Nintendo 3DS"; #endif #if UNITY_5_6 || UNITY_5_6_OR_NEWER case BuildTargetGroup.Facebook: return "Facebook"; case BuildTargetGroup.Switch: return "Nintendo Switch"; #endif default: return g.ToString () + "(deprecated)"; } } public static BuildTargetGroup TargetToGroup (UnityEditor.BuildTarget t) { if ((int)t == int.MaxValue) { return BuildTargetGroup.Unknown; } switch (t) { case BuildTarget.Android: return BuildTargetGroup.Android; case BuildTarget.iOS: return BuildTargetGroup.iOS; case BuildTarget.PS4: return BuildTargetGroup.PS4; case BuildTarget.PSP2: return BuildTargetGroup.PSP2; #if !UNITY_2017_3_OR_NEWER case BuildTarget.SamsungTV: return BuildTargetGroup.SamsungTV; #endif case BuildTarget.StandaloneLinux: case BuildTarget.StandaloneLinux64: case BuildTarget.StandaloneLinuxUniversal: #if UNITY_2017_3_OR_NEWER case BuildTarget.StandaloneOSX: #else case BuildTarget.StandaloneOSXIntel: case BuildTarget.StandaloneOSXIntel64: case BuildTarget.StandaloneOSXUniversal: #endif case BuildTarget.StandaloneWindows: case BuildTarget.StandaloneWindows64: return BuildTargetGroup.Standalone; case BuildTarget.Tizen: return BuildTargetGroup.Tizen; case BuildTarget.tvOS: return BuildTargetGroup.tvOS; case BuildTarget.WebGL: return BuildTargetGroup.WebGL; #if !UNITY_2018_1_OR_NEWER case BuildTarget.WiiU: return BuildTargetGroup.WiiU; #endif case BuildTarget.WSAPlayer: return BuildTargetGroup.WSA; case BuildTarget.XboxOne: return BuildTargetGroup.XboxOne; #if !UNITY_5_5_OR_NEWER case BuildTarget.Nintendo3DS: return BuildTargetGroup.Nintendo3DS; case BuildTarget.PS3: return BuildTargetGroup.PS3; case BuildTarget.XBOX360: return BuildTargetGroup.XBOX360; #endif #if UNITY_5_5_OR_NEWER case BuildTarget.N3DS: return BuildTargetGroup.N3DS; #endif #if UNITY_5_6 || UNITY_5_6_OR_NEWER case BuildTarget.Switch: return BuildTargetGroup.Switch; #endif default: return BuildTargetGroup.Unknown; } } public static BuildTarget GroupToTarget (UnityEditor.BuildTargetGroup g) { switch (g) { case BuildTargetGroup.Android: return BuildTarget.Android; case BuildTargetGroup.iOS: return BuildTarget.iOS; case BuildTargetGroup.PS4: return BuildTarget.PS4; case BuildTargetGroup.PSP2: return BuildTarget.PSP2; #if !UNITY_2017_3_OR_NEWER case BuildTargetGroup.SamsungTV: return BuildTarget.SamsungTV; #endif case BuildTargetGroup.Standalone: return BuildTarget.StandaloneWindows; case BuildTargetGroup.Tizen: return BuildTarget.Tizen; case BuildTargetGroup.tvOS: return BuildTarget.tvOS; case BuildTargetGroup.WebGL: return BuildTarget.WebGL; #if !UNITY_2018_1_OR_NEWER case BuildTargetGroup.WiiU: return BuildTarget.WiiU; #endif case BuildTargetGroup.WSA: return BuildTarget.WSAPlayer; case BuildTargetGroup.XboxOne: return BuildTarget.XboxOne; #if !UNITY_5_5_OR_NEWER case BuildTargetGroup.Nintendo3DS: return BuildTarget.Nintendo3DS; case BuildTargetGroup.PS3: return BuildTarget.PS3; case BuildTargetGroup.XBOX360: return BuildTarget.XBOX360; #endif #if UNITY_5_5_OR_NEWER case BuildTargetGroup.N3DS: return BuildTarget.N3DS; #endif #if UNITY_5_6 || UNITY_5_6_OR_NEWER case BuildTargetGroup.Switch: return BuildTarget.Switch; case BuildTargetGroup.Facebook: return BuildTarget.StandaloneWindows; // TODO: Facebook can be StandardWindows or WebGL #endif default: // temporarily assigned for default value (BuildTargetGroup.Unknown) return (BuildTarget)int.MaxValue; } } public static BuildTarget BuildTargetFromString (string val) { return (BuildTarget)Enum.Parse(typeof(BuildTarget), val); } public static bool IsBuildTargetSupported(BuildTarget t) { BuildTargetGroup g = BuildTargetUtility.TargetToGroup(t); #if UNITY_2018_1_OR_NEWER return UnityEditor.BuildPipeline.IsBuildTargetSupported(g, t); #else var objType = typeof(UnityEditor.BuildPipeline); var method = objType.GetMethod("IsBuildTargetSupported", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); //internal static extern bool IsBuildTargetSupported (BuildTargetGroup buildTargetGroup, BuildTarget target); var retval = method.Invoke(null, new object[]{ System.Enum.ToObject(typeof(BuildTargetGroup), g), System.Enum.ToObject(typeof(BuildTarget), t)}); return Convert.ToBoolean(retval); #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.Xml; using System.ComponentModel; namespace System.ServiceModel.Channels { public sealed class BinaryMessageEncodingBindingElement : MessageEncodingBindingElement { private int _maxReadPoolSize; private int _maxWritePoolSize; private XmlDictionaryReaderQuotas _readerQuotas; private int _maxSessionSize; private BinaryVersion _binaryVersion; private MessageVersion _messageVersion; private long _maxReceivedMessageSize; public BinaryMessageEncodingBindingElement() { _maxReadPoolSize = EncoderDefaults.MaxReadPoolSize; _maxWritePoolSize = EncoderDefaults.MaxWritePoolSize; _readerQuotas = new XmlDictionaryReaderQuotas(); EncoderDefaults.ReaderQuotas.CopyTo(_readerQuotas); _maxSessionSize = BinaryEncoderDefaults.MaxSessionSize; _binaryVersion = BinaryEncoderDefaults.BinaryVersion; _messageVersion = MessageVersion.CreateVersion(BinaryEncoderDefaults.EnvelopeVersion); CompressionFormat = EncoderDefaults.DefaultCompressionFormat; } private BinaryMessageEncodingBindingElement(BinaryMessageEncodingBindingElement elementToBeCloned) : base(elementToBeCloned) { _maxReadPoolSize = elementToBeCloned._maxReadPoolSize; _maxWritePoolSize = elementToBeCloned._maxWritePoolSize; _readerQuotas = new XmlDictionaryReaderQuotas(); elementToBeCloned._readerQuotas.CopyTo(_readerQuotas); MaxSessionSize = elementToBeCloned.MaxSessionSize; BinaryVersion = elementToBeCloned.BinaryVersion; _messageVersion = elementToBeCloned._messageVersion; CompressionFormat = elementToBeCloned.CompressionFormat; _maxReceivedMessageSize = elementToBeCloned._maxReceivedMessageSize; } [DefaultValue(EncoderDefaults.DefaultCompressionFormat)] public CompressionFormat CompressionFormat { get; set; } /* public */ private BinaryVersion BinaryVersion { get { return _binaryVersion; } set { _binaryVersion = value ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); } } public override MessageVersion MessageVersion { get { return _messageVersion; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); } if (value.Envelope != BinaryEncoderDefaults.EnvelopeVersion) { string errorMsg = SR.Format(SR.UnsupportedEnvelopeVersion, GetType().FullName, BinaryEncoderDefaults.EnvelopeVersion, value.Envelope); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(errorMsg)); } _messageVersion = MessageVersion.CreateVersion(BinaryEncoderDefaults.EnvelopeVersion, value.Addressing); } } [DefaultValue(EncoderDefaults.MaxReadPoolSize)] public int MaxReadPoolSize { get { return _maxReadPoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value), value, SR.ValueMustBePositive)); } _maxReadPoolSize = value; } } [DefaultValue(EncoderDefaults.MaxWritePoolSize)] public int MaxWritePoolSize { get { return _maxWritePoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value), value, SR.ValueMustBePositive)); } _maxWritePoolSize = value; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return _readerQuotas; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); } value.CopyTo(_readerQuotas); } } [DefaultValue(BinaryEncoderDefaults.MaxSessionSize)] public int MaxSessionSize { get { return _maxSessionSize; } set { if (value < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value), value, SR.ValueMustBeNonNegative)); } _maxSessionSize = value; } } private void VerifyCompression(BindingContext context) { if (CompressionFormat != CompressionFormat.None) { ITransportCompressionSupport compressionSupport = context.GetInnerProperty<ITransportCompressionSupport>(); if (compressionSupport == null || !compressionSupport.IsCompressionFormatSupported(CompressionFormat)) { throw FxTrace.Exception.AsError(new NotSupportedException(SR.Format( SR.TransportDoesNotSupportCompression, CompressionFormat.ToString(), GetType().Name, CompressionFormat.None.ToString()))); } } } private void SetMaxReceivedMessageSizeFromTransport(BindingContext context) { TransportBindingElement transport = context.Binding.Elements.Find<TransportBindingElement>(); if (transport != null) { // We are guaranteed that a transport exists when building a binding; // Allow the regular flow/checks to happen rather than throw here // (InternalBuildChannelListener will call into the BindingContext. Validation happens there and it will throw) _maxReceivedMessageSize = transport.MaxReceivedMessageSize; } } public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context) { VerifyCompression(context); SetMaxReceivedMessageSizeFromTransport(context); return InternalBuildChannelFactory<TChannel>(context); } public override BindingElement Clone() { return new BinaryMessageEncodingBindingElement(this); } public override MessageEncoderFactory CreateMessageEncoderFactory() { return new BinaryMessageEncoderFactory( MessageVersion, MaxReadPoolSize, MaxWritePoolSize, MaxSessionSize, ReaderQuotas, _maxReceivedMessageSize, BinaryVersion, CompressionFormat); } public override T GetProperty<T>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(context)); } if (typeof(T) == typeof(XmlDictionaryReaderQuotas)) { return (T)(object)_readerQuotas; } else { return base.GetProperty<T>(context); } } internal override bool IsMatch(BindingElement b) { if (!base.IsMatch(b)) { return false; } BinaryMessageEncodingBindingElement binary = b as BinaryMessageEncodingBindingElement; if (binary == null) { return false; } if (_maxReadPoolSize != binary.MaxReadPoolSize) { return false; } if (_maxWritePoolSize != binary.MaxWritePoolSize) { return false; } // compare XmlDictionaryReaderQuotas if (_readerQuotas.MaxStringContentLength != binary.ReaderQuotas.MaxStringContentLength) { return false; } if (_readerQuotas.MaxArrayLength != binary.ReaderQuotas.MaxArrayLength) { return false; } if (_readerQuotas.MaxBytesPerRead != binary.ReaderQuotas.MaxBytesPerRead) { return false; } if (_readerQuotas.MaxDepth != binary.ReaderQuotas.MaxDepth) { return false; } if (_readerQuotas.MaxNameTableCharCount != binary.ReaderQuotas.MaxNameTableCharCount) { return false; } if (MaxSessionSize != binary.MaxSessionSize) { return false; } if (CompressionFormat != binary.CompressionFormat) { return false; } return true; } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeReaderQuotas() { return (!EncoderDefaults.IsDefaultReaderQuotas(ReaderQuotas)); } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeMessageVersion() { return (!_messageVersion.IsMatch(MessageVersion.Default)); } } }
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; /// MouseLook rotates the transform based on the mouse delta. /// Minimum and Maximum values can be used to constrain the possible rotation /// To make an FPS style character: /// - Create a capsule. /// - Add the MouseLook script to the capsule. /// -> Set the mouse look to use LookX. (You want to only turn character but not tilt it) /// - Add FPSInputController script to the capsule /// -> A CharacterMotor and a CharacterController component will be automatically added. /// - Create a camera. Make the camera a child of the capsule. Reset it's transform. /// - Add a MouseLook script to the camera. /// -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.) [AddComponentMenu("Camera-Control/Mouse Look")] public class MouseLook : MonoBehaviour { //public GameObject sys; //private MainScript mainScript; public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2, MouseZ = 3 } public RotationAxes axes = RotationAxes.MouseXAndY; public float sensitivityX = 7F; public float sensitivityY = 7F; public bool usePhasespace = false; public float minimumX = -360F; public float maximumX = 360F; public float minimumY = -90F; public float maximumY = 90F; float rotationY = 0F; float rotationX = 0F; float rotationZ = 0F; public float calibX = 0.0F; public float calibY = 0.0F; public float calibZ = 0.0F; public float offsetX = 0.0F; public float offsetY = 0.0F; public float offsetZ = 0.0F; [DllImport("UnityServerPlugin")] private static extern float getRoll(); [DllImport("UnityServerPlugin")] private static extern float getPitch(); [DllImport("UnityServerPlugin")] private static extern float getYaw(); [DllImport("UnityServerPlugin")] private static extern float getDragX(); [DllImport("UnityServerPlugin")] private static extern float getDragY(); [DllImport("UnityServerPlugin")] private static extern float getPSQuatW(); [DllImport("UnityServerPlugin")] private static extern float getPSQuatX(); [DllImport("UnityServerPlugin")] private static extern float getPSQuatY(); [DllImport("UnityServerPlugin")] private static extern float getPSQuatZ(); [DllImport("UnityServerPlugin")] private static extern void sendDistance(float distance); public Vector3 GetOrientation() { return mobileDeviceRotation.eulerAngles; } public Vector3 GetCalibration() { return new Vector3(calibX, calibY, calibZ); } Quaternion mobileDeviceRotation; Quaternion phaseSpaceRotation; GameObject distanceSphere; void Awake() { //sys = GameObject.Find("System"); //mainScript = sys.GetComponent<MainScript>(); mobileDeviceRotation = Quaternion.identity; phaseSpaceRotation = Quaternion.identity; lineRenderer = GetComponent<LineRenderer>(); distanceSphere = GameObject.Find("DistanceSphere"); } bool isFirstTouch = true; float firstTouchX = 0.0f; float firstTouchY = 0.0f; float oldDragX = 0.0f; float oldDragY = 0.0f; private LineRenderer lineRenderer; void Update() { // if(mainScript.getExperimentInterface() != (int)MainScript.interfaces.WIM) // { float roll = getRoll(); float pitch = getPitch(); //float yaw = -getYaw (); //minus to turn phone 180 degrees on other landscape float yaw = getYaw(); float phaseSpaceX = getPSQuatX(); float phaseSpaceY = getPSQuatY(); float phaseSpaceZ = getPSQuatZ(); float phaseSpaceW = getPSQuatW(); // mobileDeviceRotation = Quaternion.Euler(pitch /*- calibY*/, roll /*- calibX + 335f*/, yaw); // 335 is the rotation halfway between the two scene cameras (used for calibration) phaseSpaceRotation = new Quaternion(phaseSpaceX, phaseSpaceY, phaseSpaceZ, phaseSpaceW); Vector3 mobileDeviceRotEuler = mobileDeviceRotation.eulerAngles; Vector3 PSRotEuler = phaseSpaceRotation.eulerAngles; PSRotEuler.y += 180; mobileDeviceRotEuler.x = mobileDeviceRotEuler.x - calibX + offsetX; mobileDeviceRotEuler.y = mobileDeviceRotEuler.y - calibY + offsetY; mobileDeviceRotEuler.z = mobileDeviceRotEuler.z - calibZ + offsetZ; PSRotEuler.x = PSRotEuler.x - calibX + offsetX; PSRotEuler.y = PSRotEuler.y - calibY + offsetY; PSRotEuler.z = PSRotEuler.z - calibZ + offsetZ; mobileDeviceRotation = Quaternion.Euler(mobileDeviceRotEuler); phaseSpaceRotation = Quaternion.Euler (PSRotEuler); if (usePhasespace) { transform.rotation = phaseSpaceRotation; } else { transform.rotation = mobileDeviceRotation; } Ray ray = new Ray(transform.position, transform.rotation * Vector3.forward); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { lineRenderer.SetPosition(0, transform.position + new Vector3(0f, -0.5f, 0f)); lineRenderer.SetPosition(1, hit.point); sendDistance(hit.distance); distanceSphere.transform.position = hit.point; } else { lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, transform.position); sendDistance(-1); distanceSphere.transform.position = transform.position; } //transform.localRotation = Quaternion.Euler (30f,30f,0f); //transform.localEulerAngles = new Vector3(30f,30f,0f); // if (axes == RotationAxes.MouseX) // { // // // //rotationX += Input.GetAxis("Mouse X") * sensitivityX; // rotationX = roll - calibX + 330.0f; // rotationX = Mathf.Clamp (rotationX, minimumX, maximumX); // transform.localEulerAngles = new Vector3(0, rotationX, 0); // //Debug.Log ("X: " + Input.GetAxis("Mouse X")); // } // else if (axes == RotationAxes.MouseY) // { // //rotationY += -1*Input.GetAxis("Mouse Y") * sensitivityY; // rotationY = pitch - calibY; // rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); // transform.localEulerAngles = new Vector3(rotationY, 0, 0); // // } // else // { // //rotationZ += Input.GetAxis("Mouse Y") * sensitivityY; // rotationZ = yaw - calibZ; // transform.localEulerAngles = new Vector3(0, 0, rotationZ); // } // if (Input.GetKeyDown("c")) { calibY = roll; //- 180; calibX = pitch; //- 180; calibZ = yaw; //calibY = PSRotEuler.y;//roll; //calibX = PSRotEuler.x;//pitch; } //Offsets should be continuously updated with PhaseSpace //Something like: // calibX = PSRotEuler.x - pitch; // calibY = PSRotEuler.y - roll; // calibZ = PSRotEuler.z - yaw; //Debug.Log(roll + " "+ pitch + " " + yaw); // } // else // { // float dragX = getDragX (); // float dragY = getDragY (); // // if(axes == RotationAxes.MouseZ) // { // transform.localEulerAngles = new Vector3(0, 0, 0); // } // // if(dragX != 0 && dragY != 0) // { // if(isFirstTouch) // { // oldDragX = dragX; // oldDragY = dragY; // isFirstTouch = false; // } // else if (axes == RotationAxes.MouseX) // { // // rotationX += dragX - oldDragX; // oldDragX = dragX; // //rotationX = Mathf.Clamp (rotationX, minimumX, maximumX); // transform.localEulerAngles = new Vector3(0, -rotationX/sensitivityX, 0); // // //transform.Rotate(Vector3.right, rotationX); // // } // else if (axes == RotationAxes.MouseY) // { // rotationY += dragY - oldDragY; // oldDragY = dragY; // rotationY = Mathf.Clamp (rotationY, minimumY, maximumY); // transform.localEulerAngles = new Vector3(rotationY/sensitivityY, 0, 0); // //transform.Rotate(Vector3.up, rotationY); // } // // } // else // { // isFirstTouch = true; // } // } //transform.localEulerAngles = new Vector3(rotationY, rotationX, 0); //transform.Rotate(new Vector3(roll, pitch, yaw)); } void Start() { // Make the rigid body not change rotation if (GetComponent<Rigidbody>()) GetComponent<Rigidbody>().freezeRotation = true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Loon.Core; using Loon.Core.Graphics.Opengl; using Loon.Core.Timer; using Loon.Action.Map; using Loon.Core.Geom; namespace Loon.Action.Sprite.Effect { public class ScrollEffect : LObject,ISprite { private int backgroundLoop; private int count; private int width, height; private LTexture texture; private bool visible, stop; private LTimer timer; private int code; public ScrollEffect(string fileName) : this(new LTexture(fileName)) { } public ScrollEffect(LTexture tex2d) : this(Config.DOWN, tex2d, LSystem.screenRect) { } public ScrollEffect(int d, string fileName) : this(d, new LTexture(fileName)) { } public ScrollEffect(int d, LTexture tex2d) : this(d, tex2d, LSystem.screenRect) { } public ScrollEffect(int d, string fileName, RectBox limit) : this(d, new LTexture(fileName), limit) { } public ScrollEffect(int d, LTexture tex2d, RectBox limit) : this(d, tex2d, limit.x, limit.y, limit.width, limit.height) { } public ScrollEffect(int d, LTexture tex2d, float x, float y, int w, int h) { this.SetLocation(x, y); this.texture = tex2d; this.width = w; this.height = h; this.count = 1; this.timer = new LTimer(10); this.visible = true; this.code = d; } public void SetDelay(long delay) { timer.SetDelay(delay); } public long GetDelay() { return timer.GetDelay(); } public override int GetHeight() { return height; } public override int GetWidth() { return width; } public override void Update(long elapsedTime) { if (stop) { return; } if (timer.Action(elapsedTime)) { switch (code) { case Config.DOWN: case Config.TDOWN: case Config.UP: case Config.TUP: this.backgroundLoop = ((backgroundLoop + count) % height); break; case Config.LEFT: case Config.RIGHT: case Config.TLEFT: case Config.TRIGHT: this.backgroundLoop = ((backgroundLoop + count) % width); break; } } } public void CreateUI(GLEx g) { if (!visible) { return; } if (alpha > 0 && alpha < 1) { g.SetAlpha(alpha); } texture.GLBegin(); switch (code) { case Config.DOWN: case Config.TDOWN: for (int i = -1; i < 1; i++) { for (int j = 0; j < 1; j++) { texture.Draw(X() + (j * width), Y() + (i * height + backgroundLoop), width, height, 0, 0, width, height); } } break; case Config.RIGHT: case Config.TRIGHT: for (int j = -1; j < 1; j++) { for (int i = 0; i < 1; i++) { texture.Draw(X() + (j * width + backgroundLoop), Y() + (i * height), width, height, 0, 0, width, height); } } break; case Config.UP: case Config.TUP: for (int i = -1; i < 1; i++) { for (int j = 0; j < 1; j++) { texture.Draw(X() + (j * width), Y() - (i * height + backgroundLoop), width, height, 0, 0, width, height); } } break; case Config.LEFT: case Config.TLEFT: for (int j = -1; j < 1; j++) { for (int i = 0; i < 1; i++) { texture.Draw(X() - (j * width + backgroundLoop), Y() + (i * height), width, height, 0, 0, width, height); } } break; } texture.GLEnd(); if (alpha > 0 && alpha < 1) { g.SetAlpha(1f); } } public int GetCount() { return count; } public void SetCount(int count) { this.count = count; } public LTexture GetBitmap() { return texture; } public bool IsStop() { return stop; } public void SetStop(bool stop) { this.stop = stop; } public RectBox GetCollisionBox() { return GetRect(X(), Y(), width, height); } public bool IsVisible() { return visible; } public void SetVisible(bool visible) { this.visible = visible; } public void Dispose() { if (texture != null) { texture.Destroy(); texture = null; } } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Text; using DotSpatial.Data; using DotSpatial.NTSExtension; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// Symbolizer for point features. /// </summary> public class PointSymbolizer : FeatureSymbolizer, IPointSymbolizer { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="PointSymbolizer"/> class. /// </summary> public PointSymbolizer() { Configure(); } /// <summary> /// Initializes a new instance of the <see cref="PointSymbolizer"/> class with only one symbol. /// </summary> /// <param name="symbol">The symbol to use for creating this symbolizer</param> public PointSymbolizer(ISymbol symbol) { Smoothing = true; Symbols = new CopyList<ISymbol> { symbol }; } /// <summary> /// Initializes a new instance of the <see cref="PointSymbolizer"/> class. /// </summary> /// <param name="presetSymbols">The symbols that are used.</param> public PointSymbolizer(IEnumerable<ISymbol> presetSymbols) { Smoothing = true; Symbols = new CopyList<ISymbol>(); foreach (ISymbol symbol in presetSymbols) { Symbols.Add(symbol); } } /// <summary> /// Initializes a new instance of the <see cref="PointSymbolizer"/> class with one member that constructed /// based on the values specified. /// </summary> /// <param name="color">The color of the symbol.</param> /// <param name="shape">The shape of the symbol.</param> /// <param name="size">The size of the symbol.</param> public PointSymbolizer(Color color, PointShape shape, double size) { Smoothing = true; Symbols = new CopyList<ISymbol>(); ISimpleSymbol ss = new SimpleSymbol(color, shape, size); Symbols.Add(ss); } /// <summary> /// Initializes a new instance of the <see cref="PointSymbolizer"/> class that has a member that is constructed /// from the specified image. /// </summary> /// <param name="image">The image to use as a point symbol</param> /// <param name="size">The desired output size of the larger dimension of the image.</param> public PointSymbolizer(Image image, double size) { Symbols = new CopyList<ISymbol>(); IPictureSymbol ps = new PictureSymbol(image); ps.Size = new Size2D(size, size); Symbols.Add(ps); } /// <summary> /// Initializes a new instance of the <see cref="PointSymbolizer"/> class that has a character symbol based on the specified characteristics. /// </summary> /// <param name="character">The character to draw</param> /// <param name="fontFamily">The font family to use for rendering the font</param> /// <param name="color">The font color</param> /// <param name="size">The size of the symbol</param> public PointSymbolizer(char character, string fontFamily, Color color, double size) { Symbols = new CopyList<ISymbol>(); CharacterSymbol cs = new CharacterSymbol(character, fontFamily, color, size); Symbols.Add(cs); } /// <summary> /// Initializes a new instance of the <see cref="PointSymbolizer"/> class. /// </summary> /// <param name="selected">Indicates whether to use the color for selected symbols.</param> public PointSymbolizer(bool selected) { Configure(); if (!selected) return; ISimpleSymbol ss = Symbols[0] as ISimpleSymbol; if (ss != null) { ss.Color = Color.Cyan; } } /// <summary> /// Initializes a new instance of the <see cref="PointSymbolizer"/> class. /// Sets the symbol type to geographic and generates a size that is 1/100 the width of the specified extents. /// </summary> /// <param name="selected">Indicates whether to use the color for selected symbols.</param> /// <param name="extents">Used for calculating the size of the symbol.</param> public PointSymbolizer(bool selected, IRectangle extents) { Configure(); ScaleMode = ScaleMode.Geographic; Smoothing = false; ISymbol s = Symbols[0]; if (s == null) return; s.Size.Width = extents.Width / 100; s.Size.Height = extents.Width / 100; ISimpleSymbol ss = Symbols[0] as ISimpleSymbol; if (ss != null && selected) ss.Color = Color.Cyan; } #endregion #region Properties /// <summary> /// Gets or sets the set of layered symbols. The symbol with the highest index is drawn on top. /// </summary> [Serialize("Symbols")] public IList<ISymbol> Symbols { get; set; } #endregion #region Methods /// <summary> /// Draws the specified value /// </summary> /// <param name="g">The Graphics object to draw to</param> /// <param name="target">The Rectangle defining the bounds to draw in</param> public override void Draw(Graphics g, Rectangle target) { Size2D size = GetSize(); double scaleH = target.Width / size.Width; double scaleV = target.Height / size.Height; double scale = Math.Min(scaleH, scaleV); Matrix old = g.Transform; Matrix shift = g.Transform; shift.Translate(target.X + (target.Width / 2), target.Y + (target.Height / 2)); g.Transform = shift; Draw(g, scale); g.Transform = old; } /// <summary> /// Draws the point symbol to the specified graphics object by cycling through each of the layers and /// drawing the content. This assumes that the graphics object has been translated to the specified point. /// </summary> /// <param name="g">Graphics object that is used for drawing.</param> /// <param name="scaleSize">Scale size represents the constant to multiply to the geographic measures in order to turn them into pixel coordinates </param> public void Draw(Graphics g, double scaleSize) { GraphicsState s = g.Save(); if (Smoothing) { g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.AntiAlias; } else { g.SmoothingMode = SmoothingMode.None; g.TextRenderingHint = TextRenderingHint.SystemDefault; } foreach (ISymbol symbol in Symbols) { symbol.Draw(g, scaleSize); } g.Restore(s); // Changed by jany_ (2015-07-06) remove smoothing because we might not want to smooth whatever is drawn with g afterwards } /// <summary> /// Returns the color of the top-most layer symbol. /// </summary> /// <returns>The fill color.</returns> public Color GetFillColor() { if (Symbols == null) return Color.Empty; if (Symbols.Count == 0) return Color.Empty; IColorable c = Symbols[Symbols.Count - 1] as IColorable; return c?.Color ?? Color.Empty; } /// <inheritdoc /> public override Size GetLegendSymbolSize() { Size2D sz = GetSize(); int w = (int)sz.Width; int h = (int)sz.Height; if (w < 1) w = 1; if (w > 128) w = 128; if (h < 1) h = 1; if (h > 128) h = 128; return new Size(w, h); } /// <summary> /// Returns the encapsulating size when considering all of the symbol layers that make up this symbolizer. /// </summary> /// <returns>A Size2D</returns> public Size2D GetSize() { return Symbols.GetBoundingSize(); } /// <summary> /// Multiplies all the linear measurements, like width, height, and offset values by the specified value. /// </summary> /// <param name="value">The double precision value to multiply all of the values against.</param> public void Scale(double value) { foreach (ISymbol symbol in Symbols) { symbol.Scale(value); } } /// <summary> /// Sets the color of the top-most layer symbol. /// </summary> /// <param name="color">The color to assign to the top-most layer.</param> public void SetFillColor(Color color) { if (Symbols == null) return; if (Symbols.Count == 0) return; Symbols[Symbols.Count - 1].SetColor(color); } /// <summary> /// Sets the outline, assuming that the symbolizer either supports outlines, or /// else by using a second symbol layer. /// </summary> /// <param name="outlineColor">The color of the outline</param> /// <param name="width">The width of the outline in pixels</param> public override void SetOutline(Color outlineColor, double width) { if (Symbols == null) return; if (Symbols.Count == 0) return; foreach (ISymbol symbol in Symbols) { IOutlinedSymbol oSymbol = symbol as IOutlinedSymbol; if (oSymbol == null) continue; oSymbol.OutlineColor = outlineColor; oSymbol.OutlineWidth = width; oSymbol.UseOutline = true; } base.SetOutline(outlineColor, width); } /// <summary> /// This assumes that you wish to simply scale the various sizes. /// It will adjust all of the sizes so that the maximum size is the same as the specified size. /// </summary> /// <param name="value">The Size2D of the new maximum size</param> public void SetSize(Size2D value) { Size2D oldSize = Symbols.GetBoundingSize(); double dX = value.Width / oldSize.Width; double dY = value.Height / oldSize.Height; foreach (ISymbol symbol in Symbols) { Size2D os = symbol.Size; symbol.Size = new Size2D(os.Width * dX, os.Height * dY); } } /// <summary> /// This controls randomly creating a single random symbol from the symbol types, and randomizing it. /// </summary> /// <param name="generator">The generator used to create the random symbol.</param> protected override void OnRandomize(Random generator) { SymbolType type = generator.NextEnum<SymbolType>(); Symbols.Clear(); switch (type) { case SymbolType.Custom: Symbols.Add(new SimpleSymbol()); break; case SymbolType.Character: Symbols.Add(new CharacterSymbol()); break; case SymbolType.Picture: Symbols.Add(new CharacterSymbol()); break; case SymbolType.Simple: Symbols.Add(new SimpleSymbol()); break; } // This part will actually randomize the sub-member base.OnRandomize(generator); } private void Configure() { Symbols = new CopyList<ISymbol>(); ISimpleSymbol ss = new SimpleSymbol(); ss.Color = SymbologyGlobal.RandomColor(); ss.Opacity = 1F; ss.PointShape = PointShape.Rectangle; Smoothing = true; ScaleMode = ScaleMode.Symbolic; Symbols.Add(ss); } #endregion } }
using System.ComponentModel; using System.Drawing.Design; using System.Web.UI.WebControls; using GuruComponents.Netrix.ComInterop; using GuruComponents.Netrix.UserInterface.TypeConverters; using GuruComponents.Netrix.UserInterface.TypeEditors; using DisplayNameAttribute = GuruComponents.Netrix.UserInterface.TypeEditors.DisplayNameAttribute; using TE = GuruComponents.Netrix.UserInterface.TypeEditors; namespace GuruComponents.Netrix.WebEditing.Elements { /// <summary> /// This class represents the &lt;img&gt; element. /// </summary> /// <remarks> /// <para> /// &lt;IMG ...&gt; puts an image on the web page. IMG requires two attributes: <see cref="src"/> and <see cref="alt"/>. <see cref="alt"/> is always required in &lt;IMG ...&gt; - /// don't make the common mistake of leaving it out. See the Rules of <see cref="alt"/> for more details. /// </para> /// Classes directly or indirectly inherited from /// <see cref="GuruComponents.Netrix.WebEditing.Elements.Element"/> are not intended to be instantiated /// directly by the host application. Use the various insertion or creation methods in the base classes /// instead. The return values are of type <see cref="GuruComponents.Netrix.WebEditing.Elements.IElement"/> /// and can be casted into the element just created. /// <para> /// Examples of how to create and modify elements with the native element classes can be found in the /// description of other element classes. /// </para> /// </remarks> public sealed class ImageElement : SelectableElement { /// <include file='DocumentorIncludes.xml' path='//WebEditing/Elements[@name="HorizontalAlign"]/*'/> [Category("Element Layout")] [DefaultValueAttribute(ImageAlign.NotSet)] [DescriptionAttribute("")] [TypeConverter(typeof(UITypeConverterDropList))] [DisplayNameAttribute()] public ImageAlign align { set { this.SetEnumAttribute("align", value, ImageAlign.NotSet); return; } get { return (ImageAlign)this.GetEnumAttribute("align", ImageAlign.NotSet); } } /// <summary> /// USEMAP indicates that the image is an image map and uses the map definition named by this attribute. /// </summary> /// <remarks> /// The name of the map is set by the NAME attribute of the MAP tag. Note that USEMAP requires that you /// precede the name of the map with a hash symbol (#). For example, the following code creates an /// image map named map1: /// <code> /// &lt;DIV ALIGN=CENTER&gt; /// &lt;MAP NAME="map1"&gt; /// &lt;AREA /// HREF="contacts.html" ALT="Contacts" TITLE="Contacts" /// SHAPE=RECT COORDS="6,116,97,184"&gt; /// &lt;AREA /// HREF="products.html" ALT="Products" TITLE="Products" /// SHAPE=CIRCLE COORDS="251,143,47"&gt; /// &lt;AREA /// HREF="new.html" ALT="New!" TITLE="New!" /// SHAPE=POLY COORDS="150,217, 190,257, 150,297,110,257"&gt; /// &lt;/MAP&gt; /// &lt;IMG SRC="testmap.gif" ALT="map of GH site" BORDER=0 WIDTH=300 HEIGHT=300 /// USEMAP="#map1"&gt;&lt;BR&gt; /// [ &lt;A HREF="contacts.html" ALT="Contacts"&gt;Contacts&lt;/A&gt; ] /// [ &lt;A HREF="products.html" ALT="Products"&gt;Products&lt;/A&gt; ] /// [ &lt;A HREF="new.html" ALT="New!"&gt;New!&lt;/A&gt; ] /// &lt;/DIV&gt; /// </code> /// </remarks> [CategoryAttribute("Element Behavior")] [DefaultValueAttribute(false)] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorString), typeof(UITypeEditor))] [DisplayName()] public string usemap { get { return this.GetStringAttribute("usemap"); } set { this.SetStringAttribute("usemap", value); return; } } /// <summary> /// Use as alt="text" attribute. /// </summary> /// <remarks> /// For user agents that cannot display images, forms, or applets, this /// attribute specifies alternate text. The language of the alternate text is specified by the lang attribute. /// </remarks> [CategoryAttribute("Element Layout")] [DefaultValueAttribute(false)] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorString), typeof(UITypeEditor))] [DisplayName()] public string alt { get { return this.GetStringAttribute("alt"); } set { this.SetStringAttribute("alt", value); return; } } /// <summary> /// BORDER is most useful for removing the visible border around images which are inside links. /// </summary> /// <remarks> /// By default images inside lunks have visible borders around them to indicate that they are links. However, user generally recognize these "link moments" and the border merely detracts from the appearance of the page. /// </remarks> [CategoryAttribute("Element Layout")] [DefaultValueAttribute(1)] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorInt), typeof(UITypeEditor))] [DisplayName()] public int border { get { return this.GetIntegerAttribute("border", 1); } set { this.SetIntegerAttribute("border", value, 1); return; } } /// <summary> /// WIDTH and HEIGHT tell the browser the dimensions of the image. /// </summary> /// <remarks> /// The browser can use this information to reserve space for the image as it contructs the page, even though the image has not downloaded yet. /// </remarks> [CategoryAttribute("Element Layout")] [DefaultValueAttribute(0)] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorInt), typeof(UITypeEditor))] [DisplayName()] public int height { set { this.SetIntegerAttribute("height", value, -1); return; } get { return this.GetIntegerAttribute("height", -1); } } /// <summary> /// HSPACE sets the horizontal space between the image and surrounding text. /// </summary> /// <remarks> /// HSPACE has the most pronounced effect when it is used in conjunction with <see cref="align"/> to right or left align the image. /// The space assigned by this attribute is added on both sides of the element. If a value of 5 is set the element grows vertically 10 pixels. /// <seealso cref="GuruComponents.Netrix.WebEditing.Elements.ImageElement.vSpace">vSpace</seealso> /// <seealso cref="GuruComponents.Netrix.WebEditing.Elements.ImageElement.align">align</seealso> /// </remarks> [CategoryAttribute("Element Layout")] [DefaultValueAttribute(0)] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorInt), typeof(UITypeEditor))] [DisplayName()] public int hSpace { get { return this.GetIntegerAttribute("hSpace", 0); } set { this.SetIntegerAttribute("hSpace", value, 0); return; } } /// <summary> /// Supports the JavaScript event 'doubleclick'. /// </summary> /// <remarks> /// The property should contain the name of a JavaScript mehtod or JavaScript executable code. /// </remarks> [CategoryAttribute("JavaScript Events")] [DefaultValueAttribute("")] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorString), typeof(UITypeEditor))] [DisplayName()] [ScriptingVisible()] public string ScriptOnDblClick { get { return this.GetStringAttribute("onDblClick"); } set { this.SetStringAttribute("onDblClick", value); return; } } /// <summary> /// Supports the JavaScript event 'mousedown'. /// </summary> /// <remarks> /// The property should contain the name of a JavaScript mehtod or JavaScript executable code. /// </remarks> [CategoryAttribute("JavaScript Events")] [DefaultValueAttribute("")] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorString), typeof(UITypeEditor))] [DisplayName()] [ScriptingVisible()] public string ScriptOnMouseDown { set { this.SetStringAttribute("onMouseDown", value); return; } get { return this.GetStringAttribute("onMouseDown"); } } /// <summary> /// Supports the JavaScript event 'mouseup'. /// </summary> /// <remarks> /// The property should contain the name of a JavaScript mehtod or JavaScript executable code. /// </remarks> [CategoryAttribute("JavaScript Events")] [DefaultValueAttribute("")] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorString), typeof(UITypeEditor))] [DisplayName()] [ScriptingVisible()] public string ScriptOnMouseUp { get { return this.GetStringAttribute("onMouseUp"); } set { this.SetStringAttribute("onMouseUp", value); return; } } /// <summary> /// SRC tells where to get the picture that should be put on the page. /// </summary> /// <remarks> /// SRC is the one required attribute. It is recommended to use relative paths. If a filename is given the property will recognize and set /// the relative path automatically. /// <para> /// Note: To bypass the automatic truncation of paths you can use the base class' SetAttribute method, which provides a raw access to /// all supported attributes like <c>img.SetAttribute("src", "file:///c:\mypath\myimage.png");</c>. Further access to <c>src></c> property will /// still truncate the value, but only for the caller. It will not change the content until you set the value explicitly through this property. /// </para> /// </remarks> [CategoryAttribute("Element Layout")] [DefaultValueAttribute("")] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorUrl), typeof(UITypeEditor))] [DisplayName()] public string src { set { this.SetStringAttribute("src", this.GetRelativeUrl(value)); return; } get { return this.GetRelativeUrl(this.GetStringAttribute("src")); } } /// <summary> /// VSPACE sets the vertical space between the image and surrounding text. /// <seealso cref="GuruComponents.Netrix.WebEditing.Elements.ImageElement.hSpace">hSpace</seealso> /// <seealso cref="GuruComponents.Netrix.WebEditing.Elements.ImageElement.align">align</seealso> /// </summary> /// <remarks> /// The space assigned by this attribute is added on both sides of the element. If a value of 5 is set the element grows vertically 10 pixels. /// <para> /// Set the value to 0 (zero) to remove the attribute. 0 (zero) is the default value. /// </para> /// </remarks> [CategoryAttribute("Element Layout")] [DefaultValueAttribute(0)] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorInt), typeof(UITypeEditor))] [DisplayName()] public int vSpace { set { this.SetIntegerAttribute("vSpace", value, 0); return; } get { return this.GetIntegerAttribute("vSpace", 0); } } /// <summary> /// WIDTH and HEIGHT tell the browser the dimensions of the image. /// </summary> /// <remarks> /// The browser can use this information to reserve space for the image as it contructs the page, even though the image has not downloaded yet. /// <para> /// Set the value to -1 to remove the attribute. The default value for the UI defaults to 30. This is simple for user support. Removing the attribute /// will not set the value to 30 nor the element will inherit that behavior. /// </para> /// </remarks> [CategoryAttribute("Element Layout")] [DefaultValueAttribute(0)] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorInt), typeof(UITypeEditor))] [DisplayName()] public int width { set { this.SetIntegerAttribute("width", value, -1); } get { return this.GetIntegerAttribute("width", -1); } } /// <summary> /// Creates the specified element. /// </summary> /// <remarks> /// The element is being created and attached to the current document, but nevertheless not visible, /// until it's being placed anywhere within the DOM. To attach an element it's possible to either /// use the <see cref="ElementDom"/> property of any other already placed element and refer to this /// DOM or use the body element (<see cref="HtmlEditor.GetBodyElement"/>) and add the element there. Also, in /// case of user interactive solutions, it's possible to add an element near the current caret /// position, using <see cref="HtmlEditor.CreateElementAtCaret(string)"/> method. /// <para> /// Note: Invisible elements do neither appear in the DOM nor do they get saved. /// </para> /// </remarks> /// <param name="editor">The editor this element belongs to.</param> public ImageElement(IHtmlEditor editor) : base("img", editor) { } internal ImageElement(Interop.IHTMLElement peer, IHtmlEditor editor) : base(peer, editor) { } } }
using UnityEngine; using UnityEditor; using System; using System.Reflection; // Source: // https://gist.github.com/cofruben/26882cf1a800c93eb24c7cbe15cbb7fa // and // https://gist.github.com/drawcode/4596778 // See also decompiled code of the AssetStoreWindow: // https://github.com/MattRix/UnityDecompiled/blob/master/UnityEditor/UnityEditor/AssetStoreWindow.cs /// <summary> /// Web editor window. /// </summary> public class WebEditorWindow : EditorWindow, IHasCustomMenu{ // The webview internal UnityEngine.Object m_WebView; // Error Handling int initErrorLevel = 0; bool errorLogged = false; // See AssetStoreWindow private bool m_IsDocked; private bool m_SyncingFocus; private WebEditorContext m_ContextScriptObject; // Things looked up by reflection private Type webViewType; private Type guiClipType; private MethodInfo setSizeAndPositionMethod; private MethodInfo loadURLMethod; private MethodInfo dockedGetterMethod; private MethodInfo unclipMethod; /// <summary> /// The url on which Vubbi is hosted! /// </summary> string urlText = "http://localhost:48719"; /// <summary> /// Opens a file in the editor. /// </summary> /// <param name="file">File.</param> public static void OpenFile(string file) { WebEditorWindow window = (WebEditorWindow)WebEditorWindow.GetWindow(typeof(WebEditorWindow)); window.OpenFileByHash (file); window.Init(); window.CreateContextObject(); window.Show (); window.titleContent = new GUIContent("Vubbi Code Editor");window.Focus (); } public WebEditorWindow() { position = new Rect(100,100,800,600); } /** * Called whenever an issue occurs with loading (or reflection) */ private void ShowCouldNotLoadError(string actualCause, Type logMethodsType) { if (errorLogged) { return; } initErrorLevel++; Debug.LogError ("Error Initializing Vubbi Code Editor Window. "+actualCause); if (logMethodsType != null) { DebugLogMethods (logMethodsType); } Close ();errorLogged = true; } // Init the window void Init() { initErrorLevel = 1; errorLogged = false; //Get docked property getter MethodInfo dockedGetterMethod = typeof(EditorWindow).GetProperty("docked", fullBinding).GetGetMethod(true); if (dockedGetterMethod == null) { ShowCouldNotLoadError ("Could not find \"docked\" getter in EditorWindow.", typeof(EditorWindow)); initErrorLevel++; } initErrorLevel--; } public virtual void AddItemsToMenu(GenericMenu menu) { menu.AddItem(new GUIContent("Reload"), false, new GenericMenu.MenuFunction(this.Reload)); } public void Reload() { this.m_IsDocked = BaseDocked; ReflWebViewType.GetMethod ("Reload").Invoke (m_WebView, new object[]{}); } public void OnLoadError(string url) { if (this.m_WebView != null) { return; } // Loading page failed... } public void OnInitScripting() { this.SetContextObject(); } public void OnOpenExternalLink(string url) { Debug.Log ("Uh?"); /*if (url.StartsWith("http://") || url.StartsWith("https://")) { this.m_ContextScriptObject.OpenBrowser(url); }*/ } private string fileToOpen = null; public void OpenFileByHash(string file) { fileToOpen = file; Repaint (); // Make sure OnGUI is triggered } void OnGUI() { if(unclipMethod==null) { guiClipType = GetTypeFromAllAssemblies ("GUIClip"); if (guiClipType == null) { ShowCouldNotLoadError ("Could not find GUIClip.", null); initErrorLevel++; return; } unclipMethod = guiClipType.GetMethod ("Unclip", new Type[]{typeof(Rect)}); } Rect webViewRect = (Rect)unclipMethod.Invoke(null, new object[]{new Rect(0f, 0f, base.position.width, base.position.height)}); if (this.m_WebView == null) { this.InitWebView(webViewRect); } // fileToOpen is not null => we need to browse to the new file! if (fileToOpen != null) { UpdateUrl (); } if (Event.current.type == EventType.Layout) { if (setSizeAndPositionMethod == null) { setSizeAndPositionMethod = ReflWebViewType.GetMethod ("SetSizeAndPosition"); if (setSizeAndPositionMethod == null) { ShowCouldNotLoadError ("Cannot find all required methods... Found:", ReflWebViewType); return; } } setSizeAndPositionMethod.Invoke(m_WebView, new object[] {(int)webViewRect.x, (int)webViewRect.y, (int)webViewRect.width,(int)webViewRect.height}); this.UpdateDockStatusIfNeeded(); } } public void UpdateDockStatusIfNeeded() { if (this.m_IsDocked != BaseDocked) { this.m_IsDocked = BaseDocked; if (this.m_ContextScriptObject != null) { this.m_ContextScriptObject.docked = BaseDocked; //this.InvokeJSMethod("document.AssetStore", "updateDockStatus", new object[0]); } } } public void OnFocus() { this.SetFocus(true); } public void OnLostFocus() { this.SetFocus(false); } public void OnBecameInvisible() { if (this.m_WebView==null) { return; } WebViewSetHostView(null); } public void OnDestroy() { UnityEngine.Object.DestroyImmediate(this.m_WebView); if (this.m_ContextScriptObject != null) { UnityEngine.Object.DestroyImmediate(this.m_ContextScriptObject); } } private void InitWebView(Rect pos) { this.m_IsDocked = BaseDocked; if (this.m_WebView == null) { var thisWindowGuiView = BaseMParent; if (thisWindowGuiView == null) { ShowCouldNotLoadError ("m_Parent property does not exit", typeof(EditorWindow)); return; } m_WebView = ScriptableObject.CreateInstance (ReflWebViewType); ReflWebViewType.GetMethod ("InitWebView").Invoke (m_WebView, new object[] { thisWindowGuiView, (int)pos.x, (int)pos.y, (int)pos.width, (int)pos.height, true }); // Set hide flags ReflWebViewType.GetProperty("hideFlags").SetValue(m_WebView, HideFlags.HideAndDontSave, null); if (BaseHasFocus) { this.SetFocus (true); } ReflWebViewType.GetMethod ("SetDelegateObject").Invoke (m_WebView, new object[] { this }); UpdateUrl (); this.wantsMouseMove = true; } } private void UpdateUrl() { loadURLMethod = ReflWebViewType.GetMethod ("LoadURL"); loadURLMethod.Invoke (m_WebView, new object[] { urlText + (fileToOpen!=null?"#"+fileToOpen:"") }); fileToOpen = null; } private void CreateContextObject() { if (this.m_ContextScriptObject != null) { return; } this.m_ContextScriptObject = ScriptableObject.CreateInstance<WebEditorContext>(); this.m_ContextScriptObject.hideFlags = HideFlags.HideAndDontSave; this.m_ContextScriptObject.window = this; } private void SetContextObject() { this.CreateContextObject(); this.m_ContextScriptObject.docked = BaseDocked; //this.m_WebView.DefineScriptObject("window.context", this.m_ContextScriptObject); } private void SetFocus(bool value) { if (this.m_SyncingFocus) { return; } this.m_SyncingFocus = true; if (this.m_WebView) { if (value) { WebViewSetHostView(BaseMParent); WebViewShow(); } WebViewSetFocus(value); } this.m_SyncingFocus = false; } // // // // Private items from the window... // // // public Type ReflWebViewType { get { if (webViewType == null) { //Get WebView type webViewType = GetTypeFromAllAssemblies("WebView"); if (webViewType == null) { ShowCouldNotLoadError ("Could not find WebView.", null); return null; } } return webViewType; } } public bool BaseDocked { get {return (bool)typeof(EditorWindow).GetProperty("docked", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this, null);} } public bool BaseHasFocus { get {return (bool)typeof(EditorWindow).GetProperty("hasFocus", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this, null);} } public object BaseMParent { get { return typeof(EditorWindow).GetField ("m_Parent", BindingFlags.Instance | BindingFlags.NonPublic).GetValue (this); } } public void WebViewSetHostView(object view){ ReflWebViewType.GetMethod ("SetHostView").Invoke (this.m_WebView, new object[]{ view }); } public void WebViewShow(){ ReflWebViewType.GetMethod ("Show").Invoke (this.m_WebView, new object[]{ }); } public void WebViewSetFocus(bool focus){ ReflWebViewType.GetMethod ("SetFocus").Invoke (this.m_WebView, new object[]{ focus }); } // // // // Tools for doing Reflection... // // // static BindingFlags fullBinding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; static StringComparison ignoreCase = StringComparison.CurrentCultureIgnoreCase; public static Type GetTypeFromAllAssemblies(string typeName) { Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); foreach(Assembly assembly in assemblies) { Type[] types = assembly.GetTypes(); foreach(Type type in types) { if(type.Name.Equals(typeName, ignoreCase) || type.Name.Contains('+' + typeName)) //+ check for inline classes return type; } } return null; } void DebugLogMethods(Type t) { MethodInfo[] methods = t.GetMethods (fullBinding); string totalMsg = ""; foreach (MethodInfo met in methods) { ParameterInfo[] param = met.GetParameters (); string pStr = ""; foreach(ParameterInfo p in param) { if (pStr.Length > 0) { pStr += ", "; } pStr += p.ParameterType.FullName; } if (totalMsg.Length > 0) { totalMsg += "\n"; } totalMsg += " - " + met.Name + " (" + pStr + ")"; } PropertyInfo[] properties = t.GetProperties (fullBinding); foreach (PropertyInfo prop in properties) { totalMsg += " - " + prop.Name+":"+prop.DeclaringType; } FieldInfo[] fields = t.GetFields (fullBinding); foreach (FieldInfo field in fields) { totalMsg += "\n - " + field.Name+":"+field.DeclaringType; } Debug.Log (totalMsg); } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Security.Policy; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Prism.Modularity; namespace Prism.Wpf.Tests.Modularity { [TestClass] public class DirectoryModuleCatalogFixture { private const string ModulesDirectory1 = @".\DynamicModules\MocksModules1"; private const string ModulesDirectory2 = @".\DynamicModules\AttributedModules"; private const string ModulesDirectory3 = @".\DynamicModules\DependantModules"; private const string ModulesDirectory4 = @".\DynamicModules\MocksModules2"; private const string ModulesDirectory5 = @".\DynamicModules\ModulesMainDomain\"; private const string InvalidModulesDirectory = @".\Modularity"; public DirectoryModuleCatalogFixture() { } [TestInitialize] [TestCleanup] public void CleanUpDirectories() { CompilerHelper.CleanUpDirectory(ModulesDirectory1); CompilerHelper.CleanUpDirectory(ModulesDirectory2); CompilerHelper.CleanUpDirectory(ModulesDirectory3); CompilerHelper.CleanUpDirectory(ModulesDirectory4); CompilerHelper.CleanUpDirectory(ModulesDirectory5); CompilerHelper.CleanUpDirectory(InvalidModulesDirectory); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void NullPathThrows() { DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.Load(); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void EmptyPathThrows() { DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.Load(); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void NonExistentPathThrows() { DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = "NonExistentPath"; catalog.Load(); } [TestMethod] public void ShouldReturnAListOfModuleInfo() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory1 + @"\MockModuleA.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory1; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.IsNotNull(modules); Assert.AreEqual(1, modules.Length); Assert.IsNotNull(modules[0].Ref); StringAssert.StartsWith(modules[0].Ref, "file://"); Assert.IsTrue(modules[0].Ref.Contains(@"MockModuleA.dll")); Assert.IsNotNull(modules[0].ModuleType); StringAssert.Contains(modules[0].ModuleType, "Prism.Wpf.Tests.Mocks.Modules.MockModuleA"); } [TestMethod] [DeploymentItem(@"Modularity\NotAValidDotNetDll.txt.dll", @".\Modularity")] public void ShouldNotThrowWithNonValidDotNetAssembly() { DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = InvalidModulesDirectory; try { catalog.Load(); } catch (Exception) { Assert.Fail("Should not have thrown."); } ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.IsNotNull(modules); Assert.AreEqual(0, modules.Length); } [TestMethod] [DeploymentItem(@"Modularity\NotAValidDotNetDll.txt.dll", InvalidModulesDirectory)] public void LoadsValidAssembliesWhenInvalidDllsArePresent() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", InvalidModulesDirectory + @"\MockModuleA.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = InvalidModulesDirectory; try { catalog.Load(); } catch (Exception) { Assert.Fail("Should not have thrown."); } ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.IsNotNull(modules); Assert.AreEqual(1, modules.Length); Assert.IsNotNull(modules[0].Ref); StringAssert.StartsWith(modules[0].Ref, "file://"); Assert.IsTrue(modules[0].Ref.Contains(@"MockModuleA.dll")); Assert.IsNotNull(modules[0].ModuleType); StringAssert.Contains(modules[0].ModuleType, "Prism.Wpf.Tests.Mocks.Modules.MockModuleA"); } [TestMethod] public void ShouldNotThrowWithLoadFromByteAssemblies() { CompilerHelper.CleanUpDirectory(@".\CompileOutput\"); CompilerHelper.CleanUpDirectory(@".\IgnoreLoadFromByteAssembliesTestDir\"); var results = CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", @".\CompileOutput\MockModuleA.dll"); CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule.cs", @".\IgnoreLoadFromByteAssembliesTestDir\MockAttributedModule.dll"); string path = @".\IgnoreLoadFromByteAssembliesTestDir"; AppDomain testDomain = null; try { testDomain = CreateAppDomain(); RemoteDirectoryLookupCatalog remoteEnum = CreateRemoteDirectoryModuleCatalogInAppDomain(testDomain); remoteEnum.LoadDynamicEmittedModule(); remoteEnum.LoadAssembliesByByte(@".\CompileOutput\MockModuleA.dll"); ModuleInfo[] infos = remoteEnum.DoEnumeration(path); Assert.IsNotNull( infos.FirstOrDefault(x => x.ModuleType.IndexOf("Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule") >= 0) ); } finally { if (testDomain != null) AppDomain.Unload(testDomain); } } [TestMethod] public void ShouldGetModuleNameFromAttribute() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule.cs", ModulesDirectory2 + @"\MockAttributedModule.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory2; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(1, modules.Length); Assert.AreEqual("TestModule", modules[0].ModuleName); } [TestMethod] public void ShouldGetDependantModulesFromAttribute() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockDependencyModule.cs", ModulesDirectory3 + @"\DependencyModule.dll"); CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockDependantModule.cs", ModulesDirectory3 + @"\DependantModule.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory3; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(2, modules.Length); var dependantModule = modules.First(module => module.ModuleName == "DependantModule"); var dependencyModule = modules.First(module => module.ModuleName == "DependencyModule"); Assert.IsNotNull(dependantModule); Assert.IsNotNull(dependencyModule); Assert.IsNotNull(dependantModule.DependsOn); Assert.AreEqual(1, dependantModule.DependsOn.Count); Assert.AreEqual(dependencyModule.ModuleName, dependantModule.DependsOn[0]); } [TestMethod] public void UseClassNameAsModuleNameWhenNotSpecifiedInAttribute() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory1 + @"\MockModuleA.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory1; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.IsNotNull(modules); Assert.AreEqual("MockModuleA", modules[0].ModuleName); } [TestMethod] public void ShouldDefaultInitializationModeToWhenAvailable() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory1 + @"\MockModuleA.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory1; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.IsNotNull(modules); Assert.AreEqual(InitializationMode.WhenAvailable, modules[0].InitializationMode); } [TestMethod] public void ShouldGetOnDemandFromAttribute() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule.cs", ModulesDirectory3 + @"\MockAttributedModule.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory3; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(1, modules.Length); Assert.AreEqual(InitializationMode.OnDemand, modules[0].InitializationMode); } [TestMethod] public void ShouldNotLoadAssembliesInCurrentAppDomain() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory4 + @"\MockModuleA.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory4; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); // filtering out dynamic assemblies due to using a dynamic mocking framework. Assembly loadedAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(assembly => !assembly.IsDynamic) .Where(assembly => assembly.Location.Equals(modules[0].Ref, StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault(); Assert.IsNull(loadedAssembly); } [TestMethod] public void ShouldNotGetModuleInfoForAnAssemblyAlreadyLoadedInTheMainDomain() { var assemblyPath = Assembly.GetCallingAssembly().Location; DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory5; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(0, modules.Length); } [TestMethod] public void ShouldLoadAssemblyEvenIfTheyAreReferencingEachOther() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory4 + @"\MockModuleZZZ.dll"); CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleReferencingOtherModule.cs", ModulesDirectory4 + @"\MockModuleReferencingOtherModule.dll", ModulesDirectory4 + @"\MockModuleZZZ.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory4; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(2, modules.Count()); } //Disabled Warning // 'System.Security.Policy.Evidence.Count' is obsolete: ' // "Evidence should not be treated as an ICollection. Please use GetHostEnumerator and GetAssemblyEnumerator to // iterate over the evidence to collect a count."' #pragma warning disable 0618 [TestMethod] public void CreateChildAppDomainHasParentEvidenceAndSetup() { TestableDirectoryModuleCatalog catalog = new TestableDirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory4; catalog.Load(); Evidence parentEvidence = new Evidence(); AppDomainSetup parentSetup = new AppDomainSetup(); parentSetup.ApplicationName = "Test Parent"; AppDomain parentAppDomain = AppDomain.CreateDomain("Parent", parentEvidence, parentSetup); AppDomain childDomain = catalog.BuildChildDomain(parentAppDomain); Assert.AreEqual(parentEvidence.Count, childDomain.Evidence.Count); Assert.AreEqual("Test Parent", childDomain.SetupInformation.ApplicationName); Assert.AreNotEqual(AppDomain.CurrentDomain.Evidence.Count, childDomain.Evidence.Count); Assert.AreNotEqual(AppDomain.CurrentDomain.SetupInformation.ApplicationName, childDomain.SetupInformation.ApplicationName); } #pragma warning restore 0618 [TestMethod] public void ShouldLoadFilesEvenIfDynamicAssemblyExists() { CompilerHelper.CleanUpDirectory(@".\CompileOutput\"); CompilerHelper.CleanUpDirectory(@".\IgnoreDynamicGeneratedFilesTestDir\"); CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule.cs", @".\IgnoreDynamicGeneratedFilesTestDir\MockAttributedModule.dll"); string path = @".\IgnoreDynamicGeneratedFilesTestDir"; AppDomain testDomain = null; try { testDomain = CreateAppDomain(); RemoteDirectoryLookupCatalog remoteEnum = CreateRemoteDirectoryModuleCatalogInAppDomain(testDomain); remoteEnum.LoadDynamicEmittedModule(); ModuleInfo[] infos = remoteEnum.DoEnumeration(path); Assert.IsNotNull( infos.FirstOrDefault(x => x.ModuleType.IndexOf("Prism.Wpf.Tests.Mocks.Modules.MockAttributedModule") >= 0) ); } finally { if (testDomain != null) AppDomain.Unload(testDomain); } } [TestMethod] public void ShouldLoadAssemblyEvenIfIsExposingTypesFromAnAssemblyInTheGac() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockExposingTypeFromGacAssemblyModule.cs", ModulesDirectory4 + @"\MockExposingTypeFromGacAssemblyModule.dll", @"System.Transactions.dll"); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory4; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(1, modules.Count()); } [TestMethod] public void ShouldNotFailWhenAlreadyLoadedAssembliesAreAlsoFoundOnTargetDirectory() { CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockModuleA.cs", ModulesDirectory1 + @"\MockModuleA.dll"); string filename = typeof(DirectoryModuleCatalog).Assembly.Location; string destinationFileName = Path.Combine(ModulesDirectory1, Path.GetFileName(filename)); File.Copy(filename, destinationFileName); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory1; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(1, modules.Length); } [TestMethod] public void ShouldIgnoreAbstractClassesThatImplementIModule() { CompilerHelper.CleanUpDirectory(ModulesDirectory1); CompilerHelper.CompileFile(@"Prism.Wpf.Tests.Mocks.Modules.MockAbstractModule.cs", ModulesDirectory1 + @"\MockAbstractModule.dll"); string filename = typeof(DirectoryModuleCatalog).Assembly.Location; string destinationFileName = Path.Combine(ModulesDirectory1, Path.GetFileName(filename)); File.Copy(filename, destinationFileName); DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = ModulesDirectory1; catalog.Load(); ModuleInfo[] modules = catalog.Modules.ToArray(); Assert.AreEqual(1, modules.Length); Assert.AreEqual("MockInheritingModule", modules[0].ModuleName); CompilerHelper.CleanUpDirectory(ModulesDirectory1); } private AppDomain CreateAppDomain() { Evidence evidence = AppDomain.CurrentDomain.Evidence; AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; return AppDomain.CreateDomain("TestDomain", evidence, setup); } private RemoteDirectoryLookupCatalog CreateRemoteDirectoryModuleCatalogInAppDomain(AppDomain testDomain) { RemoteDirectoryLookupCatalog remoteEnum; Type remoteEnumType = typeof(RemoteDirectoryLookupCatalog); remoteEnum = (RemoteDirectoryLookupCatalog)testDomain.CreateInstanceFrom( remoteEnumType.Assembly.Location, remoteEnumType.FullName).Unwrap(); return remoteEnum; } private class TestableDirectoryModuleCatalog : DirectoryModuleCatalog { public new AppDomain BuildChildDomain(AppDomain currentDomain) { return base.BuildChildDomain(currentDomain); } } private class RemoteDirectoryLookupCatalog : MarshalByRefObject { public void LoadAssembliesByByte(string assemblyPath) { byte[] assemblyBytes = File.ReadAllBytes(assemblyPath); AppDomain.CurrentDomain.Load(assemblyBytes); } public ModuleInfo[] DoEnumeration(string path) { DirectoryModuleCatalog catalog = new DirectoryModuleCatalog(); catalog.ModulePath = path; catalog.Load(); return catalog.Modules.ToArray(); } public void LoadDynamicEmittedModule() { // create a dynamic assembly and module AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "DynamicBuiltAssembly"; AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); ModuleBuilder module = assemblyBuilder.DefineDynamicModule("DynamicBuiltAssembly.dll"); // create a new type TypeBuilder typeBuilder = module.DefineType("DynamicBuiltType", TypeAttributes.Public | TypeAttributes.Class); // Create the type Type helloWorldType = typeBuilder.CreateType(); } } } }
using J2N.Collections.Generic.Extensions; using System; using System.Collections.Generic; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Base class for implementing <see cref="CompositeReader"/>s based on an array /// of sub-readers. The implementing class has to add code for /// correctly refcounting and closing the sub-readers. /// /// <para/>User code will most likely use <see cref="MultiReader"/> to build a /// composite reader on a set of sub-readers (like several /// <see cref="DirectoryReader"/>s). /// /// <para/> For efficiency, in this API documents are often referred to via /// <i>document numbers</i>, non-negative integers which each name a unique /// document in the index. These document numbers are ephemeral -- they may change /// as documents are added to and deleted from an index. Clients should thus not /// rely on a given document having the same number between sessions. /// /// <para/><b>NOTE</b>: /// <see cref="IndexReader"/> instances are completely thread /// safe, meaning multiple threads can call any of its methods, /// concurrently. If your application requires external /// synchronization, you should <b>not</b> synchronize on the /// <see cref="IndexReader"/> instance; use your own /// (non-Lucene) objects instead. /// <para/> /// @lucene.internal /// </summary> /// <seealso cref="MultiReader"/> public abstract class BaseCompositeReader<R> : CompositeReader where R : IndexReader { private readonly R[] subReaders; private readonly int[] starts; // 1st docno for each reader private readonly int maxDoc; private readonly int numDocs; /// <summary> /// List view solely for <see cref="GetSequentialSubReaders()"/>, /// for effectiveness the array is used internally. /// </summary> private readonly IList<IndexReader> subReadersList; // LUCENENET: Changed from IList<R> to IList<IndexReader> to eliminate casting /// <summary> /// Constructs a <see cref="BaseCompositeReader{R}"/> on the given <paramref name="subReaders"/>. </summary> /// <param name="subReaders"> the wrapped sub-readers. This array is returned by /// <see cref="GetSequentialSubReaders()"/> and used to resolve the correct /// subreader for docID-based methods. <b>Please note:</b> this array is <b>not</b> /// cloned and not protected for modification, the subclass is responsible /// to do this. </param> protected BaseCompositeReader(R[] subReaders) { this.subReaders = subReaders; // LUCENENET: To eliminate casting, we create the list explicitly var subReadersList = new JCG.List<IndexReader>(subReaders.Length); for (int i = 0; i < subReaders.Length; i++) subReadersList.Add(subReaders[i]); this.subReadersList = subReadersList.AsReadOnly(); starts = new int[subReaders.Length + 1]; // build starts array int maxDoc = 0, numDocs = 0; for (int i = 0; i < subReaders.Length; i++) { starts[i] = maxDoc; IndexReader r = subReaders[i]; maxDoc += r.MaxDoc; // compute maxDocs if (maxDoc < 0) // overflow { throw new ArgumentException("Too many documents, composite IndexReaders cannot exceed " + int.MaxValue); } numDocs += r.NumDocs; // compute numDocs r.RegisterParentReader(this); } starts[subReaders.Length] = maxDoc; this.maxDoc = maxDoc; this.numDocs = numDocs; } public override sealed Fields GetTermVectors(int docID) { EnsureOpen(); int i = ReaderIndex(docID); // find subreader num return subReaders[i].GetTermVectors(docID - starts[i]); // dispatch to subreader } public override sealed int NumDocs => // Don't call ensureOpen() here (it could affect performance) numDocs; public override sealed int MaxDoc => // Don't call ensureOpen() here (it could affect performance) maxDoc; public override sealed void Document(int docID, StoredFieldVisitor visitor) { EnsureOpen(); int i = ReaderIndex(docID); // find subreader num subReaders[i].Document(docID - starts[i], visitor); // dispatch to subreader } public override sealed int DocFreq(Term term) { EnsureOpen(); int total = 0; // sum freqs in subreaders for (int i = 0; i < subReaders.Length; i++) { total += subReaders[i].DocFreq(term); } return total; } public override sealed long TotalTermFreq(Term term) { EnsureOpen(); long total = 0; // sum freqs in subreaders for (int i = 0; i < subReaders.Length; i++) { long sub = subReaders[i].TotalTermFreq(term); if (sub == -1) { return -1; } total += sub; } return total; } public override sealed long GetSumDocFreq(string field) { EnsureOpen(); long total = 0; // sum doc freqs in subreaders foreach (R reader in subReaders) { long sub = reader.GetSumDocFreq(field); if (sub == -1) { return -1; // if any of the subs doesn't support it, return -1 } total += sub; } return total; } public override sealed int GetDocCount(string field) { EnsureOpen(); int total = 0; // sum doc counts in subreaders foreach (R reader in subReaders) { int sub = reader.GetDocCount(field); if (sub == -1) { return -1; // if any of the subs doesn't support it, return -1 } total += sub; } return total; } public override sealed long GetSumTotalTermFreq(string field) { EnsureOpen(); long total = 0; // sum doc total term freqs in subreaders foreach (R reader in subReaders) { long sub = reader.GetSumTotalTermFreq(field); if (sub == -1) { return -1; // if any of the subs doesn't support it, return -1 } total += sub; } return total; } /// <summary> /// Helper method for subclasses to get the corresponding reader for a doc ID </summary> protected internal int ReaderIndex(int docID) { if (docID < 0 || docID >= maxDoc) { throw new ArgumentException("docID must be >= 0 and < maxDoc=" + maxDoc + " (got docID=" + docID + ")"); } return ReaderUtil.SubIndex(docID, this.starts); } /// <summary> /// Helper method for subclasses to get the docBase of the given sub-reader index. </summary> protected internal int ReaderBase(int readerIndex) { if (readerIndex < 0 || readerIndex >= subReaders.Length) { throw new ArgumentException("readerIndex must be >= 0 and < getSequentialSubReaders().size()"); } return this.starts[readerIndex]; } protected internal override sealed IList<IndexReader> GetSequentialSubReaders() { return subReadersList; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Lucene.Net.Codecs.Lucene42 { using BlockPackedWriter = Lucene.Net.Util.Packed.BlockPackedWriter; using BytesRef = Lucene.Net.Util.BytesRef; /* * 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 FieldInfo = Lucene.Net.Index.FieldInfo; using FormatAndBits = Lucene.Net.Util.Packed.PackedInts.FormatAndBits; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexOutput = Lucene.Net.Store.IndexOutput; using IOUtils = Lucene.Net.Util.IOUtils; using MathUtil = Lucene.Net.Util.MathUtil; using PackedInts = Lucene.Net.Util.Packed.PackedInts; using SegmentWriteState = Lucene.Net.Index.SegmentWriteState; /// <summary> /// Writer for <seealso cref="Lucene42NormsFormat"/> /// </summary> internal class Lucene42NormsConsumer : DocValuesConsumer { internal const sbyte NUMBER = 0; internal const int BLOCK_SIZE = 4096; internal const sbyte DELTA_COMPRESSED = 0; internal const sbyte TABLE_COMPRESSED = 1; internal const sbyte UNCOMPRESSED = 2; internal const sbyte GCD_COMPRESSED = 3; internal IndexOutput Data, Meta; internal readonly int MaxDoc; internal readonly float AcceptableOverheadRatio; internal Lucene42NormsConsumer(SegmentWriteState state, string dataCodec, string dataExtension, string metaCodec, string metaExtension, float acceptableOverheadRatio) { this.AcceptableOverheadRatio = acceptableOverheadRatio; MaxDoc = state.SegmentInfo.DocCount; bool success = false; try { string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, dataExtension); Data = state.Directory.CreateOutput(dataName, state.Context); CodecUtil.WriteHeader(Data, dataCodec, Lucene42DocValuesProducer.VERSION_CURRENT); string metaName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, metaExtension); Meta = state.Directory.CreateOutput(metaName, state.Context); CodecUtil.WriteHeader(Meta, metaCodec, Lucene42DocValuesProducer.VERSION_CURRENT); success = true; } finally { if (!success) { IOUtils.CloseWhileHandlingException(this); } } } public override void AddNumericField(FieldInfo field, IEnumerable<long?> values) { Meta.WriteVInt(field.Number); Meta.WriteByte((byte)NUMBER); Meta.WriteLong(Data.FilePointer); long minValue = long.MaxValue; long maxValue = long.MinValue; long gcd = 0; // TODO: more efficient? HashSet<long> uniqueValues = null; if (true) { uniqueValues = new HashSet<long>(); long count = 0; foreach (long? nv in values) { Debug.Assert(nv != null); long v = nv.Value; if (gcd != 1) { if (v < long.MinValue / 2 || v > long.MaxValue / 2) { // in that case v - minValue might overflow and make the GCD computation return // wrong results. Since these extreme values are unlikely, we just discard // GCD computation for them gcd = 1; } // minValue needs to be set first else if (count != 0) { gcd = MathUtil.Gcd(gcd, v - minValue); } } minValue = Math.Min(minValue, v); maxValue = Math.Max(maxValue, v); if (uniqueValues != null) { if (uniqueValues.Add(v)) { if (uniqueValues.Count > 256) { uniqueValues = null; } } } ++count; } Debug.Assert(count == MaxDoc); } if (uniqueValues != null) { // small number of unique values int bitsPerValue = PackedInts.BitsRequired(uniqueValues.Count - 1); FormatAndBits formatAndBits = PackedInts.FastestFormatAndBits(MaxDoc, bitsPerValue, AcceptableOverheadRatio); if (formatAndBits.bitsPerValue == 8 && minValue >= sbyte.MinValue && maxValue <= sbyte.MaxValue) { Meta.WriteByte((byte)UNCOMPRESSED); // uncompressed foreach (long? nv in values) { Data.WriteByte(nv == null ? (byte)0 : (byte)(sbyte)nv.Value); } } else { Meta.WriteByte((byte)TABLE_COMPRESSED); // table-compressed //LUCENE TO-DO, ToArray had a parameter to start var decode = uniqueValues.ToArray(); var encode = new Dictionary<long, int>(); Data.WriteVInt(decode.Length); for (int i = 0; i < decode.Length; i++) { Data.WriteLong(decode[i]); encode[decode[i]] = i; } Meta.WriteVInt(PackedInts.VERSION_CURRENT); Data.WriteVInt(formatAndBits.format.id); Data.WriteVInt(formatAndBits.bitsPerValue); PackedInts.Writer writer = PackedInts.GetWriterNoHeader(Data, formatAndBits.format, MaxDoc, formatAndBits.bitsPerValue, PackedInts.DEFAULT_BUFFER_SIZE); foreach (long? nv in values) { writer.Add(encode[nv == null ? 0 : nv.Value]); } writer.Finish(); } } else if (gcd != 0 && gcd != 1) { Meta.WriteByte((byte)GCD_COMPRESSED); Meta.WriteVInt(PackedInts.VERSION_CURRENT); Data.WriteLong(minValue); Data.WriteLong(gcd); Data.WriteVInt(BLOCK_SIZE); var writer = new BlockPackedWriter(Data, BLOCK_SIZE); foreach (long? nv in values) { long value = nv == null ? 0 : nv.Value; writer.Add((value - minValue) / gcd); } writer.Finish(); } else { Meta.WriteByte((byte)DELTA_COMPRESSED); // delta-compressed Meta.WriteVInt(PackedInts.VERSION_CURRENT); Data.WriteVInt(BLOCK_SIZE); var writer = new BlockPackedWriter(Data, BLOCK_SIZE); foreach (long? nv in values) { writer.Add(nv == null ? 0 : nv.Value); } writer.Finish(); } } protected override void Dispose(bool disposing) { if (disposing) { bool success = false; try { if (Meta != null) { Meta.WriteVInt(-1); // write EOF marker CodecUtil.WriteFooter(Meta); // write checksum } if (Data != null) { CodecUtil.WriteFooter(Data); // write checksum } success = true; } finally { if (success) { IOUtils.Close(Data, Meta); } else { IOUtils.CloseWhileHandlingException(Data, Meta); } Meta = Data = null; } } } public override void AddBinaryField(FieldInfo field, IEnumerable<BytesRef> values) { throw new System.NotSupportedException(); } public override void AddSortedField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrd) { throw new System.NotSupportedException(); } public override void AddSortedSetField(FieldInfo field, IEnumerable<BytesRef> values, IEnumerable<long?> docToOrdCount, IEnumerable<long?> ords) { throw new System.NotSupportedException(); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.Specialized; using System.Collections.Generic; using System.Management.Automation; using System.Management.Automation.Internal; namespace Microsoft.PowerShell.Commands.Internal.Format { /// <summary> /// inner command class used to manage the sub pipelines /// it determines which command should process the incoming objects /// based on the object type /// /// This class is the implementation class for out-console and out-file /// </summary> internal sealed class OutputManagerInner : ImplementationCommandBase { #region tracer [TraceSource("format_out_OutputManagerInner", "OutputManagerInner")] internal static PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutputManagerInner", "OutputManagerInner"); #endregion tracer #region LineOutput internal LineOutput LineOutput { set { lock (_syncRoot) { _lo = value; if (_isStopped) { _lo.StopProcessing(); } } } } private LineOutput _lo = null; #endregion /// <summary> /// handler for processing each object coming through the pipeline /// it forwards the call to the pipeline manager object /// </summary> internal override void ProcessRecord() { PSObject so = this.ReadObject(); if (so == null || so == AutomationNull.Value) { return; } // on demand initialization when the first pipeline // object is initialized if (_mgr == null) { _mgr = new SubPipelineManager(); _mgr.Initialize(_lo, this.OuterCmdlet().Context); } #if false // if the object supports IEnumerable, // unpack the object and process each member separately IEnumerable e = PSObjectHelper.GetEnumerable (so); if (e == null) { this.mgr.Process (so); } else { foreach (object obj in e) { this.mgr.Process (PSObjectHelper.AsPSObject (obj)); } } #else _mgr.Process(so); #endif } /// <summary> /// handler for processing shut down. It forwards the call to the /// pipeline manager object /// </summary> internal override void EndProcessing() { // shut down only if we ever processed a pipeline object if (_mgr != null) _mgr.ShutDown(); } internal override void StopProcessing() { lock (_syncRoot) { if (_lo != null) { _lo.StopProcessing(); } _isStopped = true; } } /// <summary> /// make sure we dispose of the sub pipeline manager /// </summary> protected override void InternalDispose() { base.InternalDispose(); if (_mgr != null) { _mgr.Dispose(); _mgr = null; } } /// <summary> /// instance of the pipeline manager object /// </summary> private SubPipelineManager _mgr = null; /// <summary> /// True if the cmdlet has been stopped /// </summary> private bool _isStopped = false; /// <summary> /// Lock object /// </summary> private object _syncRoot = new object(); } /// <summary> /// object managing the sub-pipelines that execute /// different output commands (or different instances of the /// default one) /// </summary> internal sealed class SubPipelineManager : IDisposable { /// <summary> /// entry defining a command to be run in a separate pipeline /// </summary> private sealed class CommandEntry : IDisposable { /// <summary> /// instance of pipeline wrapper object /// </summary> internal CommandWrapper command = new CommandWrapper(); /// <summary> /// /// </summary> /// <param name="typeName">ETS type name of the object to process</param> /// <returns>true if there is a match</returns> internal bool AppliesToType(string typeName) { foreach (String s in _applicableTypes) { if (string.Equals(s, typeName, StringComparison.OrdinalIgnoreCase)) return true; } return false; } /// <summary> /// just dispose of the inner command wrapper /// </summary> public void Dispose() { if (this.command == null) return; this.command.Dispose(); this.command = null; } /// <summary> /// ordered list of ETS type names this object is handling /// </summary> private StringCollection _applicableTypes = new StringCollection(); } /// <summary> /// Initialize the pipeline manager before any object is processed /// </summary> /// <param name="lineOutput">LineOutput to pass to the child pipelines</param> /// <param name="context">ExecutionContext to pass to the child pipelines</param> internal void Initialize(LineOutput lineOutput, ExecutionContext context) { _lo = lineOutput; InitializeCommandsHardWired(context); } /// <summary> /// hard wired registration helper for specialized types /// </summary> /// <param name="context">ExecutionContext to pass to the child pipeline</param> private void InitializeCommandsHardWired(ExecutionContext context) { // set the default handler RegisterCommandDefault(context, "out-lineoutput", typeof(OutLineOutputCommand)); /* NOTE: This is the spot where we could add new specialized handlers for additional types. Adding a handler here would cause a new sub-pipeline to be created. For example, the following line would add a new handler named "out-foobar" to be invoked when the incoming object type is "MyNamespace.Whatever.FooBar" RegisterCommandForTypes (context, "out-foobar", new string[] { "MyNamespace.Whatever.FooBar" }); And the method can be like this: private void RegisterCommandForTypes (ExecutionContext context, string commandName, Type commandType, string[] types) { CommandEntry ce = new CommandEntry (); ce.command.Initialize (context, commandName, commandType); ce.command.AddNamedParameter ("LineOutput", this.lo); for (int k = 0; k < types.Length; k++) { ce.AddApplicableType (types[k]); } this.commandEntryList.Add (ce); } */ } /// <summary> /// register the default output command /// </summary> /// <param name="context">ExecutionContext to pass to the child pipeline</param> /// <param name="commandName">name of the command to execute</param> /// <param name="commandType">Type of the command to execute</param> private void RegisterCommandDefault(ExecutionContext context, string commandName, Type commandType) { CommandEntry ce = new CommandEntry(); ce.command.Initialize(context, commandName, commandType); ce.command.AddNamedParameter("LineOutput", _lo); _defaultCommandEntry = ce; } /// <summary> /// process an incoming parent pipeline object /// </summary> /// <param name="so">pipeline object to process</param> internal void Process(PSObject so) { // select which pipeline should handle the object CommandEntry ce = this.GetActiveCommandEntry(so); Diagnostics.Assert(ce != null, "CommandEntry ce must not be null"); // delegate the processing ce.command.Process(so); } /// <summary> /// shut down the child pipelines /// </summary> internal void ShutDown() { // we assume that command entries are never null foreach (CommandEntry ce in _commandEntryList) { Diagnostics.Assert(ce != null, "ce != null"); ce.command.ShutDown(); ce.command = null; } // we assume we always have a default command entry Diagnostics.Assert(_defaultCommandEntry != null, "defaultCommandEntry != null"); _defaultCommandEntry.command.ShutDown(); _defaultCommandEntry.command = null; } public void Dispose() { // we assume that command entries are never null foreach (CommandEntry ce in _commandEntryList) { Diagnostics.Assert(ce != null, "ce != null"); ce.Dispose(); } // we assume we always have a default command entry Diagnostics.Assert(_defaultCommandEntry != null, "defaultCommandEntry != null"); _defaultCommandEntry.Dispose(); } /// <summary> /// it selects the applicable out command (it can be the default one) /// to process the current pipeline object /// </summary> /// <param name="so">pipeline object to be processed</param> /// <returns>applicable command entry</returns> private CommandEntry GetActiveCommandEntry(PSObject so) { string typeName = PSObjectHelper.PSObjectIsOfExactType(so.InternalTypeNames); foreach (CommandEntry ce in _commandEntryList) { if (ce.AppliesToType(typeName)) return ce; } // failed any match: return the default handler return _defaultCommandEntry; } private LineOutput _lo = null; /// <summary> /// list of command entries, each with a set of applicable types /// </summary> private List<CommandEntry> _commandEntryList = new List<CommandEntry>(); /// <summary> /// default command entry to be executed when all type matches fail /// </summary> private CommandEntry _defaultCommandEntry = new CommandEntry(); } }
// // Community.CsharpSqlite.SQLiteClient.SqliteDataReader.cs // // Provides a means of reading a forward-only stream of rows from a Sqlite // database file. // // Author(s): Vladimir Vukicevic <vladimir@pobox.com> // Everaldo Canuto <everaldo_canuto@yahoo.com.br> // Joshua Tauberer <tauberer@for.net> // // Copyright (C) 2002 Vladimir Vukicevic // // 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.Collections.Generic ; using System.Data; using System.Data.Common; using Community.CsharpSqlite; namespace Community.CsharpSqlite.SQLiteClient { public class SqliteDataReader : DbDataReader, IDataReader, IDisposable, IDataRecord { #region Fields private SqliteCommand command; private List<object[]> rows; private string[] columns; private Dictionary<String, Object> column_names_sens, column_names_insens; private int current_row; private bool closed; private bool reading; private int records_affected; private string[] decltypes; #endregion #region Constructors and destructors internal SqliteDataReader (SqliteCommand cmd, Sqlite3.Vdbe pVm, int version) { command = cmd; rows = new List<object[]>(); column_names_sens = new Dictionary<String, Object>(); column_names_insens = new Dictionary<String, Object>( StringComparer.InvariantCultureIgnoreCase ); closed = false; current_row = -1; reading = true; ReadpVm (pVm, version, cmd); ReadingDone (); } #endregion #region Properties public override int Depth { get { return 0; } } public override int FieldCount { get { return columns.Length; } } public override object this[string name] { get { return GetValue (GetOrdinal (name)); } } public override object this[int i] { get { return GetValue (i); } } public override bool IsClosed { get { return closed; } } public override int RecordsAffected { get { return records_affected; } } #endregion #region Internal Methods internal void ReadpVm (Sqlite3.Vdbe pVm, int version, SqliteCommand cmd) { int pN; IntPtr pazValue; IntPtr pazColName; bool first = true; int[] declmode = null; while (true) { bool hasdata = cmd.ExecuteStatement(pVm, out pN, out pazValue, out pazColName); // For the first row, get the column information if (first) { first = false; if (version == 3) { // A decltype might be null if the type is unknown to sqlite. decltypes = new string[pN]; declmode = new int[pN]; // 1 == integer, 2 == datetime for (int i = 0; i < pN; i++) { string decl = Sqlite3.sqlite3_column_decltype (pVm, i); if (decl != null) { decltypes[i] = decl.ToLower(System.Globalization.CultureInfo.InvariantCulture); if (decltypes[i] == "int" || decltypes[i] == "integer") declmode[i] = 1; else if (decltypes[i] == "date" || decltypes[i] == "datetime") declmode[i] = 2; } } } columns = new string[pN]; for (int i = 0; i < pN; i++) { string colName; //if (version == 2) { // IntPtr fieldPtr = Marshal.ReadIntPtr (pazColName, i*IntPtr.Size); // colName = Sqlite.HeapToString (fieldPtr, ((SqliteConnection)cmd.Connection).Encoding); //} else { colName = Sqlite3.sqlite3_column_name (pVm, i); //} columns[i] = colName; column_names_sens [colName] = i; column_names_insens [colName] = i; } } if (!hasdata) break; object[] data_row = new object [pN]; for (int i = 0; i < pN; i++) { /* if (version == 2) { IntPtr fieldPtr = Marshal.ReadIntPtr (pazValue, i*IntPtr.Size); data_row[i] = Sqlite.HeapToString (fieldPtr, ((SqliteConnection)cmd.Connection).Encoding); } else { */ switch (Sqlite3.sqlite3_column_type (pVm, i)) { case 1: long val = Sqlite3.sqlite3_column_int64 (pVm, i); // If the column was declared as an 'int' or 'integer', let's play // nice and return an int (version 3 only). if (declmode[i] == 1 && val >= int.MinValue && val <= int.MaxValue) data_row[i] = (int)val; // Or if it was declared a date or datetime, do the reverse of what we // do for DateTime parameters. else if (declmode[i] == 2) data_row[i] = DateTime.FromFileTime(val); else data_row[i] = val; break; case 2: data_row[i] = Sqlite3.sqlite3_column_double (pVm, i); break; case 3: data_row[i] = Sqlite3.sqlite3_column_text (pVm, i); // If the column was declared as a 'date' or 'datetime', let's play // nice and return a DateTime (version 3 only). if (declmode[i] == 2) if (data_row[i] == null) data_row[i] = null; else data_row[i] = DateTime.Parse((string)data_row[i], System.Globalization.CultureInfo.InvariantCulture); break; case 4: int blobbytes = Sqlite3.sqlite3_column_bytes16 (pVm, i); byte[] blob = Sqlite3.sqlite3_column_blob(pVm, i); //byte[] blob = new byte[blobbytes]; //Marshal.Copy (blobptr, blob, 0, blobbytes); data_row[i] = blob; break; case 5: data_row[i] = null; break; default: throw new Exception ("FATAL: Unknown sqlite3_column_type"); //} } } rows.Add (data_row); } } internal void ReadingDone () { records_affected = command.NumChanges (); reading = false; } #endregion #region Public Methods public override void Close () { closed = true; } protected override void Dispose (bool disposing) { if (disposing) Close (); } public override IEnumerator GetEnumerator () { return new DbEnumerator (this); } #if !SQLITE_SILVERLIGHT public override DataTable GetSchemaTable () { DataTable dataTableSchema = new DataTable (); dataTableSchema.Columns.Add ("ColumnName", typeof (String)); dataTableSchema.Columns.Add ("ColumnOrdinal", typeof (Int32)); dataTableSchema.Columns.Add ("ColumnSize", typeof (Int32)); dataTableSchema.Columns.Add ("NumericPrecision", typeof (Int32)); dataTableSchema.Columns.Add ("NumericScale", typeof (Int32)); dataTableSchema.Columns.Add ("IsUnique", typeof (Boolean)); dataTableSchema.Columns.Add ("IsKey", typeof (Boolean)); dataTableSchema.Columns.Add ("BaseCatalogName", typeof (String)); dataTableSchema.Columns.Add ("BaseColumnName", typeof (String)); dataTableSchema.Columns.Add ("BaseSchemaName", typeof (String)); dataTableSchema.Columns.Add ("BaseTableName", typeof (String)); dataTableSchema.Columns.Add ("DataType", typeof(Type)); dataTableSchema.Columns.Add ("AllowDBNull", typeof (Boolean)); dataTableSchema.Columns.Add ("ProviderType", typeof (Int32)); dataTableSchema.Columns.Add ("IsAliased", typeof (Boolean)); dataTableSchema.Columns.Add ("IsExpression", typeof (Boolean)); dataTableSchema.Columns.Add ("IsIdentity", typeof (Boolean)); dataTableSchema.Columns.Add ("IsAutoIncrement", typeof (Boolean)); dataTableSchema.Columns.Add ("IsRowVersion", typeof (Boolean)); dataTableSchema.Columns.Add ("IsHidden", typeof (Boolean)); dataTableSchema.Columns.Add ("IsLong", typeof (Boolean)); dataTableSchema.Columns.Add ("IsReadOnly", typeof (Boolean)); dataTableSchema.BeginLoadData(); for (int i = 0; i < this.FieldCount; i += 1 ) { DataRow schemaRow = dataTableSchema.NewRow (); schemaRow["ColumnName"] = columns[i]; schemaRow["ColumnOrdinal"] = i; schemaRow["ColumnSize"] = 0; schemaRow["NumericPrecision"] = 0; schemaRow["NumericScale"] = 0; schemaRow["IsUnique"] = false; schemaRow["IsKey"] = false; schemaRow["BaseCatalogName"] = ""; schemaRow["BaseColumnName"] = columns[i]; schemaRow["BaseSchemaName"] = ""; schemaRow["BaseTableName"] = ""; schemaRow["DataType"] = typeof(string); schemaRow["AllowDBNull"] = true; schemaRow["ProviderType"] = 0; schemaRow["IsAliased"] = false; schemaRow["IsExpression"] = false; schemaRow["IsIdentity"] = false; schemaRow["IsAutoIncrement"] = false; schemaRow["IsRowVersion"] = false; schemaRow["IsHidden"] = false; schemaRow["IsLong"] = false; schemaRow["IsReadOnly"] = false; dataTableSchema.Rows.Add (schemaRow); schemaRow.AcceptChanges(); } dataTableSchema.EndLoadData(); return dataTableSchema; } #endif public override bool NextResult () { current_row++; return (current_row < rows.Count); } public override bool Read () { return NextResult (); } #endregion #region IDataRecord getters public override bool GetBoolean (int i) { return Convert.ToBoolean (((object[]) rows[current_row])[i]); } public override byte GetByte (int i) { return Convert.ToByte (((object[]) rows[current_row])[i]); } public override long GetBytes (int i, long fieldOffset, byte[] buffer, int bufferOffset, int length) { byte[] data = (byte[])(((object[]) rows[current_row])[i]); if (buffer != null) Array.Copy (data, (int)fieldOffset, buffer, bufferOffset, length); #if (SQLITE_SILVERLIGHT||WINDOWS_MOBILE) return data.Length - fieldOffset; #else return data.LongLength - fieldOffset; #endif } public override char GetChar (int i) { return Convert.ToChar (((object[]) rows[current_row])[i]); } public override long GetChars (int i, long fieldOffset, char[] buffer, int bufferOffset, int length) { char[] data = (char[])(((object[]) rows[current_row])[i]); if (buffer != null) Array.Copy (data, (int)fieldOffset, buffer, bufferOffset, length); #if (SQLITE_SILVERLIGHT||WINDOWS_MOBILE) return data.Length - fieldOffset; #else return data.LongLength - fieldOffset; #endif } public override string GetDataTypeName (int i) { if (decltypes != null && decltypes[i] != null) return decltypes[i]; return "text"; // SQL Lite data type } public override DateTime GetDateTime (int i) { return Convert.ToDateTime (((object[]) rows[current_row])[i]); } public override decimal GetDecimal (int i) { return Convert.ToDecimal (((object[]) rows[current_row])[i]); } public override double GetDouble (int i) { return Convert.ToDouble (((object[]) rows[current_row])[i]); } public override Type GetFieldType (int i) { int row = current_row; if (row == -1 && rows.Count == 0) return typeof(string); if (row == -1) row = 0; object element = ((object[]) rows[row])[i]; if (element != null) return element.GetType(); else return typeof (string); // Note that the return value isn't guaranteed to // be the same as the rows are read if different // types of information are stored in the column. } public override float GetFloat (int i) { return Convert.ToSingle (((object[]) rows[current_row])[i]); } public override Guid GetGuid (int i) { object value = GetValue (i); if (!(value is Guid)) { if (value is DBNull) throw new SqliteExecutionException ("Column value must not be null"); throw new InvalidCastException ("Type is " + value.GetType ().ToString ()); } return ((Guid) value); } public override short GetInt16 (int i) { return Convert.ToInt16 (((object[]) rows[current_row])[i]); } public override int GetInt32 (int i) { return Convert.ToInt32 (((object[]) rows[current_row])[i]); } public override long GetInt64 (int i) { return Convert.ToInt64 (((object[]) rows[current_row])[i]); } public override string GetName (int i) { return columns[i]; } public override int GetOrdinal (string name) { object v = column_names_sens.ContainsKey( name ) ? column_names_sens[name] : null; if ( v == null ) v = column_names_insens.ContainsKey( name ) ? column_names_insens[name] : null; if ( v == null ) throw new ArgumentException( "Column does not exist." ); return (int)v; } public override string GetString (int i) { if (((object[]) rows[current_row])[i] != null) return (((object[]) rows[current_row])[i]).ToString(); else return null; } public override object GetValue (int i) { return ((object[]) rows[current_row])[i]; } public override int GetValues (object[] values) { int num_to_fill = System.Math.Min (values.Length, columns.Length); for (int i = 0; i < num_to_fill; i++) { if (((object[]) rows[current_row])[i] != null) { values[i] = ((object[]) rows[current_row])[i]; } else { values[i] = DBNull.Value; } } return num_to_fill; } public override bool IsDBNull (int i) { return (((object[]) rows[current_row])[i] == null); } public override bool HasRows { get { return rows.Count > 0; } } public override int VisibleFieldCount { get { return FieldCount; } } #endregion } }
/* Copyright (c) 2009-11, ReactionGrid Inc. http://reactiongrid.com * See License.txt for full licence information. * * Sit.cs Revision 1.4.1107.20 * Enables an avatar to sit on items designated to be sittable */ using UnityEngine; using System.Collections; using ReactionGrid.Jibe; public class Sit : MonoBehaviour { public string sitPose = "sit1"; public string groundSitPose = "groundsit"; private bool isSitting = false; private bool isHovering = false; public float clickDistanceLimit = 15; public float sitTargetOffsetX = 0.0f; public float sitTargetOffsetY = 0.0f; public float sitTargetOffsetZ = 0.0f; public Vector3 unsitOffset = Vector3.zero; public string sitText = "sit"; public string groundSitText = "Sit"; public bool enableGroundSit = true; public Texture2D sitIcon; public string standText = "stand"; public GUISkin skin; public bool ShowStandButton = false; private Vector3 sitTarget; private Quaternion sitRotation; private GameObject currentPlayer; // contains movement controls public NetworkController networkController; // controls the environment public ChatInput chatController; // controls the chat system private GameObject playerCam; public GameObject cursor; private GameObject currentChair; private JibeActivityLog jibeLog; private string username; private string userId; private float playerCapsuleRadius = 0.2f; private float playerCapsuleHeight = 1.6f; private bool showTerrainSit = false; private Vector2 terrainSitPosition; private Vector3 terrainSitCoordinates; private float groundSitShowDuration = 2.0f; private float groundSitShowElapsed = 0.0f; //used in case another function that takes the same screenspace as the sit screenspace needs to override sitting private int sitNextFrame=-1; public GameObject standUpButton; void Start() { // Initialize static values sitTarget = transform.position; sitRotation = transform.rotation; if (cursor == null) cursor = GameObject.Find("Cursor"); if (networkController == null) { networkController = GameObject.FindGameObjectWithTag("NetworkController").GetComponent<NetworkController>(); } if (chatController == null) { //chatController = GameObject.Find("ChatBox").GetComponent<ChatInput>(); } } void Update() { if(sitNextFrame==0) { InitiateSit(); } if (!isSitting) { DetectMousePosition(); } if (isHovering) { cursor.SendMessage("ShowSitCursor", true, SendMessageOptions.DontRequireReceiver); } else { cursor.SendMessage("ShowSitCursor", false, SendMessageOptions.DontRequireReceiver); } if (showTerrainSit) { groundSitShowElapsed += Time.deltaTime; if (groundSitShowElapsed > groundSitShowDuration) { showTerrainSit = false; groundSitShowElapsed = 0.0f; } } sitNextFrame--; } private void DetectMousePosition() { // Can't do this with MouseOver / MouseExit since the camera could be disabled // and mouseover doesn't play nice if that has happened! if (playerCam == null) playerCam = GameObject.FindGameObjectWithTag("MainCamera"); if (playerCam != null) { if (playerCam.GetComponent<Camera>().enabled) { Ray mouseRay = playerCam.GetComponent<Camera>().ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(mouseRay, out hit, clickDistanceLimit)) { //Debug.Log(hit.transform.name); if (hit.transform.tag == "SitTarget") { // Player is hovering over a sittable object - one tagged as a "SitTarget". // NOTE A sittable object MUST contain a collider (even a simple trigger would do) for this (raycasting) to work. if(!Test.isHitting) { isHovering = true; } else { isHovering=false; } sitTarget = hit.transform.position; sitRotation = hit.transform.rotation; if (Input.GetMouseButtonDown(0) && !Input.GetKey(KeyCode.LeftAlt) && !Test.isHitting) { currentChair = hit.transform.gameObject; sitNextFrame=5; //InitiateSit(); } } else if (enableGroundSit && hit.transform.name == "Terrain") { terrainSitCoordinates = hit.point; if (Input.GetMouseButtonDown(1)) { terrainSitPosition = playerCam.GetComponent<Camera>().WorldToScreenPoint(terrainSitCoordinates); showTerrainSit = true; } } else { isHovering = false; } } else { isHovering=false; } } } } void OnGUI() { GUI.skin = skin; if (isSitting) { // To stand up, the player moves forward or back while not chatting if (Input.GetButton("Vertical") || (Input.GetMouseButton(0) && Input.GetMouseButton(1)) || Input.GetButton("Jump")) { if (!chatController.IsChatting()) { UnSit(); } } if (ShowStandButton) { // An alternative - show a button so the player can stand up when they are finished if (GUI.Button(new Rect(Screen.width/2-50,Screen.height-50,100,25), standText)) { UnSit(); } } } if (showTerrainSit) { Vector2 pos = GUIUtility.ScreenToGUIPoint(new Vector2(terrainSitPosition.x, Screen.height - terrainSitPosition.y)); GUIStyle buttonStyle = new GUIStyle("Button"); buttonStyle.fixedWidth = 50; if (GUI.Button(new Rect(pos.x, pos.y, 50, 20), groundSitText, buttonStyle)) { InitiateGroundSit(); } } } private void InitiateGroundSit() { // update localPlayer currentPlayer = GameObject.FindGameObjectWithTag("Player"); // Sit on the chair/object isSitting = true; isHovering = false; showTerrainSit = false; groundSitShowElapsed = 0.0f; SitAtPosition(terrainSitCoordinates, currentPlayer.transform.rotation, groundSitPose); } private void InitiateSit() { if(!Test.isHitting) { // update localPlayer currentPlayer = GameObject.FindGameObjectWithTag("Player"); // Sit on the chair/object isSitting = true; isHovering = false; cursor.SendMessage("ShowSitCursor", false); standUpButton.SendMessage("Toggle", false); // Move the player to the correct position and rotation float extraOffsetX = 0.0f; float extraOffsetY = 0.0f; float extraOffsetZ = 0.0f; if (currentChair.GetComponent<SitOffset>() != null) { extraOffsetX = currentChair.GetComponent<SitOffset>().SitOffsetX; extraOffsetY = currentChair.GetComponent<SitOffset>().SitOffsetY; extraOffsetZ = currentChair.GetComponent<SitOffset>().SitOffsetZ; sitPose = currentChair.GetComponent<SitOffset>().SitPose; } Vector3 sitPosition = sitTarget; sitPosition.x = sitTarget.x + sitTargetOffsetX + extraOffsetX; sitPosition.y = sitTarget.y + sitTargetOffsetY + extraOffsetY; sitPosition.z = sitTarget.z + sitTargetOffsetZ + extraOffsetZ; sitRotation = Quaternion.Euler(sitRotation.eulerAngles + currentChair.GetComponent<SitOffset>().offsetRotation.eulerAngles); SitAtPosition(sitPosition, sitRotation, sitPose); try { if (currentChair != null) { if (currentChair.GetComponent<ChairController>() != null) { currentChair.GetComponent<ChairController>().Sit(); } } } catch { Debug.Log("No sit camera script on this chair"); } currentPlayer.SendMessage("SnapCameraToDefault"); currentPlayer.SendMessage("GetSitRotation", sitRotation); } } private void SitAtPosition(Vector3 targetPosition, Quaternion targetRotation, string animationToPlay) { // Disable movement controls // ((Behaviour)currentPlayer.GetComponent<PlayerCharacter>()).enabled = false; currentPlayer.GetComponent<FPSInputController>().enabled=false; currentPlayer.GetComponent<CharacterMotor>().enabled=false; currentPlayer.GetComponent<MouseLook>().playerControlOn=false; // If we're using physical characters, turn off the RB component /* PlayerSpawnController psc = networkController.GetComponent<PlayerSpawnController>(); if (psc != null) { if (psc.usePhysicalCharacter) { currentPlayer.GetComponent<Rigidbody>().useGravity = false; playerCapsuleRadius = currentPlayer.GetComponent<CapsuleCollider>().radius; playerCapsuleHeight = currentPlayer.GetComponent<CapsuleCollider>().height; currentPlayer.GetComponent<CapsuleCollider>().radius = 0.01f; currentPlayer.GetComponent<CapsuleCollider>().height = 0.01f; } }*/ // currentPlayer.GetComponent<CharacterController>().radius=.1f; // currentPlayer.GetComponent<CharacterController>().height=.1f; currentPlayer.transform.position = targetPosition; // Note there is no simple way to control the rotation via user settings in inspector. Best approach, adjust the collider on the // sittable object to the correct orientation. This could mean adding an empty cube collider to a chair and rotating to the correct // angle for the avatar to face the correct way. currentPlayer.transform.rotation = targetRotation; // Play the selected sit pose AnimateCharacter tpa = currentPlayer.transform.GetChild(0).GetComponent<AnimateCharacter>(); tpa.SitAnimation(animationToPlay); tpa.EnableIdleWakeup(false); // never want an idle wake up while sitting currentPlayer.transform.GetChild(0).GetComponent<PlayerMovement>().SetSitting(true, animationToPlay); Debug.Log("Sitting: " + isSitting); networkController.SendTransform(currentPlayer.transform); networkController.SendAnimation(animationToPlay); TrackSit(); } private void TrackSit() { // Log the sit interaction to the database, if the activity log is enabled. if (jibeLog == null) { jibeLog = GameObject.Find("Jibe").GetComponent<JibeActivityLog>(); if (jibeLog != null) { Debug.Log("Found jibeLog"); } } if (jibeLog.logEnabled) { if (string.IsNullOrEmpty(username)) { username = networkController.GetMyName(); } IJibePlayer localPlayer = networkController.GetLocalPlayer(); string playerId = localPlayer.PlayerID.ToString(); if (PlayerPrefs.GetString("useruuid") != null) playerId = PlayerPrefs.GetString("useruuid"); Debug.Log(jibeLog.TrackEvent(JibeEventType.Sit, Application.srcValue, this.transform.position.x, this.transform.position.y, this.transform.position.z, playerId, username, "User Sat on Chair")); } } public void UnSit() { standUpButton.SendMessage("Toggle", true); // Cancel sit try { if (currentChair != null) { currentChair.GetComponent<ChairController>().UnSit(); } } catch { Debug.Log("No sit camera script on this chair"); } AnimateCharacter tpa = currentPlayer.transform.GetChild(0).GetComponent<AnimateCharacter>(); tpa.CancelSitAnimation(); bool idleAnimWakeupEnabledByDefault = networkController.gameObject.GetComponent<PlayerSpawnController>().enableIdleAnimationWakeup; tpa.SendMessage("EnableIdleWakeup", idleAnimWakeupEnabledByDefault); // only re-enable if enabled in PSC // If we're using physical characters, turn off the RB component /* PlayerSpawnController psc = networkController.GetComponent<PlayerSpawnController>(); if (psc != null) { if (psc.usePhysicalCharacter) { currentPlayer.GetComponent<Rigidbody>().useGravity = true; currentPlayer.GetComponent<CapsuleCollider>().radius = playerCapsuleRadius; currentPlayer.GetComponent<CapsuleCollider>().height = playerCapsuleHeight; } }*/ currentPlayer.GetComponent<CharacterController>().radius=.5f; currentPlayer.GetComponent<CharacterController>().height=2f; currentPlayer.transform.GetChild(0).GetComponent<PlayerMovement>().SetSitting(false, sitPose); // Re-enable movement // ((Behaviour)currentPlayer.transform.GetChild(0).GetComponent<PlayerCharacter>()).enabled = true; currentPlayer.GetComponent<FPSInputController>().enabled=true; currentPlayer.GetComponent<CharacterMotor>().enabled=true; currentPlayer.GetComponent<MouseLook>().playerControlOn=true; //currentPlayer.GetComponent<MouseLook>().SetCurrentTransformAsDefault(); currentPlayer.transform.Translate(unsitOffset); currentPlayer.GetComponent<MouseLook>().SetCurrentTransformAsDefault(); isSitting = false; Debug.Log("Sitting: " + isSitting); } public void DisableSitThisFrame() { sitNextFrame=-1; } }
/* * Copyright 2007 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; namespace ZXing.Common { /// <summary> <p>A simple, fast array of bits, represented compactly by an array of ints internally.</p> /// /// </summary> /// <author> Sean Owen /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> public sealed class BitArray { private int[] bits; private int size; public int Size { get { return size; } } public int SizeInBytes { get { return (size + 7) >> 3; } } public bool this[int i] { get { return (bits[i >> 5] & (1 << (i & 0x1F))) != 0; } set { if (value) bits[i >> 5] |= 1 << (i & 0x1F); } } public BitArray() { this.size = 0; this.bits = new int[1]; } public BitArray(int size) { if (size < 1) { throw new ArgumentException("size must be at least 1"); } this.size = size; this.bits = makeArray(size); } private void ensureCapacity(int size) { if (size > bits.Length << 5) { int[] newBits = makeArray(size); System.Array.Copy(bits, 0, newBits, 0, bits.Length); bits = newBits; } } /// <summary> Flips bit i. /// /// </summary> /// <param name="i">bit to set /// </param> public void flip(int i) { bits[i >> 5] ^= 1 << (i & 0x1F); } private static int numberOfTrailingZeros(int num) { var index = (-num & num)%37; if (index < 0) index *= -1; return _lookup[index]; } private static readonly int[] _lookup = { 32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4, 7, 17, 0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5, 20, 8, 19, 18 }; /// <summary> /// Gets the next set. /// </summary> /// <param name="from">first bit to check</param> /// <returns>index of first bit that is set, starting from the given index, or size if none are set /// at or beyond this given index</returns> public int getNextSet(int from) { if (from >= size) { return size; } int bitsOffset = from >> 5; int currentBits = bits[bitsOffset]; // mask off lesser bits first currentBits &= ~((1 << (from & 0x1F)) - 1); while (currentBits == 0) { if (++bitsOffset == bits.Length) { return size; } currentBits = bits[bitsOffset]; } int result = (bitsOffset << 5) + numberOfTrailingZeros(currentBits); return result > size ? size : result; } /// <summary> /// see getNextSet(int) /// </summary> /// <param name="from"></param> /// <returns></returns> public int getNextUnset(int from) { if (from >= size) { return size; } int bitsOffset = from >> 5; int currentBits = ~bits[bitsOffset]; // mask off lesser bits first currentBits &= ~((1 << (from & 0x1F)) - 1); while (currentBits == 0) { if (++bitsOffset == bits.Length) { return size; } currentBits = ~bits[bitsOffset]; } int result = (bitsOffset << 5) + numberOfTrailingZeros(currentBits); return result > size ? size : result; } /// <summary> Sets a block of 32 bits, starting at bit i. /// /// </summary> /// <param name="i">first bit to set /// </param> /// <param name="newBits">the new value of the next 32 bits. Note again that the least-significant bit /// corresponds to bit i, the next-least-significant to i+1, and so on. /// </param> public void setBulk(int i, int newBits) { bits[i >> 5] = newBits; } /// <summary> /// Sets a range of bits. /// </summary> /// <param name="start">start of range, inclusive.</param> /// <param name="end">end of range, exclusive</param> public void setRange(int start, int end) { if (end < start) { throw new ArgumentException(); } if (end == start) { return; } end--; // will be easier to treat this as the last actually set bit -- inclusive int firstInt = start >> 5; int lastInt = end >> 5; for (int i = firstInt; i <= lastInt; i++) { int firstBit = i > firstInt ? 0 : start & 0x1F; int lastBit = i < lastInt ? 31 : end & 0x1F; int mask; if (firstBit == 0 && lastBit == 31) { mask = -1; } else { mask = 0; for (int j = firstBit; j <= lastBit; j++) { mask |= 1 << j; } } bits[i] |= mask; } } /// <summary> Clears all bits (sets to false).</summary> public void clear() { int max = bits.Length; for (int i = 0; i < max; i++) { bits[i] = 0; } } /// <summary> Efficient method to check if a range of bits is set, or not set. /// /// </summary> /// <param name="start">start of range, inclusive. /// </param> /// <param name="end">end of range, exclusive /// </param> /// <param name="value">if true, checks that bits in range are set, otherwise checks that they are not set /// </param> /// <returns> true iff all bits are set or not set in range, according to value argument /// </returns> /// <throws> IllegalArgumentException if end is less than or equal to start </throws> public bool isRange(int start, int end, bool value) { if (end < start) { throw new System.ArgumentException(); } if (end == start) { return true; // empty range matches } end--; // will be easier to treat this as the last actually set bit -- inclusive int firstInt = start >> 5; int lastInt = end >> 5; for (int i = firstInt; i <= lastInt; i++) { int firstBit = i > firstInt ? 0 : start & 0x1F; int lastBit = i < lastInt ? 31 : end & 0x1F; int mask; if (firstBit == 0 && lastBit == 31) { mask = -1; } else { mask = 0; for (int j = firstBit; j <= lastBit; j++) { mask |= 1 << j; } } // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is, // equals the mask, or we're looking for 0s and the masked portion is not all 0s if ((bits[i] & mask) != (value ? mask : 0)) { return false; } } return true; } /// <summary> /// Appends the bit. /// </summary> /// <param name="bit">The bit.</param> public void appendBit(bool bit) { ensureCapacity(size + 1); if (bit) { bits[size >> 5] |= 1 << (size & 0x1F); } size++; } /// <returns> underlying array of ints. The first element holds the first 32 bits, and the least /// significant bit is bit 0. /// </returns> public int[] Array { get { return bits; } } /// <summary> /// Appends the least-significant bits, from value, in order from most-significant to /// least-significant. For example, appending 6 bits from 0x000001E will append the bits /// 0, 1, 1, 1, 1, 0 in that order. /// </summary> /// <param name="value">The value.</param> /// <param name="numBits">The num bits.</param> public void appendBits(int value, int numBits) { if (numBits < 0 || numBits > 32) { throw new ArgumentException("Num bits must be between 0 and 32"); } ensureCapacity(size + numBits); for (int numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--) { appendBit(((value >> (numBitsLeft - 1)) & 0x01) == 1); } } public void appendBitArray(BitArray other) { int otherSize = other.size; ensureCapacity(size + otherSize); for (int i = 0; i < otherSize; i++) { appendBit(other[i]); } } public void xor(BitArray other) { if (bits.Length != other.bits.Length) { throw new ArgumentException("Sizes don't match"); } for (int i = 0; i < bits.Length; i++) { // The last byte could be incomplete (i.e. not have 8 bits in // it) but there is no problem since 0 XOR 0 == 0. bits[i] ^= other.bits[i]; } } /// <summary> /// Toes the bytes. /// </summary> /// <param name="bitOffset">first bit to start writing</param> /// <param name="array">array to write into. Bytes are written most-significant byte first. This is the opposite /// of the internal representation, which is exposed by BitArray</param> /// <param name="offset">position in array to start writing</param> /// <param name="numBytes">how many bytes to write</param> public void toBytes(int bitOffset, byte[] array, int offset, int numBytes) { for (int i = 0; i < numBytes; i++) { int theByte = 0; for (int j = 0; j < 8; j++) { if (this[bitOffset]) { theByte |= 1 << (7 - j); } bitOffset++; } array[offset + i] = (byte)theByte; } } /// <summary> Reverses all bits in the array.</summary> public void reverse() { int[] newBits = new int[bits.Length]; int size = this.size; for (int i = 0; i < size; i++) { if (this[size - i - 1]) { newBits[i >> 5] |= 1 << (i & 0x1F); } } bits = newBits; } private static int[] makeArray(int size) { return new int[(size + 31) >> 5]; } public override String ToString() { var result = new System.Text.StringBuilder(size); for (int i = 0; i < size; i++) { if ((i & 0x07) == 0) { result.Append(' '); } result.Append(this[i] ? 'X' : '.'); } return result.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.Threading.Tasks; using Xunit; namespace System.IO.Tests { public partial class WaitForChangedTests : FileSystemWatcherTest { private const int BetweenOperationsDelayMilliseconds = 100; [Fact] public static void WaitForChangedResult_DefaultValues() { var result = new WaitForChangedResult(); Assert.Equal((WatcherChangeTypes)0, result.ChangeType); Assert.Null(result.Name); Assert.Null(result.OldName); Assert.False(result.TimedOut); } [Theory] [InlineData(WatcherChangeTypes.All)] [InlineData(WatcherChangeTypes.Changed)] [InlineData(WatcherChangeTypes.Created)] [InlineData(WatcherChangeTypes.Deleted)] [InlineData(WatcherChangeTypes.Renamed)] [InlineData(WatcherChangeTypes.Changed | WatcherChangeTypes.Created)] [InlineData(WatcherChangeTypes.Deleted | WatcherChangeTypes.Renamed)] [InlineData((WatcherChangeTypes)0)] [InlineData((WatcherChangeTypes)int.MinValue)] [InlineData((WatcherChangeTypes)int.MaxValue)] [InlineData((WatcherChangeTypes)int.MaxValue)] public static void WaitForChangedResult_ChangeType_Roundtrip(WatcherChangeTypes changeType) { var result = new WaitForChangedResult(); result.ChangeType = changeType; Assert.Equal(changeType, result.ChangeType); } [Theory] [InlineData("")] [InlineData("myfile.txt")] [InlineData(" ")] [InlineData(" myfile.txt ")] public static void WaitForChangedResult_Name_Roundtrip(string name) { var result = new WaitForChangedResult(); result.Name = name; Assert.Equal(name, result.Name); } [Theory] [InlineData("")] [InlineData("myfile.txt")] [InlineData(" ")] [InlineData(" myfile.txt ")] public static void WaitForChangedResult_OldName_Roundtrip(string name) { var result = new WaitForChangedResult(); result.OldName = name; Assert.Equal(name, result.OldName); } [Theory] public static void WaitForChangedResult_TimedOut_Roundtrip() { var result = new WaitForChangedResult(); result.TimedOut = true; Assert.True(result.TimedOut); result.TimedOut = false; Assert.False(result.TimedOut); result.TimedOut = true; Assert.True(result.TimedOut); } [Theory] [InlineData(false)] [InlineData(true)] public void ZeroTimeout_TimesOut(bool enabledBeforeWait) { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var fsw = new FileSystemWatcher(testDirectory.Path)) { if (enabledBeforeWait) fsw.EnableRaisingEvents = true; AssertTimedOut(fsw.WaitForChanged(WatcherChangeTypes.All, 0)); Assert.Equal(enabledBeforeWait, fsw.EnableRaisingEvents); } } [Theory] [InlineData(false)] [InlineData(true)] public void NonZeroTimeout_NoEvents_TimesOut(bool enabledBeforeWait) { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var fsw = new FileSystemWatcher(testDirectory.Path)) { if (enabledBeforeWait) fsw.EnableRaisingEvents = true; AssertTimedOut(fsw.WaitForChanged(0, 1)); Assert.Equal(enabledBeforeWait, fsw.EnableRaisingEvents); } } [Theory] [InlineData(WatcherChangeTypes.Deleted, false)] [InlineData(WatcherChangeTypes.Created, true)] [InlineData(WatcherChangeTypes.Changed, false)] [InlineData(WatcherChangeTypes.Renamed, true)] [InlineData(WatcherChangeTypes.All, true)] public void NonZeroTimeout_NoActivity_TimesOut(WatcherChangeTypes changeType, bool enabledBeforeWait) { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var fsw = new FileSystemWatcher(testDirectory.Path)) { if (enabledBeforeWait) fsw.EnableRaisingEvents = true; AssertTimedOut(fsw.WaitForChanged(changeType, 1)); Assert.Equal(enabledBeforeWait, fsw.EnableRaisingEvents); } } [Theory] [OuterLoop("This test has a longer than average timeout and may fail intermittently")] [InlineData(WatcherChangeTypes.Created)] [InlineData(WatcherChangeTypes.Deleted)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #18308")] public void CreatedDeleted_Success(WatcherChangeTypes changeType) { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var fsw = new FileSystemWatcher(testDirectory.Path)) { for (int i = 1; i <= DefaultAttemptsForExpectedEvent; i++) { Task<WaitForChangedResult> t = Task.Run(() => fsw.WaitForChanged(changeType, LongWaitTimeout)); while (!t.IsCompleted) { string path = Path.Combine(testDirectory.Path, Path.GetRandomFileName()); File.WriteAllText(path, "text"); Task.Delay(BetweenOperationsDelayMilliseconds).Wait(); if ((changeType & WatcherChangeTypes.Deleted) != 0) { File.Delete(path); } } try { Assert.Equal(TaskStatus.RanToCompletion, t.Status); Assert.Equal(changeType, t.Result.ChangeType); Assert.NotNull(t.Result.Name); Assert.Null(t.Result.OldName); Assert.False(t.Result.TimedOut); } catch when (i < DefaultAttemptsForExpectedEvent) { continue; } return; } } } [Fact] [OuterLoop("This test has a longer than average timeout and may fail intermittently")] public void Changed_Success() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var fsw = new FileSystemWatcher(testDirectory.Path)) { for (int i = 1; i <= DefaultAttemptsForExpectedEvent; i++) { string name = Path.Combine(testDirectory.Path, Path.GetRandomFileName()); File.Create(name).Dispose(); Task<WaitForChangedResult> t = Task.Run(() => fsw.WaitForChanged(WatcherChangeTypes.Changed, LongWaitTimeout)); while (!t.IsCompleted) { File.AppendAllText(name, "text"); Task.Delay(BetweenOperationsDelayMilliseconds).Wait(); } try { Assert.Equal(TaskStatus.RanToCompletion, t.Status); Assert.Equal(WatcherChangeTypes.Changed, t.Result.ChangeType); Assert.NotNull(t.Result.Name); Assert.Null(t.Result.OldName); Assert.False(t.Result.TimedOut); } catch when (i < DefaultAttemptsForExpectedEvent) { continue; } return; } } } [Fact] [OuterLoop("This test has a longer than average timeout and may fail intermittently")] public void Renamed_Success() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var fsw = new FileSystemWatcher(testDirectory.Path)) { for (int i = 1; i <= DefaultAttemptsForExpectedEvent; i++) { Task<WaitForChangedResult> t = Task.Run(() => fsw.WaitForChanged(WatcherChangeTypes.Renamed | WatcherChangeTypes.Created, LongWaitTimeout)); // on some OSes, the renamed might come through as Deleted/Created string name = Path.Combine(testDirectory.Path, Path.GetRandomFileName()); File.Create(name).Dispose(); while (!t.IsCompleted) { string newName = Path.Combine(testDirectory.Path, Path.GetRandomFileName()); File.Move(name, newName); name = newName; Task.Delay(BetweenOperationsDelayMilliseconds).Wait(); } try { Assert.Equal(TaskStatus.RanToCompletion, t.Status); Assert.True(t.Result.ChangeType == WatcherChangeTypes.Created || t.Result.ChangeType == WatcherChangeTypes.Renamed); Assert.NotNull(t.Result.Name); Assert.False(t.Result.TimedOut); } catch when (i < DefaultAttemptsForExpectedEvent) { continue; } return; } } } private static void AssertTimedOut(WaitForChangedResult result) { Assert.Equal(0, (int)result.ChangeType); Assert.Null(result.Name); Assert.Null(result.OldName); Assert.True(result.TimedOut); } } }
// 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.Runtime.InteropServices; using System.Threading.Tasks; using System.Collections.Generic; using System.Runtime.CompilerServices; public static class Assert { public static bool HasAssertFired; public static void AreEqual(Object actual, Object expected) { if (!(actual == null && expected == null) && !actual.Equals(expected)) { Console.WriteLine("Not equal!"); Console.WriteLine("actual = " + actual.ToString()); Console.WriteLine("expected = " + expected.ToString()); HasAssertFired = true; } } } public interface IMyInterface { #if V2 // Adding new methods to interfaces is incompatible change, but we will make sure that it works anyway void NewInterfaceMethod(); #endif string InterfaceMethod(string s); } public class MyClass : IMyInterface { #if V2 public int _field1; public int _field2; public int _field3; #endif public int InstanceField; #if V2 public static Object StaticObjectField2; [ThreadStatic] public static String ThreadStaticStringField2; [ThreadStatic] public static int ThreadStaticIntField; public static Nullable<Guid> StaticNullableGuidField; public static Object StaticObjectField; [ThreadStatic] public static int ThreadStaticIntField2; public static long StaticLongField; [ThreadStatic] public static DateTime ThreadStaticDateTimeField2; public static long StaticLongField2; [ThreadStatic] public static DateTime ThreadStaticDateTimeField; public static Nullable<Guid> StaticNullableGuidField2; [ThreadStatic] public static String ThreadStaticStringField; #else public static Object StaticObjectField; public static long StaticLongField; public static Nullable<Guid> StaticNullableGuidField; [ThreadStatic] public static String ThreadStaticStringField; [ThreadStatic] public static int ThreadStaticIntField; [ThreadStatic] public static DateTime ThreadStaticDateTimeField; #endif public MyClass() { } #if V2 public virtual void NewVirtualMethod() { } public virtual void NewInterfaceMethod() { throw new Exception(); } #endif public virtual string VirtualMethod() { return "Virtual method result"; } public virtual string InterfaceMethod(string s) { return "Interface" + s + "result"; } public static string TestInterfaceMethod(IMyInterface i, string s) { return i.InterfaceMethod(s); } public static void TestStaticFields() { StaticObjectField = (int)StaticObjectField + 12345678; StaticLongField *= 456; Assert.AreEqual(StaticNullableGuidField, new Guid("0D7E505F-E767-4FEF-AEEC-3243A3005673")); StaticNullableGuidField = null; ThreadStaticStringField += "World"; ThreadStaticIntField /= 78; ThreadStaticDateTimeField = ThreadStaticDateTimeField + new TimeSpan(123); MyGeneric<int,int>.ThreadStatic = new Object(); #if false // TODO: Enable once LDFTN is supported // Do some operations on static fields on a different thread to verify that we are not mixing thread-static and non-static Task.Run(() => { StaticObjectField = (int)StaticObjectField + 1234; StaticLongField *= 45; ThreadStaticStringField = "Garbage"; ThreadStaticIntField = 0xBAAD; ThreadStaticDateTimeField = DateTime.Now; }).Wait(); #endif } [DllImport("api-ms-win-core-sysinfo-l1-1-0.dll")] public extern static int GetTickCount(); [DllImport("libcoreclr")] public extern static int GetCurrentThreadId(); static public void TestInterop() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { GetTickCount(); } else { GetCurrentThreadId(); } } #if V2 public string MovedToBaseClass() { return "MovedToBaseClass"; } #endif #if V2 public virtual string ChangedToVirtual() { return null; } #else public string ChangedToVirtual() { return "ChangedToVirtual"; } #endif } public class MyChildClass : MyClass { public MyChildClass() { } #if !V2 public string MovedToBaseClass() { return "MovedToBaseClass"; } #endif #if V2 public override string ChangedToVirtual() { return "ChangedToVirtual"; } #endif } public struct MyStruct : IDisposable { int x; #if V2 void IDisposable.Dispose() { } #else public void Dispose() { } #endif } public class MyGeneric<T,U> { [ThreadStatic] public static Object ThreadStatic; public MyGeneric() { } public virtual string GenericVirtualMethod<V,W>() { return typeof(T).ToString() + typeof(U).ToString() + typeof(V).ToString() + typeof(W).ToString(); } #if V2 public string MovedToBaseClass<W>() { typeof(Dictionary<W,W>).ToString(); return typeof(List<W>).ToString(); } #endif #if V2 public virtual string ChangedToVirtual<W>() { return null; } #else public string ChangedToVirtual<W>() { return typeof(List<W>).ToString(); } #endif } public class MyChildGeneric<T> : MyGeneric<T,T> { public MyChildGeneric() { } #if !V2 public string MovedToBaseClass<W>() { return typeof(List<W>).ToString(); } #endif #if V2 public override string ChangedToVirtual<W>() { typeof(Dictionary<Int32, W>).ToString(); return typeof(List<W>).ToString(); } #endif } [StructLayout(LayoutKind.Sequential)] public class MyClassWithLayout { #if V2 public int _field1; public int _field2; public int _field3; #endif } public struct MyGrowingStruct { int x; int y; #if V2 Object o1; Object o2; #endif static public MyGrowingStruct Construct() { return new MyGrowingStruct() { x = 111, y = 222 }; } public static void Check(ref MyGrowingStruct s) { Assert.AreEqual(s.x, 111); Assert.AreEqual(s.y, 222); } } public struct MyChangingStruct { #if V2 public int y; public int x; #else public int x; public int y; #endif static public MyChangingStruct Construct() { return new MyChangingStruct() { x = 111, y = 222 }; } public static void Check(ref MyChangingStruct s) { Assert.AreEqual(s.x, 112); Assert.AreEqual(s.y, 222); } } public struct MyChangingHFAStruct { #if V2 float x; float y; #else int x; int y; #endif static public MyChangingHFAStruct Construct() { return new MyChangingHFAStruct() { x = 12, y = 23 }; } public static void Check(MyChangingHFAStruct s) { #if V2 Assert.AreEqual(s.x, 12.0f); Assert.AreEqual(s.y, 23.0f); #else Assert.AreEqual(s.x, 12); Assert.AreEqual(s.y, 23); #endif } } public class ByteBaseClass : List<byte> { public byte BaseByte; } public class ByteChildClass : ByteBaseClass { public byte ChildByte; [MethodImplAttribute(MethodImplOptions.NoInlining)] public ByteChildClass(byte value) { ChildByte = 67; } }
//******************************************************************************************************************************************************************************************// // Public Domain // // // // Written by Peter O. in 2014. // // // // Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ // // // // If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ // //******************************************************************************************************************************************************************************************// using System; using System.IO; using Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor.Numbers; namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor { // Contains extra methods placed separately // because they are not CLS-compliant or they // are specific to the .NET version of the library. public sealed partial class CBORObject { /* The "==" and "!=" operators are not overridden in the .NET version to be consistent with Equals, for two reasons: (1) This type is mutable in certain cases, which can cause different results when comparing with another object. (2) Objects with this type can have arbitrary size (e.g., they can be byte strings, text strings, arrays, or maps of arbitrary size), and comparing two of them for equality can be much more complicated and take much more time than the default behavior of reference equality. */ /// <summary>Returns whether one object's value is less than /// another's.</summary> /// <param name='a'>The left-hand side of the comparison.</param> /// <param name='b'>The right-hand side of the comparison.</param> /// <returns><c>true</c> if one object's value is less than another's; /// otherwise, <c>false</c>.</returns> /// <exception cref='ArgumentNullException'>The parameter <paramref /// name='a'/> is null.</exception> public static bool operator <(CBORObject a, CBORObject b) { return a == null ? b != null : a.CompareTo(b) < 0; } /// <summary>Returns whether one object's value is up to /// another's.</summary> /// <param name='a'>The left-hand side of the comparison.</param> /// <param name='b'>The right-hand side of the comparison.</param> /// <returns><c>true</c> if one object's value is up to another's; /// otherwise, <c>false</c>.</returns> /// <exception cref='ArgumentNullException'>The parameter <paramref /// name='a'/> is null.</exception> public static bool operator <=(CBORObject a, CBORObject b) { return a == null || a.CompareTo(b) <= 0; } /// <summary>Returns whether one object's value is greater than /// another's.</summary> /// <param name='a'>The left-hand side of the comparison.</param> /// <param name='b'>The right-hand side of the comparison.</param> /// <returns><c>true</c> if one object's value is greater than /// another's; otherwise, <c>false</c>.</returns> /// <exception cref='ArgumentNullException'>The parameter <paramref /// name='a'/> is null.</exception> public static bool operator >(CBORObject a, CBORObject b) { return a != null && a.CompareTo(b) > 0; } /// <summary>Returns whether one object's value is at least /// another's.</summary> /// <param name='a'>The left-hand side of the comparison.</param> /// <param name='b'>The right-hand side of the comparison.</param> /// <returns><c>true</c> if one object's value is at least another's; /// otherwise, <c>false</c>.</returns> /// <exception cref='ArgumentNullException'>The parameter <paramref /// name='a'/> is null.</exception> public static bool operator >=(CBORObject a, CBORObject b) { return a == null ? b == null : a.CompareTo(b) >= 0; } /// <summary>Converts this object to a 16-bit unsigned integer after /// discarding any fractional part, if any, from its value.</summary> /// <returns>A 16-bit unsigned integer.</returns> /// <exception cref='InvalidOperationException'>This object does not /// represent a number (for this purpose, infinities and not-a-number /// or NaN values, but not CBORObject.Null, are considered /// numbers).</exception> /// <exception cref='OverflowException'>This object's value, if /// converted to an integer by discarding its fractional part, is /// outside the range of a 16-bit unsigned integer.</exception> [CLSCompliant(false)] [Obsolete("Instead, use the following:" + "\u0020(cbor.AsNumber().ToUInt16Checked()), or .ToObject<ushort>().")] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public ushort AsUInt16() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return this.AsUInt16Legacy(); } internal ushort AsUInt16Legacy() { int v = this.AsInt32(); if (v > UInt16.MaxValue || v < 0) { throw new OverflowException("This object's value is out of range"); } return (ushort)v; } /// <summary>Converts this object to a 32-bit unsigned integer after /// discarding any fractional part, if any, from its value.</summary> /// <returns>A 32-bit unsigned integer.</returns> /// <exception cref='InvalidOperationException'>This object does not /// represent a number (for this purpose, infinities and not-a-number /// or NaN values, but not CBORObject.Null, are considered /// numbers).</exception> /// <exception cref='OverflowException'>This object's value, if /// converted to an integer by discarding its fractional part, is /// outside the range of a 32-bit unsigned integer.</exception> [CLSCompliant(false)] [Obsolete("Instead, use the following:" + "\u0020(cbor.AsNumber().ToUInt32Checked()), or .ToObject<uint>().")] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public uint AsUInt32() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return this.AsUInt32Legacy(); } internal uint AsUInt32Legacy() { ulong v = this.AsUInt64Legacy(); if (v > UInt32.MaxValue) { throw new OverflowException("This object's value is out of range"); } return (uint)v; } /// <summary>Converts this object to an 8-bit signed integer.</summary> /// <returns>An 8-bit signed integer.</returns> [CLSCompliant(false)] [Obsolete("Instead, use the following:" + "\u0020(cbor.AsNumber().ToSByteChecked()), or .ToObject<sbyte>().")] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public sbyte AsSByte() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return this.AsSByteLegacy(); } internal sbyte AsSByteLegacy() { int v = this.AsInt32(); if (v > SByte.MaxValue || v < SByte.MinValue) { throw new OverflowException("This object's value is out of range"); } return (sbyte)v; } /// <summary>Writes a CBOR major type number and an integer 0 or /// greater associated with it to a data stream, where that integer is /// passed to this method as a 32-bit unsigned integer. This is a /// low-level method that is useful for implementing custom CBOR /// encoding methodologies. This method encodes the given major type /// and value in the shortest form allowed for the major /// type.</summary> /// <param name='outputStream'>A writable data stream.</param> /// <param name='majorType'>The CBOR major type to write. This is a /// number from 0 through 7 as follows. 0: integer 0 or greater; 1: /// negative integer; 2: byte string; 3: UTF-8 text string; 4: array; /// 5: map; 6: tag; 7: simple value. See RFC 7049 for details on these /// major types.</param> /// <param name='value'>An integer 0 or greater associated with the /// major type, as follows. 0: integer 0 or greater; 1: the negative /// integer's absolute value is 1 plus this number; 2: length in bytes /// of the byte string; 3: length in bytes of the UTF-8 text string; 4: /// number of items in the array; 5: number of key-value pairs in the /// map; 6: tag number; 7: simple value number, which must be in the /// interval [0, 23] or [32, 255].</param> /// <returns>The number of bytes ordered to be written to the data /// stream.</returns> /// <exception cref='ArgumentNullException'>The parameter <paramref /// name='outputStream'/> is null.</exception> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public static int WriteValue( #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant Stream outputStream, int majorType, uint value) { if (outputStream == null) { throw new ArgumentNullException(nameof(outputStream)); } return WriteValue(outputStream, majorType, (long)value); } /// <summary>Writes a CBOR major type number and an integer 0 or /// greater associated with it to a data stream, where that integer is /// passed to this method as a 64-bit unsigned integer. This is a /// low-level method that is useful for implementing custom CBOR /// encoding methodologies. This method encodes the given major type /// and value in the shortest form allowed for the major /// type.</summary> /// <param name='outputStream'>A writable data stream.</param> /// <param name='majorType'>The CBOR major type to write. This is a /// number from 0 through 7 as follows. 0: integer 0 or greater; 1: /// negative integer; 2: byte string; 3: UTF-8 text string; 4: array; /// 5: map; 6: tag; 7: simple value. See RFC 7049 for details on these /// major types.</param> /// <param name='value'>An integer 0 or greater associated with the /// major type, as follows. 0: integer 0 or greater; 1: the negative /// integer's absolute value is 1 plus this number; 2: length in bytes /// of the byte string; 3: length in bytes of the UTF-8 text string; 4: /// number of items in the array; 5: number of key-value pairs in the /// map; 6: tag number; 7: simple value number, which must be in the /// interval [0, 23] or [32, 255].</param> /// <returns>The number of bytes ordered to be written to the data /// stream.</returns> /// <exception cref='ArgumentException'>The parameter <paramref /// name='majorType'/> is 7 and value is greater than 255.</exception> /// <exception cref='ArgumentNullException'>The parameter <paramref /// name='outputStream'/> is null.</exception> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public static int WriteValue( #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant Stream outputStream, int majorType, ulong value) { if (outputStream == null) { throw new ArgumentNullException(nameof(outputStream)); } if (value <= Int64.MaxValue) { return WriteValue(outputStream, majorType, (long)value); } else { if (majorType < 0) { throw new ArgumentException("majorType(" + majorType + ") is less than 0"); } if (majorType > 7) { throw new ArgumentException("majorType(" + majorType + ") is more than 7"); } if (majorType == 7) { throw new ArgumentException("majorType is 7 and value is greater" + "\u0020than 255"); } byte[] bytes = { (byte)(27 | (majorType << 5)), (byte)((value >> 56) & 0xff), (byte)((value >> 48) & 0xff), (byte)((value >> 40) & 0xff), (byte)((value >> 32) & 0xff), (byte)((value >> 24) & 0xff), (byte)((value >> 16) & 0xff), (byte)((value >> 8) & 0xff), (byte)(value & 0xff), }; outputStream.Write(bytes, 0, bytes.Length); return bytes.Length; } } private static EInteger DecimalToEInteger(decimal dec) { return ((EDecimal)dec).ToEInteger(); } /// <summary>Converts this object to a.NET decimal.</summary> /// <returns>The closest big integer to this object.</returns> /// <exception cref='InvalidOperationException'>This object does not /// represent a number (for this purpose, infinities and not-a-number /// or NaN values, but not CBORObject.Null, are considered /// numbers).</exception> /// <exception cref='OverflowException'>This object's value exceeds the /// range of a.NET decimal.</exception> public decimal AsDecimal() { return (this.ItemType == CBORObjectTypeInteger) ? ((decimal)(long)this.ThisItem) : ((this.HasOneTag(30) || this.HasOneTag(270)) ? (decimal)this.ToObject<ERational>() : (decimal)this.ToObject<EDecimal>()); } /// <summary>Converts this object to a 64-bit unsigned integer after /// discarding any fractional part, if any, from its value.</summary> /// <returns>A 64-bit unsigned integer.</returns> /// <exception cref='InvalidOperationException'>This object does not /// represent a number (for this purpose, infinities and not-a-number /// or NaN values, but not CBORObject.Null, are considered /// numbers).</exception> /// <exception cref='OverflowException'>This object's value, if /// converted to an integer by discarding its fractional part, is /// outside the range of a 64-bit unsigned integer.</exception> [CLSCompliant(false)] [Obsolete("Instead, use the following:" + "\u0020(cbor.AsNumber().ToUInt64Checked()), or .ToObject<ulong>().")] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public ulong AsUInt64() { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return this.AsUInt64Legacy(); } internal ulong AsUInt64Legacy() { EInteger bigint = this.ToObject<EInteger>(); if (bigint.Sign < 0 || bigint.GetUnsignedBitLengthAsEInteger().CompareTo(64) > 0) { throw new OverflowException("This object's value is out of range"); } return (ulong)bigint; } /// <summary>Writes an 8-bit signed integer in CBOR format to a data /// stream.</summary> /// <param name='value'>The parameter <paramref name='value'/> is an /// 8-bit signed integer.</param> /// <param name='stream'>A writable data stream.</param> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public static void Write(sbyte value, Stream stream) { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant Write((long)value, stream); } /// <summary>Writes a 64-bit unsigned integer in CBOR format to a data /// stream.</summary> /// <param name='value'>A 64-bit unsigned integer.</param> /// <param name='stream'>A writable data stream.</param> /// <exception cref='ArgumentNullException'>The parameter <paramref /// name='stream'/> is null.</exception> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public static void Write(ulong value, Stream stream) { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (value <= Int64.MaxValue) { Write((long)value, stream); } else { stream.WriteByte((byte)27); stream.WriteByte((byte)((value >> 56) & 0xff)); stream.WriteByte((byte)((value >> 48) & 0xff)); stream.WriteByte((byte)((value >> 40) & 0xff)); stream.WriteByte((byte)((value >> 32) & 0xff)); stream.WriteByte((byte)((value >> 24) & 0xff)); stream.WriteByte((byte)((value >> 16) & 0xff)); stream.WriteByte((byte)((value >> 8) & 0xff)); stream.WriteByte((byte)(value & 0xff)); } } /// <summary>Converts a.NET decimal to a CBOR object.</summary> /// <param name='value'>The parameter <paramref name='value'/> is a /// Decimal object.</param> /// <returns>A CBORObject object with the same value as the.NET /// decimal.</returns> public static CBORObject FromObject(decimal value) { return FromObject((EDecimal)value); } /// <summary>Writes a 32-bit unsigned integer in CBOR format to a data /// stream.</summary> /// <param name='value'>A 32-bit unsigned integer.</param> /// <param name='stream'>A writable data stream.</param> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public static void Write(uint value, Stream stream) { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant Write((ulong)value, stream); } /// <summary>Writes a 16-bit unsigned integer in CBOR format to a data /// stream.</summary> /// <param name='value'>A 16-bit unsigned integer.</param> /// <param name='stream'>A writable data stream.</param> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public static void Write(ushort value, Stream stream) { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant Write((ulong)value, stream); } /// <summary>Converts a signed 8-bit integer to a CBOR /// object.</summary> /// <param name='value'>The parameter <paramref name='value'/> is an /// 8-bit signed integer.</param> /// <returns>A CBORObject object.</returns> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public static CBORObject FromObject(sbyte value) { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return FromObject((long)value); } private static EInteger UInt64ToEInteger(ulong value) { var data = new byte[9]; ulong uvalue = value; data[0] = (byte)(uvalue & 0xff); data[1] = (byte)((uvalue >> 8) & 0xff); data[2] = (byte)((uvalue >> 16) & 0xff); data[3] = (byte)((uvalue >> 24) & 0xff); data[4] = (byte)((uvalue >> 32) & 0xff); data[5] = (byte)((uvalue >> 40) & 0xff); data[6] = (byte)((uvalue >> 48) & 0xff); data[7] = (byte)((uvalue >> 56) & 0xff); data[8] = (byte)0; return EInteger.FromBytes(data, true); } /// <summary>Converts a 64-bit unsigned integer to a CBOR /// object.</summary> /// <param name='value'>A 64-bit unsigned integer.</param> /// <returns>A CBORObject object.</returns> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public static CBORObject FromObject(ulong value) { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return CBORObject.FromObject(UInt64ToEInteger(value)); } /// <summary>Converts a 32-bit unsigned integer to a CBOR /// object.</summary> /// <param name='value'>A 32-bit unsigned integer.</param> /// <returns>A CBORObject object.</returns> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public static CBORObject FromObject(uint value) { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return FromObject((long)(Int64)value); } /// <summary>Converts a 16-bit unsigned integer to a CBOR /// object.</summary> /// <param name='value'>A 16-bit unsigned integer.</param> /// <returns>A CBORObject object.</returns> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public static CBORObject FromObject(ushort value) { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return FromObject((long)(Int64)value); } /// <summary>Generates a CBOR object from this one, but gives the /// resulting object a tag in addition to its existing tags (the new /// tag is made the outermost tag).</summary> /// <param name='tag'>A 64-bit integer that specifies a tag number. The /// tag number 55799 can be used to mark a "self-described CBOR" /// object. This document does not attempt to list all CBOR tags and /// their meanings. An up-to-date list can be found at the CBOR Tags /// registry maintained by the Internet Assigned Numbers Authority( /// <i>iana.org/assignments/cbor-tags</i> ).</param> /// <returns>A CBOR object with the same value as this one but given /// the tag <paramref name='tag'/> in addition to its existing tags /// (the new tag is made the outermost tag).</returns> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public CBORObject WithTag(ulong tag) { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return FromObjectAndTag(this, UInt64ToEInteger(tag)); } /// <summary>Generates a CBOR object from an arbitrary object and gives /// the resulting object a tag.</summary> /// <param name='o'>The parameter <paramref name='o'/> is an arbitrary /// object, which can be null. /// <para><b>NOTE:</b> For security reasons, whenever possible, an /// application should not base this parameter on user input or other /// externally supplied data unless the application limits this /// parameter's inputs to types specially handled by this method (such /// as <c>int</c> or <c>String</c> ) and/or to plain-old-data types /// (POCO or POJO types) within the control of the application. If the /// plain-old-data type references other data types, those types should /// likewise meet either criterion above.</para>.</param> /// <param name='tag'>A 64-bit integer that specifies a tag number. The /// tag number 55799 can be used to mark a "self-described CBOR" /// object. This document does not attempt to list all CBOR tags and /// their meanings. An up-to-date list can be found at the CBOR Tags /// registry maintained by the Internet Assigned Numbers Authority( /// <i>iana.org/assignments/cbor-tags</i> ).</param> /// <returns>A CBOR object where the object <paramref name='o'/> is /// converted to a CBOR object and given the tag <paramref name='tag'/> /// . If "valueOb" is null, returns a version of CBORObject.Null with /// the given tag.</returns> [CLSCompliant(false)] #pragma warning disable CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant public static CBORObject FromObjectAndTag(Object o, ulong tag) { #pragma warning restore CS3021 // Le type ou le membre n'a pas besoin d'un attribut CLSCompliant, car l'assembly n'a pas d'attribut CLSCompliant return FromObjectAndTag(o, UInt64ToEInteger(tag)); } /// <summary> /// <para>Converts this CBOR object to an object of an arbitrary type. /// See /// <see cref='PeterO.Cbor.CBORObject.ToObject(System.Type)'/> for /// further information.</para></summary> /// <typeparam name='T'>The type, class, or interface that this /// method's return value will belong to. <b>Note:</b> For security /// reasons, an application should not base this parameter on user /// input or other externally supplied data. Whenever possible, this /// parameter should be either a type specially handled by this method /// (such as <c>int</c> or <c>String</c> ) or a plain-old-data type /// (POCO or POJO type) within the control of the application. If the /// plain-old-data type references other data types, those types should /// likewise meet either criterion above.</typeparam> /// <returns>The converted object.</returns> /// <exception cref='NotSupportedException'>The given type "T", or this /// object's CBOR type, is not supported.</exception> public T ToObject<T>() { return (T)this.ToObject(typeof(T)); } /// <summary> /// <para>Converts this CBOR object to an object of an arbitrary type. /// See /// <see cref='PeterO.Cbor.CBORObject.ToObject(System.Type)'/> for /// further information.</para></summary> /// <param name='mapper'>This parameter controls which data types are /// eligible for Plain-Old-Data deserialization and includes custom /// converters from CBOR objects to certain data types.</param> /// <typeparam name='T'>The type, class, or interface that this /// method's return value will belong to. <b>Note:</b> For security /// reasons, an application should not base this parameter on user /// input or other externally supplied data. Whenever possible, this /// parameter should be either a type specially handled by this method /// (such as <c>int</c> or <c>String</c> ) or a plain-old-data type /// (POCO or POJO type) within the control of the application. If the /// plain-old-data type references other data types, those types should /// likewise meet either criterion above.</typeparam> /// <returns>The converted object.</returns> /// <exception cref='NotSupportedException'>The given type "T", or this /// object's CBOR type, is not supported.</exception> public T ToObject<T>(CBORTypeMapper mapper) { return (T)this.ToObject(typeof(T), mapper); } /// <summary> /// <para>Converts this CBOR object to an object of an arbitrary type. /// See /// <see cref='PeterO.Cbor.CBORObject.ToObject(System.Type)'/> for /// further information.</para></summary> /// <param name='options'>Specifies options for controlling /// deserialization of CBOR objects.</param> /// <typeparam name='T'>The type, class, or interface that this /// method's return value will belong to. <b>Note:</b> For security /// reasons, an application should not base this parameter on user /// input or other externally supplied data. Whenever possible, this /// parameter should be either a type specially handled by this method /// (such as <c>int</c> or <c>String</c> ) or a plain-old-data type /// (POCO or POJO type) within the control of the application. If the /// plain-old-data type references other data types, those types should /// likewise meet either criterion above.</typeparam> /// <returns>The converted object.</returns> /// <exception cref='NotSupportedException'>The given type "T", or this /// object's CBOR type, is not supported.</exception> public T ToObject<T>(PODOptions options) { return (T)this.ToObject(typeof(T), options); } /// <summary> /// <para>Converts this CBOR object to an object of an arbitrary type. /// See /// <see cref='PeterO.Cbor.CBORObject.ToObject(System.Type)'/> for /// further information.</para></summary> /// <param name='mapper'>This parameter controls which data types are /// eligible for Plain-Old-Data deserialization and includes custom /// converters from CBOR objects to certain data types.</param> /// <param name='options'>Specifies options for controlling /// deserialization of CBOR objects.</param> /// <typeparam name='T'>The type, class, or interface that this /// method's return value will belong to. <b>Note:</b> For security /// reasons, an application should not base this parameter on user /// input or other externally supplied data. Whenever possible, this /// parameter should be either a type specially handled by this method /// (such as <c>int</c> or <c>String</c> ) or a plain-old-data type /// (POCO or POJO type) within the control of the application. If the /// plain-old-data type references other data types, those types should /// likewise meet either criterion above.</typeparam> /// <returns>The converted object.</returns> /// <exception cref='NotSupportedException'>The given type "T", or this /// object's CBOR type, is not supported.</exception> public T ToObject<T>(CBORTypeMapper mapper, PODOptions options) { return (T)this.ToObject(typeof(T), mapper, options); } /// <summary>Adds two CBOR objects and returns their result.</summary> /// <param name='a'>The parameter <paramref name='a'/> is a CBOR /// object.</param> /// <param name='b'>The parameter <paramref name='b'/> is a CBOR /// object.</param> /// <returns>The sum of the two objects.</returns> [Obsolete("May be removed in the next major version. Consider converting" + "\u0020the objects to CBOR numbers and performing the operation" + "\u0020there.")] public static CBORObject operator +(CBORObject a, CBORObject b) { return Addition(a, b); } /// <summary>Subtracts a CBORObject object from a CBORObject /// object.</summary> /// <param name='a'>The parameter <paramref name='a'/> is a CBOR /// object.</param> /// <param name='b'>The parameter <paramref name='b'/> is a CBOR /// object.</param> /// <returns>The difference of the two objects.</returns> [Obsolete("May be removed in the next major version. Consider converting" + "\u0020the objects to CBOR numbers and performing the operation" + "\u0020there.")] public static CBORObject operator -(CBORObject a, CBORObject b) { return Subtract(a, b); } /// <summary>Multiplies a CBORObject object by the value of a /// CBORObject object.</summary> /// <param name='a'>The parameter <paramref name='a'/> is a CBOR /// object.</param> /// <param name='b'>The parameter <paramref name='b'/> is a CBOR /// object.</param> /// <returns>The product of the two numbers.</returns> [Obsolete("May be removed in the next major version. Consider converting" + "\u0020the objects to CBOR numbers and performing the operation" + "\u0020there.")] public static CBORObject operator *(CBORObject a, CBORObject b) { return Multiply(a, b); } /// <summary>Divides a CBORObject object by the value of a CBORObject /// object.</summary> /// <param name='a'>The parameter <paramref name='a'/> is a CBOR /// object.</param> /// <param name='b'>The parameter <paramref name='b'/> is a CBOR /// object.</param> /// <returns>The quotient of the two objects.</returns> [Obsolete("May be removed in the next major version. Consider converting" + "\u0020the objects to CBOR numbers and performing the operation" + "\u0020there.")] public static CBORObject operator /(CBORObject a, CBORObject b) { return Divide(a, b); } /// <summary>Finds the remainder that results when a CBORObject object /// is divided by the value of a CBORObject object.</summary> /// <param name='a'>The parameter <paramref name='a'/> is a CBOR /// object.</param> /// <param name='b'>The parameter <paramref name='b'/> is a CBOR /// object.</param> /// <returns>The remainder of the two numbers.</returns> [Obsolete("May be removed in the next major version. Consider converting" + "\u0020the objects to CBOR numbers and performing the operation" + "\u0020there.")] public static CBORObject operator %(CBORObject a, CBORObject b) { return Remainder(a, b); } } }
using System; using System.Runtime.InteropServices; using System.Security; using BulletSharp.Math; namespace BulletSharp { public enum ActivationState { Undefined = 0, ActiveTag = 1, IslandSleeping = 2, WantsDeactivation = 3, DisableDeactivation = 4, DisableSimulation = 5 } [Flags] public enum AnisotropicFrictionFlags { FrictionDisabled = 0, Friction = 1, RollingFriction = 2 } [Flags] public enum CollisionFlags { None = 0, StaticObject = 1, KinematicObject = 2, NoContactResponse = 4, CustomMaterialCallback = 8, CharacterObject = 16, DisableVisualizeObject = 32, DisableSpuCollisionProcessing = 64 } [Flags] public enum CollisionObjectTypes { None = 0, CollisionObject = 1, RigidBody = 2, GhostObject = 4, SoftBody = 8, HFFluid = 16, UserType = 32, FeatherstoneLink = 64 } public class CollisionObject : IDisposable { internal IntPtr _native; private bool _isDisposed; private BroadphaseProxy _broadphaseHandle; protected CollisionShape _collisionShape; internal static CollisionObject GetManaged(IntPtr obj) { if (obj == IntPtr.Zero) { return null; } IntPtr userPtr = btCollisionObject_getUserPointer(obj); if (userPtr != IntPtr.Zero) { return GCHandle.FromIntPtr(userPtr).Target as CollisionObject; } throw new InvalidOperationException("Unknown collision object!"); } internal CollisionObject(IntPtr native) { _native = native; GCHandle handle = GCHandle.Alloc(this, GCHandleType.Normal); btCollisionObject_setUserPointer(_native, GCHandle.ToIntPtr(handle)); } public CollisionObject() : this(btCollisionObject_new()) { } public void Activate() { btCollisionObject_activate(_native); } public void Activate(bool forceActivation) { btCollisionObject_activate2(_native, forceActivation); } public int CalculateSerializeBufferSize() { return btCollisionObject_calculateSerializeBufferSize(_native); } public bool CheckCollideWith(CollisionObject co) { return btCollisionObject_checkCollideWith(_native, co._native); } public bool CheckCollideWithOverride(CollisionObject co) { return btCollisionObject_checkCollideWithOverride(_native, co._native); } public void ForceActivationState(ActivationState newState) { btCollisionObject_forceActivationState(_native, newState); } public void GetWorldTransform(out Matrix transform) { btCollisionObject_getWorldTransform(_native, out transform); } public bool HasAnisotropicFriction() { return btCollisionObject_hasAnisotropicFriction(_native); } public bool HasAnisotropicFriction(AnisotropicFrictionFlags frictionMode) { return btCollisionObject_hasAnisotropicFriction2(_native, frictionMode); } public IntPtr InternalGetExtensionPointer() { return btCollisionObject_internalGetExtensionPointer(_native); } public void InternalSetExtensionPointer(IntPtr pointer) { btCollisionObject_internalSetExtensionPointer(_native, pointer); } public bool MergesSimulationIslands() { return btCollisionObject_mergesSimulationIslands(_native); } public string Serialize(IntPtr dataBuffer, Serializer serializer) { return Marshal.PtrToStringAnsi(btCollisionObject_serialize(_native, dataBuffer, serializer._native)); } public void SerializeSingleObject(Serializer serializer) { btCollisionObject_serializeSingleObject(_native, serializer._native); } public void SetAnisotropicFrictionRef(ref Vector3 anisotropicFriction) { btCollisionObject_setAnisotropicFriction(_native, ref anisotropicFriction); } public void SetAnisotropicFriction(Vector3 anisotropicFriction) { btCollisionObject_setAnisotropicFriction(_native, ref anisotropicFriction); } public void SetAnisotropicFrictionRef(ref Vector3 anisotropicFriction, AnisotropicFrictionFlags frictionMode) { btCollisionObject_setAnisotropicFriction2(_native, ref anisotropicFriction, frictionMode); } public void SetAnisotropicFriction(Vector3 anisotropicFriction, AnisotropicFrictionFlags frictionMode) { btCollisionObject_setAnisotropicFriction2(_native, ref anisotropicFriction, frictionMode); } public void SetIgnoreCollisionCheck(CollisionObject co, bool ignoreCollisionCheck) { btCollisionObject_setIgnoreCollisionCheck(_native, co._native, ignoreCollisionCheck); } public ActivationState ActivationState { get { return btCollisionObject_getActivationState(_native); } set { btCollisionObject_setActivationState(_native, value); } } public Vector3 AnisotropicFriction { get { Vector3 value; btCollisionObject_getAnisotropicFriction(_native, out value); return value; } set { btCollisionObject_setAnisotropicFriction(_native, ref value); } } public BroadphaseProxy BroadphaseHandle { get { return _broadphaseHandle; } set { btCollisionObject_setBroadphaseHandle(_native, (value != null) ? value._native : IntPtr.Zero); _broadphaseHandle = value; } } public float CcdMotionThreshold { get { return btCollisionObject_getCcdMotionThreshold(_native); } set { btCollisionObject_setCcdMotionThreshold(_native, value); } } public float CcdSquareMotionThreshold { get { return btCollisionObject_getCcdSquareMotionThreshold(_native); } } public float CcdSweptSphereRadius { get { return btCollisionObject_getCcdSweptSphereRadius(_native); } set { btCollisionObject_setCcdSweptSphereRadius(_native, value); } } public CollisionFlags CollisionFlags { get { return btCollisionObject_getCollisionFlags(_native); } set { btCollisionObject_setCollisionFlags(_native, value); } } public CollisionShape CollisionShape { get { return _collisionShape; } set { btCollisionObject_setCollisionShape(_native, value._native); _collisionShape = value; } } public int CompanionId { get { return btCollisionObject_getCompanionId(_native); } set { btCollisionObject_setCompanionId(_native, value); } } public float ContactProcessingThreshold { get { return btCollisionObject_getContactProcessingThreshold(_native); } set { btCollisionObject_setContactProcessingThreshold(_native, value); } } public float DeactivationTime { get { return btCollisionObject_getDeactivationTime(_native); } set { btCollisionObject_setDeactivationTime(_native, value); } } public float Friction { get { return btCollisionObject_getFriction(_native); } set { btCollisionObject_setFriction(_native, value); } } public bool HasContactResponse { get { return btCollisionObject_hasContactResponse(_native); } } public float HitFraction { get { return btCollisionObject_getHitFraction(_native); } set { btCollisionObject_setHitFraction(_native, value); } } public CollisionObjectTypes InternalType { get { return btCollisionObject_getInternalType(_native); } } public Vector3 InterpolationAngularVelocity { get { Vector3 value; btCollisionObject_getInterpolationAngularVelocity(_native, out value); return value; } set { btCollisionObject_setInterpolationAngularVelocity(_native, ref value); } } public Vector3 InterpolationLinearVelocity { get { Vector3 value; btCollisionObject_getInterpolationLinearVelocity(_native, out value); return value; } set { btCollisionObject_setInterpolationLinearVelocity(_native, ref value); } } public Matrix InterpolationWorldTransform { get { Matrix value; btCollisionObject_getInterpolationWorldTransform(_native, out value); return value; } set { btCollisionObject_setInterpolationWorldTransform(_native, ref value); } } public bool IsActive { get { return btCollisionObject_isActive(_native); } } public bool IsKinematicObject { get { return btCollisionObject_isKinematicObject(_native); } } public int IslandTag { get { return btCollisionObject_getIslandTag(_native); } set { btCollisionObject_setIslandTag(_native, value); } } public bool IsStaticObject { get { return btCollisionObject_isStaticObject(_native); } } public bool IsStaticOrKinematicObject { get { return btCollisionObject_isStaticOrKinematicObject(_native); } } public float Restitution { get { return btCollisionObject_getRestitution(_native); } set { btCollisionObject_setRestitution(_native, value); } } public float RollingFriction { get { return btCollisionObject_getRollingFriction(_native); } set { btCollisionObject_setRollingFriction(_native, value); } } public object UserObject { get; set; } public int UserIndex { get { return btCollisionObject_getUserIndex(_native); } set { btCollisionObject_setUserIndex(_native, value); } } public Matrix WorldTransform { get { Matrix value; btCollisionObject_getWorldTransform(_native, out value); return value; } set { btCollisionObject_setWorldTransform(_native, ref value); } } public override bool Equals(object obj) { CollisionObject colObj = obj as CollisionObject; if (colObj == null) { return false; } return _native == colObj._native; } public override int GetHashCode() { return _native.GetHashCode(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_isDisposed) { // Is the object added to a world? if (btCollisionObject_getBroadphaseHandle(_native) != IntPtr.Zero) { BroadphaseHandle = null; //System.Diagnostics.Debugger.Break(); return; } _isDisposed = true; IntPtr userPtr = btCollisionObject_getUserPointer(_native); GCHandle.FromIntPtr(userPtr).Free(); btCollisionObject_delete(_native); } } ~CollisionObject() { Dispose(false); } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btCollisionObject_new(); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_activate(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_activate2(IntPtr obj, bool forceActivation); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btCollisionObject_calculateSerializeBufferSize(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btCollisionObject_checkCollideWith(IntPtr obj, IntPtr co); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btCollisionObject_checkCollideWithOverride(IntPtr obj, IntPtr co); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_forceActivationState(IntPtr obj, ActivationState newState); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern ActivationState btCollisionObject_getActivationState(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_getAnisotropicFriction(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btCollisionObject_getBroadphaseHandle(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btCollisionObject_getCcdMotionThreshold(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btCollisionObject_getCcdSquareMotionThreshold(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btCollisionObject_getCcdSweptSphereRadius(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern CollisionFlags btCollisionObject_getCollisionFlags(IntPtr obj); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern IntPtr btCollisionObject_getCollisionShape(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btCollisionObject_getCompanionId(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btCollisionObject_getContactProcessingThreshold(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btCollisionObject_getDeactivationTime(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btCollisionObject_getFriction(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btCollisionObject_getHitFraction(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern CollisionObjectTypes btCollisionObject_getInternalType(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_getInterpolationAngularVelocity(IntPtr obj, [Out] out Vector3 angvel); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_getInterpolationLinearVelocity(IntPtr obj, [Out] out Vector3 linvel); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_getInterpolationWorldTransform(IntPtr obj, [Out] out Matrix trans); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btCollisionObject_getIslandTag(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btCollisionObject_getRestitution(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btCollisionObject_getRollingFriction(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btCollisionObject_getUserIndex(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btCollisionObject_getUserPointer(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_getWorldTransform(IntPtr obj, [Out] out Matrix worldTrans); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btCollisionObject_hasAnisotropicFriction(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btCollisionObject_hasAnisotropicFriction2(IntPtr obj, AnisotropicFrictionFlags frictionMode); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btCollisionObject_hasContactResponse(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btCollisionObject_internalGetExtensionPointer(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_internalSetExtensionPointer(IntPtr obj, IntPtr pointer); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btCollisionObject_isActive(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btCollisionObject_isKinematicObject(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btCollisionObject_isStaticObject(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btCollisionObject_isStaticOrKinematicObject(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] static extern bool btCollisionObject_mergesSimulationIslands(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btCollisionObject_serialize(IntPtr obj, IntPtr dataBuffer, IntPtr serializer); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_serializeSingleObject(IntPtr obj, IntPtr serializer); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setActivationState(IntPtr obj, ActivationState newState); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setAnisotropicFriction(IntPtr obj, [In] ref Vector3 anisotropicFriction); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setAnisotropicFriction2(IntPtr obj, [In] ref Vector3 anisotropicFriction, AnisotropicFrictionFlags frictionMode); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setBroadphaseHandle(IntPtr obj, IntPtr handle); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setCcdMotionThreshold(IntPtr obj, float ccdMotionThreshold); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setCcdSweptSphereRadius(IntPtr obj, float radius); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setCollisionFlags(IntPtr obj, CollisionFlags flags); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setCollisionShape(IntPtr obj, IntPtr collisionShape); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setCompanionId(IntPtr obj, int id); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setContactProcessingThreshold(IntPtr obj, float contactProcessingThreshold); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setDeactivationTime(IntPtr obj, float time); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setFriction(IntPtr obj, float frict); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setHitFraction(IntPtr obj, float hitFraction); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setIgnoreCollisionCheck(IntPtr obj, IntPtr co, bool ignoreCollisionCheck); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setInterpolationAngularVelocity(IntPtr obj, [In] ref Vector3 angvel); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setInterpolationLinearVelocity(IntPtr obj, [In] ref Vector3 linvel); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setInterpolationWorldTransform(IntPtr obj, [In] ref Matrix trans); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setIslandTag(IntPtr obj, int tag); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setRestitution(IntPtr obj, float rest); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setRollingFriction(IntPtr obj, float frict); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setUserIndex(IntPtr obj, int index); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setUserPointer(IntPtr obj, IntPtr userPointer); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_setWorldTransform(IntPtr obj, [In] ref Matrix worldTrans); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btCollisionObject_delete(IntPtr obj); } [StructLayout(LayoutKind.Sequential)] internal struct CollisionObjectFloatData { public IntPtr BroadphaseHandle; public IntPtr CollisionShape; public IntPtr RootCollisionShape; public IntPtr Name; public TransformFloatData WorldTransform; public TransformFloatData InterpolationWorldTransform; public Vector3FloatData InterpolationLinearVelocity; public Vector3FloatData InterpolationAngularVelocity; public Vector3FloatData AnisotropicFriction; public float ContactProcessingThreshold; public float DeactivationTime; public float Friction; public float RollingFriction; public float Restitution; public float HitFraction; public float CcdSweptSphereRadius; public float CcdMotionThreshold; public int HasAnisotropicFriction; public int CollisionFlags; public int IslandTag1; public int CompanionId; public int ActivationState1; public int InternalType; public int CheckCollideWith; public int Padding; public static int Offset(string fieldName) { return Marshal.OffsetOf(typeof(CollisionObjectFloatData), fieldName).ToInt32(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Yad2.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
//------------------------------------------------------------------------------ // <copyright file="ResXResourceWriter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ #if SYSTEM_WEB // See DevDiv 9030 namespace System.PrivateResources { #else namespace System.Resources { #endif using System.Diagnostics; using System.Reflection; using System; using System.Windows.Forms; using Microsoft.Win32; using System.Drawing; using System.IO; using System.Text; using System.ComponentModel; using System.Collections; using System.Resources; using System.Xml; using System.Runtime.Serialization; using System.Diagnostics.CodeAnalysis; #if SYSTEM_WEB using System.Web; // This is needed to access the SR resource strings #endif /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter"]/*' /> /// <devdoc> /// ResX resource writer. See the text in "ResourceSchema" for more /// information. /// </devdoc> [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.InheritanceDemand, Name="FullTrust")] [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name="FullTrust")] #if SYSTEM_WEB internal class ResXResourceWriter : IResourceWriter { #else public class ResXResourceWriter : IResourceWriter { #endif internal const string TypeStr = "type"; internal const string NameStr = "name"; internal const string DataStr = "data"; internal const string MetadataStr = "metadata"; internal const string MimeTypeStr = "mimetype"; internal const string ValueStr = "value"; internal const string ResHeaderStr = "resheader"; internal const string VersionStr = "version"; internal const string ResMimeTypeStr = "resmimetype"; internal const string ReaderStr = "reader"; internal const string WriterStr = "writer"; internal const string CommentStr = "comment"; internal const string AssemblyStr ="assembly"; internal const string AliasStr= "alias" ; private Hashtable cachedAliases; private static TraceSwitch ResValueProviderSwitch = new TraceSwitch("ResX", "Debug the resource value provider"); // internal static readonly string Beta2CompatSerializedObjectMimeType = "text/microsoft-urt/psuedoml-serialized/base64"; // These two "compat" mimetypes are here. In Beta 2 and RTM we used the term "URT" // internally to refer to parts of the .NET Framework. Since these references // will be in Beta 2 ResX files, and RTM ResX files for customers that had // early access to releases, we don't want to break that. We will read // and parse these types correctly in version 1.0, but will always // write out the new version. So, opening and editing a ResX file in VS will // update it to the new types. // internal static readonly string CompatBinSerializedObjectMimeType = "text/microsoft-urt/binary-serialized/base64"; internal static readonly string CompatSoapSerializedObjectMimeType = "text/microsoft-urt/soap-serialized/base64"; /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.BinSerializedObjectMimeType"]/*' /> /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly string BinSerializedObjectMimeType = "application/x-microsoft.net.object.binary.base64"; /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.SoapSerializedObjectMimeType"]/*' /> /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly string SoapSerializedObjectMimeType = "application/x-microsoft.net.object.soap.base64"; /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.DefaultSerializedObjectMimeType"]/*' /> /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly string DefaultSerializedObjectMimeType = BinSerializedObjectMimeType; /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.ByteArraySerializedObjectMimeType"]/*' /> /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly string ByteArraySerializedObjectMimeType = "application/x-microsoft.net.object.bytearray.base64"; /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.ResMimeType"]/*' /> /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly string ResMimeType = "text/microsoft-resx"; /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.Version"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly string Version = "2.0"; /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.ResourceSchema"]/*' /> /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static readonly string ResourceSchema = @" <!-- Microsoft ResX Schema Version " + Version + @" The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name=""resmimetype"">text/microsoft-resx</resheader> <resheader name=""version"">" + Version + @"</resheader> <resheader name=""reader"">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name=""writer"">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name=""Name1""><value>this is my long string</value><comment>this is a comment</comment></data> <data name=""Color1"" type=""System.Drawing.Color, System.Drawing"">Blue</data> <data name=""Bitmap1"" mimetype=""" + BinSerializedObjectMimeType + @"""> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name=""Icon1"" type=""System.Drawing.Icon, System.Drawing"" mimetype=""" + ByteArraySerializedObjectMimeType + @"""> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of ""resheader"" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - " + BinSerializedObjectMimeType + @" is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: " + BinSerializedObjectMimeType + @" value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: " + SoapSerializedObjectMimeType + @" value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: " + ByteArraySerializedObjectMimeType + @" value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id=""root"" xmlns="""" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xsd:import namespace=""http://www.w3.org/XML/1998/namespace""/> <xsd:element name=""root"" msdata:IsDataSet=""true""> <xsd:complexType> <xsd:choice maxOccurs=""unbounded""> <xsd:element name=""metadata""> <xsd:complexType> <xsd:sequence> <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0""/> </xsd:sequence> <xsd:attribute name=""name"" use=""required"" type=""xsd:string""/> <xsd:attribute name=""type"" type=""xsd:string""/> <xsd:attribute name=""mimetype"" type=""xsd:string""/> <xsd:attribute ref=""xml:space""/> </xsd:complexType> </xsd:element> <xsd:element name=""assembly""> <xsd:complexType> <xsd:attribute name=""alias"" type=""xsd:string""/> <xsd:attribute name=""name"" type=""xsd:string""/> </xsd:complexType> </xsd:element> <xsd:element name=""data""> <xsd:complexType> <xsd:sequence> <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" /> <xsd:element name=""comment"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""2"" /> </xsd:sequence> <xsd:attribute name=""name"" type=""xsd:string"" use=""required"" msdata:Ordinal=""1"" /> <xsd:attribute name=""type"" type=""xsd:string"" msdata:Ordinal=""3"" /> <xsd:attribute name=""mimetype"" type=""xsd:string"" msdata:Ordinal=""4"" /> <xsd:attribute ref=""xml:space""/> </xsd:complexType> </xsd:element> <xsd:element name=""resheader""> <xsd:complexType> <xsd:sequence> <xsd:element name=""value"" type=""xsd:string"" minOccurs=""0"" msdata:Ordinal=""1"" /> </xsd:sequence> <xsd:attribute name=""name"" type=""xsd:string"" use=""required"" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> "; IFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter (); string fileName; Stream stream; TextWriter textWriter; XmlTextWriter xmlTextWriter; string basePath; bool hasBeenSaved; bool initialized; private Func<Type, string> typeNameConverter; // no public property to be consistent with ResXDataNode class. /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.BasePath"]/*' /> /// <devdoc> /// Base Path for ResXFileRefs. /// </devdoc> public string BasePath { get { return basePath; } set { basePath = value; } } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.ResXResourceWriter"]/*' /> /// <devdoc> /// Creates a new ResXResourceWriter that will write to the specified file. /// </devdoc> public ResXResourceWriter(string fileName) { this.fileName = fileName; } public ResXResourceWriter(string fileName, Func<Type, string> typeNameConverter) { this.fileName = fileName; this.typeNameConverter = typeNameConverter; } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.ResXResourceWriter1"]/*' /> /// <devdoc> /// Creates a new ResXResourceWriter that will write to the specified stream. /// </devdoc> public ResXResourceWriter(Stream stream) { this.stream = stream; } public ResXResourceWriter(Stream stream, Func<Type, string> typeNameConverter) { this.stream = stream; this.typeNameConverter = typeNameConverter; } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.ResXResourceWriter2"]/*' /> /// <devdoc> /// Creates a new ResXResourceWriter that will write to the specified TextWriter. /// </devdoc> public ResXResourceWriter(TextWriter textWriter) { this.textWriter = textWriter; } public ResXResourceWriter(TextWriter textWriter, Func<Type, string> typeNameConverter) { this.textWriter = textWriter; this.typeNameConverter = typeNameConverter; } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.Finalize"]/*' /> ~ResXResourceWriter() { Dispose(false); } private void InitializeWriter() { if (xmlTextWriter == null) { // bool writeHeaderHack = false; if (textWriter != null) { textWriter.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); writeHeaderHack = true; xmlTextWriter = new XmlTextWriter(textWriter); } else if (stream != null) { xmlTextWriter = new XmlTextWriter(stream, System.Text.Encoding.UTF8); } else { Debug.Assert(fileName != null, "Nothing to output to"); xmlTextWriter = new XmlTextWriter(fileName, System.Text.Encoding.UTF8); } xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.Indentation = 2; if (!writeHeaderHack) { xmlTextWriter.WriteStartDocument(); // writes <?xml version="1.0" encoding="utf-8"?> } } else { xmlTextWriter.WriteStartDocument(); } xmlTextWriter.WriteStartElement("root"); XmlTextReader reader = new XmlTextReader(new StringReader(ResourceSchema)); reader.WhitespaceHandling = WhitespaceHandling.None; xmlTextWriter.WriteNode(reader, true); xmlTextWriter.WriteStartElement(ResHeaderStr); { xmlTextWriter.WriteAttributeString(NameStr, ResMimeTypeStr); xmlTextWriter.WriteStartElement(ValueStr); { xmlTextWriter.WriteString(ResMimeType); } xmlTextWriter.WriteEndElement(); } xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteStartElement(ResHeaderStr); { xmlTextWriter.WriteAttributeString(NameStr, VersionStr); xmlTextWriter.WriteStartElement(ValueStr); { xmlTextWriter.WriteString(Version); } xmlTextWriter.WriteEndElement(); } xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteStartElement(ResHeaderStr); { xmlTextWriter.WriteAttributeString(NameStr, ReaderStr); xmlTextWriter.WriteStartElement(ValueStr); { xmlTextWriter.WriteString(MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXResourceReader), this.typeNameConverter)); } xmlTextWriter.WriteEndElement(); } xmlTextWriter.WriteEndElement(); xmlTextWriter.WriteStartElement(ResHeaderStr); { xmlTextWriter.WriteAttributeString(NameStr, WriterStr); xmlTextWriter.WriteStartElement(ValueStr); { xmlTextWriter.WriteString(MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXResourceWriter), this.typeNameConverter)); } xmlTextWriter.WriteEndElement(); } xmlTextWriter.WriteEndElement(); initialized = true; } private XmlWriter Writer { get { if (!initialized) { InitializeWriter(); } return xmlTextWriter; } } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.AddAlias"]/*' /> /// <devdoc> /// Adds aliases to the resource file... /// </devdoc> public virtual void AddAlias(string aliasName, AssemblyName assemblyName) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } if (cachedAliases == null) { cachedAliases = new Hashtable(); } cachedAliases[assemblyName.FullName] = aliasName; } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.AddMetadata"]/*' /> /// <devdoc> /// Adds the given value to the collection of metadata. These name/value pairs /// will be emitted to the <metadata> elements in the .resx file. /// </devdoc> public void AddMetadata(string name, byte[] value) { AddDataRow(MetadataStr, name, value); } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.AddMetadata1"]/*' /> /// <devdoc> /// Adds the given value to the collection of metadata. These name/value pairs /// will be emitted to the <metadata> elements in the .resx file. /// </devdoc> public void AddMetadata(string name, string value) { AddDataRow(MetadataStr, name, value); } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.AddMetadata2"]/*' /> /// <devdoc> /// Adds the given value to the collection of metadata. These name/value pairs /// will be emitted to the <metadata> elements in the .resx file. /// </devdoc> public void AddMetadata(string name, object value) { AddDataRow(MetadataStr, name, value); } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.AddResource"]/*' /> /// <devdoc> /// Adds a blob resource to the resources. /// </devdoc> // NOTE: Part of IResourceWriter - not protected by class level LinkDemand. public void AddResource(string name, byte[] value) { AddDataRow(DataStr, name, value); } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.AddResource1"]/*' /> /// <devdoc> /// Adds a resource to the resources. If the resource is a string, /// it will be saved that way, otherwise it will be serialized /// and stored as in binary. /// </devdoc> // NOTE: Part of IResourceWriter - not protected by class level LinkDemand. public void AddResource(string name, object value) { if (value is ResXDataNode) { AddResource((ResXDataNode)value); } else { AddDataRow(DataStr, name, value); } } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.AddResource2"]/*' /> /// <devdoc> /// Adds a string resource to the resources. /// </devdoc> // NOTE: Part of IResourceWriter - not protected by class level LinkDemand. public void AddResource(string name, string value) { AddDataRow(DataStr, name, value); } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.AddResource3"]/*' /> /// <devdoc> /// Adds a string resource to the resources. /// </devdoc> public void AddResource(ResXDataNode node) { // we're modifying the node as we're adding it to the resxwriter // this is BAD, so we clone it. adding it to a writer doesnt change it // we're messing with a copy ResXDataNode nodeClone = node.DeepClone(); ResXFileRef fileRef = nodeClone.FileRef; string modifiedBasePath = BasePath; if (!String.IsNullOrEmpty(modifiedBasePath)) { if (!(modifiedBasePath.EndsWith("\\"))) { modifiedBasePath += "\\"; } if (fileRef != null) { fileRef.MakeFilePathRelative(modifiedBasePath); } } DataNodeInfo info = nodeClone.GetDataNodeInfo(); AddDataRow(DataStr, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment); } /// <devdoc> /// Adds a blob resource to the resources. /// </devdoc> private void AddDataRow(string elementName, string name, byte[] value) { AddDataRow(elementName, name, ToBase64WrappedString(value), TypeNameWithAssembly(typeof(byte[])), null, null); } /// <devdoc> /// Adds a resource to the resources. If the resource is a string, /// it will be saved that way, otherwise it will be serialized /// and stored as in binary. /// </devdoc> private void AddDataRow(string elementName, string name, object value) { Debug.WriteLineIf(ResValueProviderSwitch.TraceVerbose, " resx: adding resource " + name); if (value is string) { AddDataRow(elementName, name, (string)value); } else if (value is byte[]) { AddDataRow(elementName, name, (byte[])value); } else if(value is ResXFileRef) { ResXFileRef fileRef = (ResXFileRef)value; ResXDataNode node = new ResXDataNode(name, fileRef, this.typeNameConverter); if (fileRef != null) { fileRef.MakeFilePathRelative(BasePath); } DataNodeInfo info = node.GetDataNodeInfo(); AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment); } else { ResXDataNode node = new ResXDataNode(name, value, this.typeNameConverter); DataNodeInfo info = node.GetDataNodeInfo(); AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment); } } /// <devdoc> /// Adds a string resource to the resources. /// </devdoc> private void AddDataRow(string elementName, string name, string value) { if(value == null) { // if it's a null string, set it here as a resxnullref AddDataRow(elementName, name, value, MultitargetUtil.GetAssemblyQualifiedName(typeof(ResXNullRef), this.typeNameConverter), null, null); } else { AddDataRow(elementName, name, value, null, null, null); } } /// <devdoc> /// Adds a new row to the Resources table. This helper is used because /// we want to always late bind to the columns for greater flexibility. /// </devdoc> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void AddDataRow(string elementName, string name, string value, string type, string mimeType, string comment) { if (hasBeenSaved) throw new InvalidOperationException(SR.GetString(SR.ResXResourceWriterSaved)); string alias = null; if (!string.IsNullOrEmpty(type) && elementName == DataStr) { string assemblyName = GetFullName(type); if(string.IsNullOrEmpty(assemblyName)) { try { Type typeObject = Type.GetType(type); if(typeObject == typeof(string)) { type = null; } else if(typeObject != null) { assemblyName = GetFullName(MultitargetUtil.GetAssemblyQualifiedName(typeObject, this.typeNameConverter)); alias = GetAliasFromName(new AssemblyName(assemblyName)); } } catch { } } else { alias = GetAliasFromName(new AssemblyName(GetFullName(type))); } //AddAssemblyRow(AssemblyStr, alias, GetFullName(type)); } Writer.WriteStartElement(elementName); { Writer.WriteAttributeString(NameStr, name); if (!string.IsNullOrEmpty(alias) && !string.IsNullOrEmpty(type) && elementName == DataStr) { // CHANGE: we still output version information. This might have // to change in 3.2 string typeName = GetTypeName(type); string typeValue = typeName + ", " + alias; Writer.WriteAttributeString(TypeStr, typeValue); } else { if (type != null) { Writer.WriteAttributeString(TypeStr, type); } } if (mimeType != null) { Writer.WriteAttributeString(MimeTypeStr, mimeType); } if((type == null && mimeType == null) || (type != null && type.StartsWith("System.Char", StringComparison.Ordinal))) { Writer.WriteAttributeString("xml", "space", null, "preserve"); } Writer.WriteStartElement(ValueStr); { if(!string.IsNullOrEmpty(value)) { Writer.WriteString(value); } } Writer.WriteEndElement(); if(!string.IsNullOrEmpty(comment)) { Writer.WriteStartElement(CommentStr); { Writer.WriteString(comment); } Writer.WriteEndElement(); } } Writer.WriteEndElement(); } private void AddAssemblyRow(string elementName, string alias, string name) { Writer.WriteStartElement(elementName); { if (!string.IsNullOrEmpty(alias)) { Writer.WriteAttributeString(AliasStr, alias); } if (!string.IsNullOrEmpty(name)) { Writer.WriteAttributeString(NameStr, name); } //Writer.WriteEndElement(); } Writer.WriteEndElement(); } private string GetAliasFromName(AssemblyName assemblyName) { if (cachedAliases == null) { cachedAliases = new Hashtable(); } string alias = (string) cachedAliases[assemblyName.FullName]; if (string.IsNullOrEmpty(alias)) { alias = assemblyName.Name; AddAlias(alias, assemblyName); AddAssemblyRow(AssemblyStr, alias, assemblyName.FullName); } return alias; } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.Close"]/*' /> /// <devdoc> /// Closes any files or streams locked by the writer. /// </devdoc> // NOTE: Part of IResourceWriter - not protected by class level LinkDemand. public void Close() { Dispose(); } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.Dispose"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> // NOTE: Part of IDisposable - not protected by class level LinkDemand. public virtual void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.Dispose1"]/*' /> protected virtual void Dispose(bool disposing) { if (disposing) { if (!hasBeenSaved) { Generate(); } if (xmlTextWriter != null) { xmlTextWriter.Close(); xmlTextWriter = null; } if (stream != null) { stream.Close(); stream = null; } if (textWriter != null) { textWriter.Close(); textWriter = null; } } } private string GetTypeName(string typeName) { int indexStart = typeName.IndexOf(","); return ((indexStart == -1) ? typeName : typeName.Substring(0, indexStart)); } private string GetFullName(string typeName) { int indexStart = typeName.IndexOf(","); if(indexStart == -1) return null; return typeName.Substring(indexStart + 2); } #if UNUSED private string GetSimpleName(string typeName) { int indexStart = typeName.IndexOf(","); int indexEnd = typeName.IndexOf(",", indexStart + 1); return typeName.Substring(indexStart + 2, indexEnd - indexStart - 3); } static string StripVersionInformation(string typeName) { int indexStart = typeName.IndexOf(" Version="); if(indexStart ==-1) indexStart = typeName.IndexOf("Version="); if(indexStart ==-1) indexStart = typeName.IndexOf("version="); int indexEnd = -1; string result = typeName; if(indexStart != -1) { // foudn version indexEnd = typeName.IndexOf(",", indexStart); if(indexEnd != -1) { result = typeName.Remove(indexStart, indexEnd-indexStart+1); } } return result; } #endif static string ToBase64WrappedString(byte[] data) { const int lineWrap = 80; const string crlf = "\r\n"; const string prefix = " "; string raw = Convert.ToBase64String(data); if (raw.Length > lineWrap) { StringBuilder output = new StringBuilder(raw.Length + (raw.Length / lineWrap) * 3); // word wrap on lineWrap chars, \r\n int current = 0; for (; current < raw.Length - lineWrap; current+=lineWrap) { output.Append(crlf); output.Append(prefix); output.Append(raw, current, lineWrap); } output.Append(crlf); output.Append(prefix); output.Append(raw, current, raw.Length - current); output.Append(crlf); return output.ToString(); } else { return raw; } } private string TypeNameWithAssembly(Type type) { // string result = MultitargetUtil.GetAssemblyQualifiedName(type, this.typeNameConverter); return result; } /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.Generate"]/*' /> /// <devdoc> /// Writes the resources out to the file or stream. /// </devdoc> // NOTE: Part of IResourceWriter - not protected by class level LinkDemand. public void Generate() { if (hasBeenSaved) throw new InvalidOperationException(SR.GetString(SR.ResXResourceWriterSaved)); hasBeenSaved = true; Debug.WriteLineIf(ResValueProviderSwitch.TraceVerbose, "writing XML"); Writer.WriteEndElement(); Writer.Flush(); Debug.WriteLineIf(ResValueProviderSwitch.TraceVerbose, "done"); } } }
// 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.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.Add(System.Object,System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IList.set_Item(System.Int32,System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Scope = "member", Target = "System.ComponentModel.PropertyDescriptorCollection.System.Collections.IDictionary.set_Item(System.Object,System.Object):System.Void")] [assembly: SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields", Scope = "type", Target = "System.ComponentModel.PropertyDescriptorCollection")] namespace System.ComponentModel { /// <summary> /// Represents a collection of properties. /// </summary> public class PropertyDescriptorCollection : ICollection, IList, IDictionary { /// <summary> /// An empty PropertyDescriptorCollection that can used instead of creating a new one with no items. /// </summary> [SuppressMessage("Microsoft.Security", "CA2112:SecuredTypesShouldNotExposeFields")] public static readonly PropertyDescriptorCollection Empty = new PropertyDescriptorCollection(null, true); private IDictionary _cachedFoundProperties; private bool _cachedIgnoreCase; private PropertyDescriptor[] _properties; private readonly string[] _namedSort; private readonly IComparer _comparer; private bool _propsOwned; private bool _needSort; private readonly bool _readOnly; private readonly object _internalSyncObject = new object(); /// <summary> /// Initializes a new instance of the <see cref='System.ComponentModel.PropertyDescriptorCollection'/> /// class. /// </summary> public PropertyDescriptorCollection(PropertyDescriptor[] properties) { if (properties == null) { _properties = Array.Empty<PropertyDescriptor>(); Count = 0; } else { _properties = properties; Count = properties.Length; } _propsOwned = true; } /// <summary> /// Initializes a new instance of a property descriptor collection, and allows you to mark the /// collection as read-only so it cannot be modified. /// </summary> public PropertyDescriptorCollection(PropertyDescriptor[] properties, bool readOnly) : this(properties) { _readOnly = readOnly; } private PropertyDescriptorCollection(PropertyDescriptor[] properties, int propCount, string[] namedSort, IComparer comparer) { _propsOwned = false; if (namedSort != null) { _namedSort = (string[])namedSort.Clone(); } _comparer = comparer; _properties = properties; Count = propCount; _needSort = true; } /// <summary> /// Gets the number of property descriptors in the collection. /// </summary> public int Count { get; private set; } /// <summary> /// Gets the property with the specified index number. /// </summary> public virtual PropertyDescriptor this[int index] { get { if (index >= Count) { throw new IndexOutOfRangeException(); } EnsurePropsOwned(); return _properties[index]; } } /// <summary> /// Gets the property with the specified name. /// </summary> public virtual PropertyDescriptor this[string name] => Find(name, false); public int Add(PropertyDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } EnsureSize(Count + 1); _properties[Count++] = value; return Count - 1; } public void Clear() { if (_readOnly) { throw new NotSupportedException(); } Count = 0; _cachedFoundProperties = null; } public bool Contains(PropertyDescriptor value) => IndexOf(value) >= 0; public void CopyTo(Array array, int index) { EnsurePropsOwned(); Array.Copy(_properties, 0, array, index, Count); } private void EnsurePropsOwned() { if (!_propsOwned) { _propsOwned = true; if (_properties != null) { PropertyDescriptor[] newProps = new PropertyDescriptor[Count]; Array.Copy(_properties, 0, newProps, 0, Count); _properties = newProps; } } if (_needSort) { _needSort = false; InternalSort(_namedSort); } } private void EnsureSize(int sizeNeeded) { if (sizeNeeded <= _properties.Length) { return; } if (_properties.Length == 0) { Count = 0; _properties = new PropertyDescriptor[sizeNeeded]; return; } EnsurePropsOwned(); int newSize = Math.Max(sizeNeeded, _properties.Length * 2); PropertyDescriptor[] newProps = new PropertyDescriptor[newSize]; Array.Copy(_properties, 0, newProps, 0, Count); _properties = newProps; } /// <summary> /// Gets the description of the property with the specified name. /// </summary> public virtual PropertyDescriptor Find(string name, bool ignoreCase) { lock (_internalSyncObject) { PropertyDescriptor p = null; if (_cachedFoundProperties == null || _cachedIgnoreCase != ignoreCase) { _cachedIgnoreCase = ignoreCase; if (ignoreCase) { _cachedFoundProperties = new Hashtable(StringComparer.OrdinalIgnoreCase); } else { _cachedFoundProperties = new Hashtable(); } } // first try to find it in the cache // object cached = _cachedFoundProperties[name]; if (cached != null) { return (PropertyDescriptor)cached; } // Now start walking from where we last left off, filling // the cache as we go. // for (int i = 0; i < Count; i++) { if (ignoreCase) { if (string.Equals(_properties[i].Name, name, StringComparison.OrdinalIgnoreCase)) { _cachedFoundProperties[name] = _properties[i]; p = _properties[i]; break; } } else { if (_properties[i].Name.Equals(name)) { _cachedFoundProperties[name] = _properties[i]; p = _properties[i]; break; } } } return p; } } public int IndexOf(PropertyDescriptor value) => Array.IndexOf(_properties, value, 0, Count); public void Insert(int index, PropertyDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } EnsureSize(Count + 1); if (index < Count) { Array.Copy(_properties, index, _properties, index + 1, Count - index); } _properties[index] = value; Count++; } public void Remove(PropertyDescriptor value) { if (_readOnly) { throw new NotSupportedException(); } int index = IndexOf(value); if (index != -1) { RemoveAt(index); } } public void RemoveAt(int index) { if (_readOnly) { throw new NotSupportedException(); } if (index < Count - 1) { Array.Copy(_properties, index + 1, _properties, index, Count - index - 1); } _properties[Count - 1] = null; Count--; } /// <summary> /// Sorts the members of this PropertyDescriptorCollection, using the default sort for this collection, /// which is usually alphabetical. /// </summary> public virtual PropertyDescriptorCollection Sort() { return new PropertyDescriptorCollection(_properties, Count, _namedSort, _comparer); } /// <summary> /// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </summary> public virtual PropertyDescriptorCollection Sort(string[] names) { return new PropertyDescriptorCollection(_properties, Count, names, _comparer); } /// <summary> /// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </summary> public virtual PropertyDescriptorCollection Sort(string[] names, IComparer comparer) { return new PropertyDescriptorCollection(_properties, Count, names, comparer); } /// <summary> /// Sorts the members of this PropertyDescriptorCollection, using the specified IComparer to compare, /// the PropertyDescriptors contained in the collection. /// </summary> public virtual PropertyDescriptorCollection Sort(IComparer comparer) { return new PropertyDescriptorCollection(_properties, Count, _namedSort, comparer); } /// <summary> /// Sorts the members of this PropertyDescriptorCollection. Any specified NamedSort arguments will /// be applied first, followed by sort using the specified IComparer. /// </summary> protected void InternalSort(string[] names) { if (_properties.Length == 0) { return; } InternalSort(_comparer); if (names != null && names.Length > 0) { List<PropertyDescriptor> propList = new List<PropertyDescriptor>(_properties); int foundCount = 0; int propCount = _properties.Length; for (int i = 0; i < names.Length; i++) { for (int j = 0; j < propCount; j++) { PropertyDescriptor currentProp = propList[j]; // Found a matching property. Here, we add it to our array. We also // mark it as null in our array list so we don't add it twice later. // if (currentProp != null && currentProp.Name.Equals(names[i])) { _properties[foundCount++] = currentProp; propList[j] = null; break; } } } // At this point we have filled in the first "foundCount" number of propeties, one for each // name in our name array. If a name didn't match, then it is ignored. Next, we must fill // in the rest of the properties. We now have a sparse array containing the remainder, so // it's easy. // for (int i = 0; i < propCount; i++) { if (propList[i] != null) { _properties[foundCount++] = propList[i]; } } Debug.Assert(foundCount == propCount, "We did not completely fill our property array"); } } /// <summary> /// Sorts the members of this PropertyDescriptorCollection using the specified IComparer. /// </summary> protected void InternalSort(IComparer sorter) { if (sorter == null) { TypeDescriptor.SortDescriptorArray(this); } else { Array.Sort(_properties, sorter); } } /// <summary> /// Gets an enumerator for this <see cref='System.ComponentModel.PropertyDescriptorCollection'/>. /// </summary> public virtual IEnumerator GetEnumerator() { EnsurePropsOwned(); // we can only return an enumerator on the props we actually have... if (_properties.Length != Count) { PropertyDescriptor[] enumProps = new PropertyDescriptor[Count]; Array.Copy(_properties, 0, enumProps, 0, Count); return enumProps.GetEnumerator(); } return _properties.GetEnumerator(); } bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => null; int ICollection.Count => Count; void IList.Clear() => Clear(); void IDictionary.Clear() => Clear(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); void IList.RemoveAt(int index) => RemoveAt(index); void IDictionary.Add(object key, object value) { if (!(value is PropertyDescriptor newProp)) { throw new ArgumentException(nameof(value)); } Add(newProp); } bool IDictionary.Contains(object key) { if (key is string) { return this[(string)key] != null; } return false; } IDictionaryEnumerator IDictionary.GetEnumerator() => new PropertyDescriptorEnumerator(this); bool IDictionary.IsFixedSize => _readOnly; bool IDictionary.IsReadOnly => _readOnly; object IDictionary.this[object key] { get { if (key is string) { return this[(string)key]; } return null; } set { if (_readOnly) { throw new NotSupportedException(); } if (value != null && !(value is PropertyDescriptor)) { throw new ArgumentException(nameof(value)); } int index = -1; if (key is int) { index = (int)key; if (index < 0 || index >= Count) { throw new IndexOutOfRangeException(); } } else if (key is string) { for (int i = 0; i < Count; i++) { if (_properties[i].Name.Equals((string)key)) { index = i; break; } } } else { throw new ArgumentException(nameof(key)); } if (index == -1) { Add((PropertyDescriptor)value); } else { EnsurePropsOwned(); _properties[index] = (PropertyDescriptor)value; if (_cachedFoundProperties != null && key is string) { _cachedFoundProperties[key] = value; } } } } ICollection IDictionary.Keys { get { string[] keys = new string[Count]; for (int i = 0; i < Count; i++) { keys[i] = _properties[i].Name; } return keys; } } ICollection IDictionary.Values { get { // We can only return an enumerator on the props we actually have. if (_properties.Length != Count) { PropertyDescriptor[] newProps = new PropertyDescriptor[Count]; Array.Copy(_properties, 0, newProps, 0, Count); return newProps; } else { return (ICollection)_properties.Clone(); } } } void IDictionary.Remove(object key) { if (key is string) { PropertyDescriptor pd = this[(string)key]; if (pd != null) { ((IList)this).Remove(pd); } } } int IList.Add(object value) => Add((PropertyDescriptor)value); bool IList.Contains(object value) => Contains((PropertyDescriptor)value); int IList.IndexOf(object value) => IndexOf((PropertyDescriptor)value); void IList.Insert(int index, object value) => Insert(index, (PropertyDescriptor)value); bool IList.IsReadOnly => _readOnly; bool IList.IsFixedSize => _readOnly; void IList.Remove(object value) => Remove((PropertyDescriptor)value); object IList.this[int index] { get => this[index]; set { if (_readOnly) { throw new NotSupportedException(); } if (index >= Count) { throw new IndexOutOfRangeException(); } if (value != null && !(value is PropertyDescriptor)) { throw new ArgumentException(nameof(value)); } EnsurePropsOwned(); _properties[index] = (PropertyDescriptor)value; } } private class PropertyDescriptorEnumerator : IDictionaryEnumerator { private PropertyDescriptorCollection _owner; private int _index = -1; public PropertyDescriptorEnumerator(PropertyDescriptorCollection owner) { _owner = owner; } public object Current => Entry; public DictionaryEntry Entry { get { PropertyDescriptor curProp = _owner[_index]; return new DictionaryEntry(curProp.Name, curProp); } } public object Key => _owner[_index].Name; public object Value => _owner[_index].Name; public bool MoveNext() { if (_index < (_owner.Count - 1)) { _index++; return true; } return false; } public void Reset() => _index = -1; } } }
// 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.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Net; using System.Security.Authentication.ExtendedProtection; using System.Security.Principal; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel { public class ClientCredentialsSecurityTokenManager : SecurityTokenManager { private ClientCredentials _parent; public ClientCredentialsSecurityTokenManager(ClientCredentials clientCredentials) { if (clientCredentials == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("clientCredentials"); } _parent = clientCredentials; } public ClientCredentials ClientCredentials { get { return _parent; } } private string GetServicePrincipalName(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement) { EndpointAddress targetAddress = initiatorRequirement.TargetAddress; if (targetAddress == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.TokenRequirementDoesNotSpecifyTargetAddress, initiatorRequirement)); } IdentityVerifier identityVerifier; SecurityBindingElement securityBindingElement = initiatorRequirement.SecurityBindingElement; if (securityBindingElement != null) { identityVerifier = securityBindingElement.LocalClientSettings.IdentityVerifier; } else { identityVerifier = IdentityVerifier.CreateDefault(); } EndpointIdentity identity; identityVerifier.TryGetIdentity(targetAddress, out identity); return SecurityUtils.GetSpnFromIdentity(identity, targetAddress); } private bool IsDigestAuthenticationScheme(SecurityTokenRequirement requirement) { if (requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty)) { AuthenticationSchemes authScheme = (AuthenticationSchemes)requirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty]; if (!authScheme.IsSingleton()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("authScheme", string.Format(SR.HttpRequiresSingleAuthScheme, authScheme)); } return (authScheme == AuthenticationSchemes.Digest); } else { return false; } } internal protected bool IsIssuedSecurityTokenRequirement(SecurityTokenRequirement requirement) { if (requirement != null && requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.IssuerAddressProperty)) { // handle all issued token requirements except for spnego, tlsnego and secure conversation if (requirement.TokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego || requirement.TokenType == ServiceModelSecurityTokenTypes.MutualSslnego || requirement.TokenType == ServiceModelSecurityTokenTypes.SecureConversation || requirement.TokenType == ServiceModelSecurityTokenTypes.Spnego) { return false; } else { return true; } } return false; } public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement) { if (tokenRequirement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement"); } SecurityTokenProvider result = null; if (tokenRequirement is RecipientServiceModelSecurityTokenRequirement && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate && tokenRequirement.KeyUsage == SecurityKeyUsage.Exchange) { // this is the uncorrelated duplex case if (_parent.ClientCertificate.Certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCertificateNotProvidedOnClientCredentials))); } result = new X509SecurityTokenProvider(_parent.ClientCertificate.Certificate, _parent.ClientCertificate.CloneCertificate); } else if (tokenRequirement is InitiatorServiceModelSecurityTokenRequirement) { InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement; string tokenType = initiatorRequirement.TokenType; if (IsIssuedSecurityTokenRequirement(initiatorRequirement)) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider (IsIssuedSecurityTokenRequirement(initiatorRequirement)"); } else if (tokenType == SecurityTokenTypes.X509Certificate) { if (initiatorRequirement.Properties.ContainsKey(SecurityTokenRequirement.KeyUsageProperty) && initiatorRequirement.KeyUsage == SecurityKeyUsage.Exchange) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider X509Certificate - SecurityKeyUsage.Exchange"); } else { if (_parent.ClientCertificate.Certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCertificateNotProvidedOnClientCredentials))); } result = new X509SecurityTokenProvider(_parent.ClientCertificate.Certificate, _parent.ClientCertificate.CloneCertificate); } } else if (tokenType == SecurityTokenTypes.Kerberos) { string spn = GetServicePrincipalName(initiatorRequirement); result = new KerberosSecurityTokenProviderWrapper( new KerberosSecurityTokenProvider(spn, _parent.Windows.AllowedImpersonationLevel, SecurityUtils.GetNetworkCredentialOrDefault(_parent.Windows.ClientCredential))); } else if (tokenType == SecurityTokenTypes.UserName) { if (_parent.UserName.UserName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.UserNamePasswordNotProvidedOnClientCredentials)); } result = new UserNameSecurityTokenProvider(_parent.UserName.UserName, _parent.UserName.Password); } else if (tokenType == ServiceModelSecurityTokenTypes.SspiCredential) { if (IsDigestAuthenticationScheme(initiatorRequirement)) { result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(_parent.HttpDigest.ClientCredential), true, TokenImpersonationLevel.Delegation); } else { #pragma warning disable 618 // to disable AllowNtlm obsolete wanring. result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(_parent.Windows.ClientCredential), _parent.Windows.AllowNtlm, _parent.Windows.AllowedImpersonationLevel); #pragma warning restore 618 } } } if ((result == null) && !tokenRequirement.IsOptionalToken) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SecurityTokenManagerCannotCreateProviderForRequirement, tokenRequirement))); } return result; } public override SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityTokenVersion version) { // not referenced anywhere in current code, but must implement abstract. throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenSerializer(SecurityTokenVersion version) not supported"); } private X509SecurityTokenAuthenticator CreateServerX509TokenAuthenticator() { return new X509SecurityTokenAuthenticator(_parent.ServiceCertificate.Authentication.GetCertificateValidator(), false); } private X509SecurityTokenAuthenticator CreateServerSslX509TokenAuthenticator() { if (_parent.ServiceCertificate.SslCertificateAuthentication != null) { return new X509SecurityTokenAuthenticator(_parent.ServiceCertificate.SslCertificateAuthentication.GetCertificateValidator(), false); } return CreateServerX509TokenAuthenticator(); } public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver) { if (tokenRequirement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement"); } outOfBandTokenResolver = null; SecurityTokenAuthenticator result = null; InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement; if (initiatorRequirement != null) { string tokenType = initiatorRequirement.TokenType; if (IsIssuedSecurityTokenRequirement(initiatorRequirement)) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : GenericXmlSecurityTokenAuthenticator"); } else if (tokenType == SecurityTokenTypes.X509Certificate) { if (initiatorRequirement.IsOutOfBandToken) { // when the client side soap security asks for a token authenticator, its for doing // identity checks on the out of band server certificate result = new X509SecurityTokenAuthenticator(X509CertificateValidator.None); } else if (initiatorRequirement.PreferSslCertificateAuthenticator) { result = CreateServerSslX509TokenAuthenticator(); } else { result = CreateServerX509TokenAuthenticator(); } } else if (tokenType == SecurityTokenTypes.Rsa) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : SecurityTokenTypes.Rsa"); } else if (tokenType == SecurityTokenTypes.Kerberos) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : SecurityTokenTypes.Kerberos"); } else if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation || tokenType == ServiceModelSecurityTokenTypes.MutualSslnego || tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego || tokenType == ServiceModelSecurityTokenTypes.Spnego) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : GenericXmlSecurityTokenAuthenticator"); } } else if ((tokenRequirement is RecipientServiceModelSecurityTokenRequirement) && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate) { // uncorrelated duplex case result = CreateServerX509TokenAuthenticator(); } if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SecurityTokenManagerCannotCreateAuthenticatorForRequirement, tokenRequirement))); } return result; } } internal class KerberosSecurityTokenProviderWrapper : CommunicationObjectSecurityTokenProvider { private KerberosSecurityTokenProvider _innerProvider; public KerberosSecurityTokenProviderWrapper(KerberosSecurityTokenProvider innerProvider) { _innerProvider = innerProvider; } internal Task<SecurityToken> GetTokenAsync(CancellationToken cancellationToken, ChannelBinding channelbinding) { return Task.FromResult((SecurityToken)new KerberosRequestorSecurityToken(_innerProvider.ServicePrincipalName, _innerProvider.TokenImpersonationLevel, _innerProvider.NetworkCredential, SecurityUniqueId.Create().Value)); } protected override Task<SecurityToken> GetTokenCoreAsync(CancellationToken cancellationToken) { return GetTokenAsync(cancellationToken, null); } } }
// -------------------------------------------------------------------------------------------------------------------- // <summary> // The web socket context. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WebStreams.Server { using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; /// <summary> /// The web socket context. /// </summary> internal class WebSocket : IDisposable { /// <summary> /// The function used to send data. /// </summary> private readonly Func<ArraySegment<byte>, int, bool, CancellationToken, Task> sendAsync; /// <summary> /// The delegate used to receive data. /// </summary> private readonly Func<ArraySegment<byte>, CancellationToken, Task<Tuple<int, bool, int>>> receiveAsync; /// <summary> /// The close async. /// </summary> private readonly Func<int, string, CancellationToken, Task> closeAsync; /// <summary> /// The context. /// </summary> private readonly IDictionary<string, object> context; /// <summary> /// A CancellationToken provided by the server to signal that the WebSocket has been canceled/aborted. /// </summary> private readonly CancellationToken callCancelled; /// <summary> /// A value indicating whether this instance is disposed. /// </summary> private bool disposed; /// <summary> /// Initializes a new instance of the <see cref="WebSocket"/> class. /// </summary> /// <param name="context"> /// The context. /// </param> public WebSocket(IDictionary<string, object> context) { this.context = context; this.sendAsync = (Func<ArraySegment<byte>, int, bool, CancellationToken, Task>)context[WebSocketConstants.SendAsync]; this.receiveAsync = (Func<ArraySegment<byte>, CancellationToken, Task<Tuple<int, bool, int>>>)context[WebSocketConstants.ReceiveAsync]; this.closeAsync = (Func<int, string, CancellationToken, Task>)context[WebSocketConstants.CloseAsync]; this.callCancelled = (CancellationToken)context[WebSocketConstants.CallCancelled]; } /// <summary> /// Gets the context. /// </summary> public IDictionary<string, object> Context { get { return this.context; } } /// <summary> /// Gets a value indicating whether the connection is closed. /// </summary> public bool IsClosed { get { object status; return this.disposed || (this.context.TryGetValue(WebSocketConstants.ClientCloseStatus, out status) && (int)status != 0); } } /// <summary> /// Gets the client close status. /// </summary> public int ClientCloseStatus { get { return (int)this.context[WebSocketConstants.ClientCloseStatus]; } } /// <summary> /// Gets the client close description. /// </summary> public string ClientCloseDescription { get { return (string)this.context[WebSocketConstants.ClientCloseDescription]; } } /// <summary> /// Send the provided <paramref name="data"/> to the client. /// </summary> /// <param name="data"> /// The data. /// </param> /// <param name="messageType"> /// The message type. /// </param> /// <param name="endOfMessage"> /// A value indicating whether this is the end of the message. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public async Task Send(ArraySegment<byte> data, int messageType, bool endOfMessage) { this.ThrowIfDisposed(); await this.sendAsync(data, messageType, endOfMessage, this.callCancelled); } /// <summary> /// Send the provided <paramref name="message"/> to the client. /// </summary> /// <param name="message"> /// The message. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public async Task Send(string message) { this.ThrowIfDisposed(); var bytes = Encoding.UTF8.GetBytes(message); var buffer = new ArraySegment<byte>(bytes); await this.Send(buffer, (int)WebSocketMessageType.Text, true); } /// <summary> /// Receives and returns a string to the client. /// </summary> /// <returns> /// The <see cref="Task"/>. /// </returns> public async Task<string> ReceiveString() { this.ThrowIfDisposed(); var result = new StringBuilder(); var buffer = new ArraySegment<byte>(new byte[4096]); var message = await this.receiveAsync(buffer, this.callCancelled); result.Append(Encoding.UTF8.GetString(buffer.Array, 0, message.Item3)); while (!message.Item2) { message = await this.receiveAsync(buffer, this.callCancelled); result.Append(Encoding.UTF8.GetString(buffer.Array, 0, message.Item3)); } return result.ToString(); } /// <summary> /// Close the connection with the client. /// </summary> /// <param name="closeStatus"> /// The close status. /// </param> /// <param name="closeDescription"> /// The close description. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public async Task Close(int closeStatus, string closeDescription) { this.ThrowIfDisposed(); await this.closeAsync(closeStatus, closeDescription, this.callCancelled); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this.disposed = true; } /// <summary> /// Throws <see cref="ObjectDisposedException"/> if this instance has been disposed. /// </summary> /// <exception cref="ObjectDisposedException">This instance has been disposed.</exception> private void ThrowIfDisposed() { if (this.disposed) { throw new ObjectDisposedException("This instance has been disposed."); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.Cx.V3.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedPagesClientSnippets { /// <summary>Snippet for ListPages</summary> public void ListPagesRequestObject() { // Snippet: ListPages(ListPagesRequest, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) ListPagesRequest request = new ListPagesRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), LanguageCode = "", }; // Make the request PagedEnumerable<ListPagesResponse, Page> response = pagesClient.ListPages(request); // Iterate over all response items, lazily performing RPCs as required foreach (Page item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListPagesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Page item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Page> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Page item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPagesAsync</summary> public async Task ListPagesRequestObjectAsync() { // Snippet: ListPagesAsync(ListPagesRequest, CallSettings) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) ListPagesRequest request = new ListPagesRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), LanguageCode = "", }; // Make the request PagedAsyncEnumerable<ListPagesResponse, Page> response = pagesClient.ListPagesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Page item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListPagesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Page item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Page> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Page item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPages</summary> public void ListPages() { // Snippet: ListPages(string, string, int?, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]"; // Make the request PagedEnumerable<ListPagesResponse, Page> response = pagesClient.ListPages(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Page item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListPagesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Page item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Page> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Page item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPagesAsync</summary> public async Task ListPagesAsync() { // Snippet: ListPagesAsync(string, string, int?, CallSettings) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]"; // Make the request PagedAsyncEnumerable<ListPagesResponse, Page> response = pagesClient.ListPagesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Page item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListPagesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Page item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Page> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Page item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPages</summary> public void ListPagesResourceNames() { // Snippet: ListPages(FlowName, string, int?, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) FlowName parent = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"); // Make the request PagedEnumerable<ListPagesResponse, Page> response = pagesClient.ListPages(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Page item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListPagesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Page item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Page> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Page item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListPagesAsync</summary> public async Task ListPagesResourceNamesAsync() { // Snippet: ListPagesAsync(FlowName, string, int?, CallSettings) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) FlowName parent = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"); // Make the request PagedAsyncEnumerable<ListPagesResponse, Page> response = pagesClient.ListPagesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Page item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListPagesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Page item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Page> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Page item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetPage</summary> public void GetPageRequestObject() { // Snippet: GetPage(GetPageRequest, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) GetPageRequest request = new GetPageRequest { PageName = PageName.FromProjectLocationAgentFlowPage("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[PAGE]"), LanguageCode = "", }; // Make the request Page response = pagesClient.GetPage(request); // End snippet } /// <summary>Snippet for GetPageAsync</summary> public async Task GetPageRequestObjectAsync() { // Snippet: GetPageAsync(GetPageRequest, CallSettings) // Additional: GetPageAsync(GetPageRequest, CancellationToken) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) GetPageRequest request = new GetPageRequest { PageName = PageName.FromProjectLocationAgentFlowPage("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[PAGE]"), LanguageCode = "", }; // Make the request Page response = await pagesClient.GetPageAsync(request); // End snippet } /// <summary>Snippet for GetPage</summary> public void GetPage() { // Snippet: GetPage(string, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]/pages/[PAGE]"; // Make the request Page response = pagesClient.GetPage(name); // End snippet } /// <summary>Snippet for GetPageAsync</summary> public async Task GetPageAsync() { // Snippet: GetPageAsync(string, CallSettings) // Additional: GetPageAsync(string, CancellationToken) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]/pages/[PAGE]"; // Make the request Page response = await pagesClient.GetPageAsync(name); // End snippet } /// <summary>Snippet for GetPage</summary> public void GetPageResourceNames() { // Snippet: GetPage(PageName, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) PageName name = PageName.FromProjectLocationAgentFlowPage("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[PAGE]"); // Make the request Page response = pagesClient.GetPage(name); // End snippet } /// <summary>Snippet for GetPageAsync</summary> public async Task GetPageResourceNamesAsync() { // Snippet: GetPageAsync(PageName, CallSettings) // Additional: GetPageAsync(PageName, CancellationToken) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) PageName name = PageName.FromProjectLocationAgentFlowPage("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[PAGE]"); // Make the request Page response = await pagesClient.GetPageAsync(name); // End snippet } /// <summary>Snippet for CreatePage</summary> public void CreatePageRequestObject() { // Snippet: CreatePage(CreatePageRequest, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) CreatePageRequest request = new CreatePageRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), Page = new Page(), LanguageCode = "", }; // Make the request Page response = pagesClient.CreatePage(request); // End snippet } /// <summary>Snippet for CreatePageAsync</summary> public async Task CreatePageRequestObjectAsync() { // Snippet: CreatePageAsync(CreatePageRequest, CallSettings) // Additional: CreatePageAsync(CreatePageRequest, CancellationToken) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) CreatePageRequest request = new CreatePageRequest { ParentAsFlowName = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"), Page = new Page(), LanguageCode = "", }; // Make the request Page response = await pagesClient.CreatePageAsync(request); // End snippet } /// <summary>Snippet for CreatePage</summary> public void CreatePage() { // Snippet: CreatePage(string, Page, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]"; Page page = new Page(); // Make the request Page response = pagesClient.CreatePage(parent, page); // End snippet } /// <summary>Snippet for CreatePageAsync</summary> public async Task CreatePageAsync() { // Snippet: CreatePageAsync(string, Page, CallSettings) // Additional: CreatePageAsync(string, Page, CancellationToken) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]"; Page page = new Page(); // Make the request Page response = await pagesClient.CreatePageAsync(parent, page); // End snippet } /// <summary>Snippet for CreatePage</summary> public void CreatePageResourceNames() { // Snippet: CreatePage(FlowName, Page, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) FlowName parent = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"); Page page = new Page(); // Make the request Page response = pagesClient.CreatePage(parent, page); // End snippet } /// <summary>Snippet for CreatePageAsync</summary> public async Task CreatePageResourceNamesAsync() { // Snippet: CreatePageAsync(FlowName, Page, CallSettings) // Additional: CreatePageAsync(FlowName, Page, CancellationToken) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) FlowName parent = FlowName.FromProjectLocationAgentFlow("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]"); Page page = new Page(); // Make the request Page response = await pagesClient.CreatePageAsync(parent, page); // End snippet } /// <summary>Snippet for UpdatePage</summary> public void UpdatePageRequestObject() { // Snippet: UpdatePage(UpdatePageRequest, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) UpdatePageRequest request = new UpdatePageRequest { Page = new Page(), LanguageCode = "", UpdateMask = new FieldMask(), }; // Make the request Page response = pagesClient.UpdatePage(request); // End snippet } /// <summary>Snippet for UpdatePageAsync</summary> public async Task UpdatePageRequestObjectAsync() { // Snippet: UpdatePageAsync(UpdatePageRequest, CallSettings) // Additional: UpdatePageAsync(UpdatePageRequest, CancellationToken) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) UpdatePageRequest request = new UpdatePageRequest { Page = new Page(), LanguageCode = "", UpdateMask = new FieldMask(), }; // Make the request Page response = await pagesClient.UpdatePageAsync(request); // End snippet } /// <summary>Snippet for UpdatePage</summary> public void UpdatePage() { // Snippet: UpdatePage(Page, FieldMask, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) Page page = new Page(); FieldMask updateMask = new FieldMask(); // Make the request Page response = pagesClient.UpdatePage(page, updateMask); // End snippet } /// <summary>Snippet for UpdatePageAsync</summary> public async Task UpdatePageAsync() { // Snippet: UpdatePageAsync(Page, FieldMask, CallSettings) // Additional: UpdatePageAsync(Page, FieldMask, CancellationToken) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) Page page = new Page(); FieldMask updateMask = new FieldMask(); // Make the request Page response = await pagesClient.UpdatePageAsync(page, updateMask); // End snippet } /// <summary>Snippet for DeletePage</summary> public void DeletePageRequestObject() { // Snippet: DeletePage(DeletePageRequest, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) DeletePageRequest request = new DeletePageRequest { PageName = PageName.FromProjectLocationAgentFlowPage("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[PAGE]"), Force = false, }; // Make the request pagesClient.DeletePage(request); // End snippet } /// <summary>Snippet for DeletePageAsync</summary> public async Task DeletePageRequestObjectAsync() { // Snippet: DeletePageAsync(DeletePageRequest, CallSettings) // Additional: DeletePageAsync(DeletePageRequest, CancellationToken) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) DeletePageRequest request = new DeletePageRequest { PageName = PageName.FromProjectLocationAgentFlowPage("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[PAGE]"), Force = false, }; // Make the request await pagesClient.DeletePageAsync(request); // End snippet } /// <summary>Snippet for DeletePage</summary> public void DeletePage() { // Snippet: DeletePage(string, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]/pages/[PAGE]"; // Make the request pagesClient.DeletePage(name); // End snippet } /// <summary>Snippet for DeletePageAsync</summary> public async Task DeletePageAsync() { // Snippet: DeletePageAsync(string, CallSettings) // Additional: DeletePageAsync(string, CancellationToken) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/flows/[FLOW]/pages/[PAGE]"; // Make the request await pagesClient.DeletePageAsync(name); // End snippet } /// <summary>Snippet for DeletePage</summary> public void DeletePageResourceNames() { // Snippet: DeletePage(PageName, CallSettings) // Create client PagesClient pagesClient = PagesClient.Create(); // Initialize request argument(s) PageName name = PageName.FromProjectLocationAgentFlowPage("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[PAGE]"); // Make the request pagesClient.DeletePage(name); // End snippet } /// <summary>Snippet for DeletePageAsync</summary> public async Task DeletePageResourceNamesAsync() { // Snippet: DeletePageAsync(PageName, CallSettings) // Additional: DeletePageAsync(PageName, CancellationToken) // Create client PagesClient pagesClient = await PagesClient.CreateAsync(); // Initialize request argument(s) PageName name = PageName.FromProjectLocationAgentFlowPage("[PROJECT]", "[LOCATION]", "[AGENT]", "[FLOW]", "[PAGE]"); // Make the request await pagesClient.DeletePageAsync(name); // End snippet } } }
// 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 MinSingle() { var test = new SimpleBinaryOpTest__MinSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // 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(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MinSingle { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[ElementCount]; private static Single[] _data2 = new Single[ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single> _dataTable; static SimpleBinaryOpTest__MinSingle() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__MinSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.Min( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.Min( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.Min( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.Min), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.Min), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.Min), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.Min(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.Min(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.Min(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__MinSingle(); var result = Sse.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(Math.Min(left[0], right[0])) != BitConverter.SingleToInt32Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (BitConverter.SingleToInt32Bits(Math.Min(left[i], right[i])) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.Min)}<Single>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using JetBrains.Annotations; using JsonApiDotNetCore.Resources.Annotations; namespace JsonApiDotNetCore.Configuration; /// <summary> /// Metadata about the shape of a JSON:API resource in the resource graph. /// </summary> [PublicAPI] public sealed class ResourceType { private readonly Dictionary<string, ResourceFieldAttribute> _fieldsByPublicName = new(); private readonly Dictionary<string, ResourceFieldAttribute> _fieldsByPropertyName = new(); /// <summary> /// The publicly exposed resource name. /// </summary> public string PublicName { get; } /// <summary> /// The CLR type of the resource. /// </summary> public Type ClrType { get; } /// <summary> /// The CLR type of the resource identity. /// </summary> public Type IdentityClrType { get; } /// <summary> /// Exposed resource attributes and relationships. See https://jsonapi.org/format/#document-resource-object-fields. /// </summary> public IReadOnlyCollection<ResourceFieldAttribute> Fields { get; } /// <summary> /// Exposed resource attributes. See https://jsonapi.org/format/#document-resource-object-attributes. /// </summary> public IReadOnlyCollection<AttrAttribute> Attributes { get; } /// <summary> /// Exposed resource relationships. See https://jsonapi.org/format/#document-resource-object-relationships. /// </summary> public IReadOnlyCollection<RelationshipAttribute> Relationships { get; } /// <summary> /// Related entities that are not exposed as resource relationships. /// </summary> public IReadOnlyCollection<EagerLoadAttribute> EagerLoads { get; } /// <summary> /// Configures which links to write in the top-level links object for this resource type. Defaults to <see cref="LinkTypes.NotConfigured" />, which falls /// back to TopLevelLinks in global options. /// </summary> /// <remarks> /// In the process of building the resource graph, this value is set based on <see cref="ResourceLinksAttribute.TopLevelLinks" /> usage. /// </remarks> public LinkTypes TopLevelLinks { get; } /// <summary> /// Configures which links to write in the resource-level links object for this resource type. Defaults to <see cref="LinkTypes.NotConfigured" />, which /// falls back to ResourceLinks in global options. /// </summary> /// <remarks> /// In the process of building the resource graph, this value is set based on <see cref="ResourceLinksAttribute.ResourceLinks" /> usage. /// </remarks> public LinkTypes ResourceLinks { get; } /// <summary> /// Configures which links to write in the relationship-level links object for all relationships of this resource type. Defaults to /// <see cref="LinkTypes.NotConfigured" />, which falls back to RelationshipLinks in global options. This can be overruled per relationship by setting /// <see cref="RelationshipAttribute.Links" />. /// </summary> /// <remarks> /// In the process of building the resource graph, this value is set based on <see cref="ResourceLinksAttribute.RelationshipLinks" /> usage. /// </remarks> public LinkTypes RelationshipLinks { get; } public ResourceType(string publicName, Type clrType, Type identityClrType, IReadOnlyCollection<AttrAttribute>? attributes = null, IReadOnlyCollection<RelationshipAttribute>? relationships = null, IReadOnlyCollection<EagerLoadAttribute>? eagerLoads = null, LinkTypes topLevelLinks = LinkTypes.NotConfigured, LinkTypes resourceLinks = LinkTypes.NotConfigured, LinkTypes relationshipLinks = LinkTypes.NotConfigured) { ArgumentGuard.NotNullNorEmpty(publicName, nameof(publicName)); ArgumentGuard.NotNull(clrType, nameof(clrType)); ArgumentGuard.NotNull(identityClrType, nameof(identityClrType)); PublicName = publicName; ClrType = clrType; IdentityClrType = identityClrType; Attributes = attributes ?? Array.Empty<AttrAttribute>(); Relationships = relationships ?? Array.Empty<RelationshipAttribute>(); EagerLoads = eagerLoads ?? Array.Empty<EagerLoadAttribute>(); TopLevelLinks = topLevelLinks; ResourceLinks = resourceLinks; RelationshipLinks = relationshipLinks; Fields = Attributes.Cast<ResourceFieldAttribute>().Concat(Relationships).ToArray(); foreach (ResourceFieldAttribute field in Fields) { _fieldsByPublicName.Add(field.PublicName, field); _fieldsByPropertyName.Add(field.Property.Name, field); } } public AttrAttribute GetAttributeByPublicName(string publicName) { AttrAttribute? attribute = FindAttributeByPublicName(publicName); return attribute ?? throw new InvalidOperationException($"Attribute '{publicName}' does not exist on resource type '{PublicName}'."); } public AttrAttribute? FindAttributeByPublicName(string publicName) { ArgumentGuard.NotNull(publicName, nameof(publicName)); return _fieldsByPublicName.TryGetValue(publicName, out ResourceFieldAttribute? field) && field is AttrAttribute attribute ? attribute : null; } public AttrAttribute GetAttributeByPropertyName(string propertyName) { AttrAttribute? attribute = FindAttributeByPropertyName(propertyName); return attribute ?? throw new InvalidOperationException($"Attribute for property '{propertyName}' does not exist on resource type '{ClrType.Name}'."); } public AttrAttribute? FindAttributeByPropertyName(string propertyName) { ArgumentGuard.NotNull(propertyName, nameof(propertyName)); return _fieldsByPropertyName.TryGetValue(propertyName, out ResourceFieldAttribute? field) && field is AttrAttribute attribute ? attribute : null; } public RelationshipAttribute GetRelationshipByPublicName(string publicName) { RelationshipAttribute? relationship = FindRelationshipByPublicName(publicName); return relationship ?? throw new InvalidOperationException($"Relationship '{publicName}' does not exist on resource type '{PublicName}'."); } public RelationshipAttribute? FindRelationshipByPublicName(string publicName) { ArgumentGuard.NotNull(publicName, nameof(publicName)); return _fieldsByPublicName.TryGetValue(publicName, out ResourceFieldAttribute? field) && field is RelationshipAttribute relationship ? relationship : null; } public RelationshipAttribute GetRelationshipByPropertyName(string propertyName) { RelationshipAttribute? relationship = FindRelationshipByPropertyName(propertyName); return relationship ?? throw new InvalidOperationException($"Relationship for property '{propertyName}' does not exist on resource type '{ClrType.Name}'."); } public RelationshipAttribute? FindRelationshipByPropertyName(string propertyName) { ArgumentGuard.NotNull(propertyName, nameof(propertyName)); return _fieldsByPropertyName.TryGetValue(propertyName, out ResourceFieldAttribute? field) && field is RelationshipAttribute relationship ? relationship : null; } public override string ToString() { return PublicName; } public override bool Equals(object? obj) { if (ReferenceEquals(this, obj)) { return true; } if (obj is null || GetType() != obj.GetType()) { return false; } var other = (ResourceType)obj; return PublicName == other.PublicName && ClrType == other.ClrType && IdentityClrType == other.IdentityClrType && Attributes.SequenceEqual(other.Attributes) && Relationships.SequenceEqual(other.Relationships) && EagerLoads.SequenceEqual(other.EagerLoads) && TopLevelLinks == other.TopLevelLinks && ResourceLinks == other.ResourceLinks && RelationshipLinks == other.RelationshipLinks; } public override int GetHashCode() { var hashCode = new HashCode(); hashCode.Add(PublicName); hashCode.Add(ClrType); hashCode.Add(IdentityClrType); foreach (AttrAttribute attribute in Attributes) { hashCode.Add(attribute); } foreach (RelationshipAttribute relationship in Relationships) { hashCode.Add(relationship); } foreach (EagerLoadAttribute eagerLoad in EagerLoads) { hashCode.Add(eagerLoad); } hashCode.Add(TopLevelLinks); hashCode.Add(ResourceLinks); hashCode.Add(RelationshipLinks); return hashCode.ToHashCode(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // /*============================================================================= ** ** ** ** Purpose: Base class for representing Events ** ** =============================================================================*/ using System; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; using Microsoft.Win32.SafeHandles; using System.IO; namespace System.Threading { [ComVisibleAttribute(true)] public class EventWaitHandle : WaitHandle { [System.Security.SecuritySafeCritical] // auto-generated public EventWaitHandle(bool initialState, EventResetMode mode) : this(initialState, mode, null) { } [System.Security.SecurityCritical] // auto-generated_required public EventWaitHandle(bool initialState, EventResetMode mode, string name) { if (null != name) { if (((int)Interop.Constants.MaxPath) < name.Length) { throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, name)); } } Contract.EndContractBlock(); uint eventFlags = initialState ? (uint)Interop.Constants.CreateEventInitialSet : 0; IntPtr unsafeHandle; switch (mode) { case EventResetMode.ManualReset: eventFlags |= (uint)Interop.Constants.CreateEventManualReset; break; case EventResetMode.AutoReset: break; default: throw new ArgumentException(SR.Format(SR.Argument_InvalidFlag, name)); }; unsafeHandle = Interop.mincore.CreateEventEx(IntPtr.Zero, name, eventFlags, (uint)Interop.Constants.EventAllAccess); int errorCode = (int)Interop.mincore.GetLastError(); SafeWaitHandle _handle = new SafeWaitHandle(unsafeHandle, true); if (_handle.IsInvalid) { _handle.SetHandleAsInvalid(); if (null != name && 0 != name.Length && Interop.mincore.Errors.ERROR_INVALID_HANDLE == errorCode) throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); throw ExceptionFromCreationError(errorCode, name); } SafeWaitHandle = _handle; } [System.Security.SecurityCritical] // auto-generated_required public EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew) { if (null != name && ((int)Interop.Constants.MaxPath) < name.Length) { throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, name)); } Contract.EndContractBlock(); SafeWaitHandle _handle = null; uint eventFlags = initialState ? (uint)Interop.Constants.CreateEventInitialSet : 0; switch (mode) { case EventResetMode.ManualReset: eventFlags |= (uint)Interop.Constants.CreateEventManualReset; break; case EventResetMode.AutoReset: break; default: throw new ArgumentException(SR.Format(SR.Argument_InvalidFlag, name)); }; IntPtr unsafeHandle = Interop.mincore.CreateEventEx(IntPtr.Zero, name, eventFlags, (uint)Interop.Constants.EventAllAccess); int errorCode = (int)Interop.mincore.GetLastError(); _handle = new SafeWaitHandle(unsafeHandle, true); if (_handle.IsInvalid) { _handle.SetHandleAsInvalid(); if (null != name && 0 != name.Length && Interop.mincore.Errors.ERROR_INVALID_HANDLE == errorCode) throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); throw ExceptionFromCreationError(errorCode, name); } createdNew = errorCode != Interop.mincore.Errors.ERROR_ALREADY_EXISTS; SafeWaitHandle = _handle; } [System.Security.SecurityCritical] // auto-generated private EventWaitHandle(SafeWaitHandle handle) { SafeWaitHandle = handle; } [System.Security.SecurityCritical] // auto-generated_required public static EventWaitHandle OpenExisting(string name) { EventWaitHandle result; switch (OpenExistingWorker(name, out result)) { case OpenExistingResult.NameNotFound: throw new WaitHandleCannotBeOpenedException(); case OpenExistingResult.NameInvalid: throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); case OpenExistingResult.PathNotFound: throw new IOException(SR.Format(SR.IO_PathNotFound_Path, name)); default: return result; } } [System.Security.SecurityCritical] // auto-generated_required public static bool TryOpenExisting(string name, out EventWaitHandle result) { return OpenExistingWorker(name, out result) == OpenExistingResult.Success; } [System.Security.SecurityCritical] // auto-generated_required private static OpenExistingResult OpenExistingWorker(string name, out EventWaitHandle result) { if (name == null) { throw new ArgumentNullException("name", SR.ArgumentNull_WithParamName); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } if (null != name && ((int)Interop.Constants.MaxPath) < name.Length) { throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, name)); } Contract.EndContractBlock(); result = null; IntPtr unsafeHandle = Interop.mincore.OpenEvent((uint)(Interop.Constants.EventModifyState | Interop.Constants.Synchronize), false, name); int errorCode = (int)Interop.mincore.GetLastError(); SafeWaitHandle myHandle = new SafeWaitHandle(unsafeHandle, true); if (myHandle.IsInvalid) { if (Interop.mincore.Errors.ERROR_FILE_NOT_FOUND == errorCode || Interop.mincore.Errors.ERROR_INVALID_NAME == errorCode) return OpenExistingResult.NameNotFound; if (Interop.mincore.Errors.ERROR_PATH_NOT_FOUND == errorCode) return OpenExistingResult.PathNotFound; if (null != name && 0 != name.Length && Interop.mincore.Errors.ERROR_INVALID_HANDLE == errorCode) return OpenExistingResult.NameInvalid; //this is for passed through Win32Native Errors throw ExceptionFromCreationError(errorCode, name); } result = new EventWaitHandle(myHandle); return OpenExistingResult.Success; } [System.Security.SecuritySafeCritical] // auto-generated public bool Reset() { waitHandle.DangerousAddRef(); try { bool res = Interop.mincore.ResetEvent(waitHandle.DangerousGetHandle()); if (!res) throw new IOException(SR.Arg_IOException, (int)Interop.mincore.GetLastError()); return res; } finally { waitHandle.DangerousRelease(); } } [System.Security.SecuritySafeCritical] // auto-generated public bool Set() { waitHandle.DangerousAddRef(); try { bool res = Interop.mincore.SetEvent(waitHandle.DangerousGetHandle()); if (!res) throw new IOException(SR.Arg_IOException, (int)Interop.mincore.GetLastError()); return res; } finally { waitHandle.DangerousRelease(); } } } }
// 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.Linq; using System.Runtime.InteropServices; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Pipes.Tests { /// <summary> /// The Specific NamedPipe tests cover edge cases or otherwise narrow cases that /// show up within particular server/client directional combinations. /// </summary> public class NamedPipeTest_Specific : NamedPipeTestBase { [Fact] public void InvalidConnectTimeout_Throws_ArgumentOutOfRangeException() { using (NamedPipeClientStream client = new NamedPipeClientStream("client1")) { AssertExtensions.Throws<ArgumentOutOfRangeException>("timeout", () => client.Connect(-111)); AssertExtensions.Throws<ArgumentOutOfRangeException>("timeout", () => { client.ConnectAsync(-111); }); } } [Fact] public async Task ConnectToNonExistentServer_Throws_TimeoutException() { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere")) { var ctx = new CancellationTokenSource(); Assert.Throws<TimeoutException>(() => client.Connect(60)); // 60 to be over internal 50 interval await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(50)); await Assert.ThrowsAsync<TimeoutException>(() => client.ConnectAsync(60, ctx.Token)); // testing Token overload; ctx is not canceled in this test } } [Fact] public async Task CancelConnectToNonExistentServer_Throws_OperationCanceledException() { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "notthere")) { var ctx = new CancellationTokenSource(); Task clientConnectToken = client.ConnectAsync(ctx.Token); ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientConnectToken); ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.ConnectAsync(ctx.Token)); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix implementation uses bidirectional sockets public void ConnectWithConflictingDirections_Throws_UnauthorizedAccessException() { string serverName1 = GetUniquePipeName(); using (NamedPipeServerStream server = new NamedPipeServerStream(serverName1, PipeDirection.Out)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName1, PipeDirection.Out)) { Assert.Throws<UnauthorizedAccessException>(() => client.Connect()); Assert.False(client.IsConnected); } string serverName2 = GetUniquePipeName(); using (NamedPipeServerStream server = new NamedPipeServerStream(serverName2, PipeDirection.In)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", serverName2, PipeDirection.In)) { Assert.Throws<UnauthorizedAccessException>(() => client.Connect()); Assert.False(client.IsConnected); } } [Theory] [InlineData(1)] [InlineData(3)] public async Task MultipleWaitingClients_ServerServesOneAtATime(int numClients) { string name = GetUniquePipeName(); using (NamedPipeServerStream server = new NamedPipeServerStream(name)) { var clients = new List<Task>(from i in Enumerable.Range(0, numClients) select ConnectClientAndReadAsync()); while (clients.Count > 0) { Task<Task> firstClient = Task.WhenAny(clients); await new Task[] { ServerWaitReadAndWriteAsync(), firstClient }.WhenAllOrAnyFailed(); clients.Remove(firstClient.Result); } async Task ServerWaitReadAndWriteAsync() { await server.WaitForConnectionAsync(); await server.WriteAsync(new byte[1], 0, 1); Assert.Equal(1, await server.ReadAsync(new byte[1], 0, 1)); server.Disconnect(); } async Task ConnectClientAndReadAsync() { using (var npcs = new NamedPipeClientStream(name)) { await npcs.ConnectAsync(); Assert.Equal(1, await npcs.ReadAsync(new byte[1], 0, 1)); await npcs.WriteAsync(new byte[1], 0, 1); } } } } [Fact] public void MaxNumberOfServerInstances_TooManyServers_Throws() { string name = GetUniquePipeName(); using (new NamedPipeServerStream(name, PipeDirection.InOut, 1)) { // NPSS was created with max of 1, so creating another fails. Assert.Throws<IOException>(() => new NamedPipeServerStream(name, PipeDirection.InOut, 1)); } using (new NamedPipeServerStream(name, PipeDirection.InOut, 3)) { // NPSS was created with max of 3, but NPSS not only validates against the original max but also // against the max of the stream being created, so since there's already 1 and this specifies max == 1, it fails. Assert.Throws<UnauthorizedAccessException>(() => new NamedPipeServerStream(name, PipeDirection.InOut, 1)); using (new NamedPipeServerStream(name, PipeDirection.InOut, 2)) // lower max ignored using (new NamedPipeServerStream(name, PipeDirection.InOut, 4)) // higher max ignored { // NPSS was created with a max of 3, and we're creating a 4th, so it fails. Assert.Throws<IOException>(() => new NamedPipeServerStream(name, PipeDirection.InOut, 3)); } using (new NamedPipeServerStream(name, PipeDirection.InOut, 3)) using (new NamedPipeServerStream(name, PipeDirection.InOut, 3)) { // NPSS was created with a max of 3, and we've already created 3, so it fails, // even if the new stream tries to raise it. Assert.Throws<IOException>(() => new NamedPipeServerStream(name, PipeDirection.InOut, 4)); Assert.Throws<IOException>(() => new NamedPipeServerStream(name, PipeDirection.InOut, 2)); } } } [Theory] [InlineData(1)] [InlineData(4)] public async Task MultipleServers_ServeMultipleClientsConcurrently(int numServers) { string name = GetUniquePipeName(); var servers = new NamedPipeServerStream[numServers]; var clients = new NamedPipeClientStream[servers.Length]; try { for (int i = 0; i < servers.Length; i++) { servers[i] = new NamedPipeServerStream(name, PipeDirection.InOut, numServers, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); } for (int i = 0; i < clients.Length; i++) { clients[i] = new NamedPipeClientStream(".", name, PipeDirection.InOut, PipeOptions.Asynchronous); } Task[] serverWaits = (from server in servers select server.WaitForConnectionAsync()).ToArray(); Task[] clientWaits = (from client in clients select client.ConnectAsync()).ToArray(); await serverWaits.Concat(clientWaits).ToArray().WhenAllOrAnyFailed(); Task[] serverSends = (from server in servers select server.WriteAsync(new byte[1], 0, 1)).ToArray(); Task<int>[] clientReceives = (from client in clients select client.ReadAsync(new byte[1], 0, 1)).ToArray(); await serverSends.Concat(clientReceives).ToArray().WhenAllOrAnyFailed(); } finally { for (int i = 0; i < clients.Length; i++) { clients[i]?.Dispose(); } for (int i = 0; i < servers.Length; i++) { servers[i]?.Dispose(); } } } [Theory] [InlineData(PipeOptions.None)] [InlineData(PipeOptions.Asynchronous)] [PlatformSpecific(TestPlatforms.Windows)] // Unix currently doesn't support message mode public void Windows_MessagePipeTransmissionMode(PipeOptions serverOptions) { byte[] msg1 = new byte[] { 5, 7, 9, 10 }; byte[] msg2 = new byte[] { 2, 4 }; byte[] received1 = new byte[] { 0, 0, 0, 0 }; byte[] received2 = new byte[] { 0, 0 }; byte[] received3 = new byte[] { 0, 0, 0, 0 }; byte[] received4 = new byte[] { 0, 0, 0, 0 }; byte[] received5 = new byte[] { 0, 0 }; byte[] received6 = new byte[] { 0, 0, 0, 0 }; string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, serverOptions)) { using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation)) { server.ReadMode = PipeTransmissionMode.Message; Assert.Equal(PipeTransmissionMode.Message, server.ReadMode); client.Connect(); Task clientTask = Task.Run(() => { client.Write(msg1, 0, msg1.Length); client.Write(msg2, 0, msg2.Length); client.Write(msg1, 0, msg1.Length); client.Write(msg1, 0, msg1.Length); client.Write(msg2, 0, msg2.Length); client.Write(msg1, 0, msg1.Length); int serverCount = client.NumberOfServerInstances; Assert.Equal(1, serverCount); }); Task serverTask = Task.Run(async () => { server.WaitForConnection(); int len1 = server.Read(received1, 0, msg1.Length); Assert.True(server.IsMessageComplete); Assert.Equal(msg1.Length, len1); Assert.Equal(msg1, received1); int len2 = server.Read(received2, 0, msg2.Length); Assert.True(server.IsMessageComplete); Assert.Equal(msg2.Length, len2); Assert.Equal(msg2, received2); int expectedRead = msg1.Length - 1; int len3 = server.Read(received3, 0, expectedRead); // read one less than message Assert.False(server.IsMessageComplete); Assert.Equal(expectedRead, len3); for (int i = 0; i < expectedRead; ++i) { Assert.Equal(msg1[i], received3[i]); } expectedRead = msg1.Length - expectedRead; Assert.Equal(expectedRead, server.Read(received3, len3, expectedRead)); Assert.True(server.IsMessageComplete); Assert.Equal(msg1, received3); Assert.Equal(msg1.Length, await server.ReadAsync(received4, 0, msg1.Length)); Assert.True(server.IsMessageComplete); Assert.Equal(msg1, received4); Assert.Equal(msg2.Length, await server.ReadAsync(received5, 0, msg2.Length)); Assert.True(server.IsMessageComplete); Assert.Equal(msg2, received5); expectedRead = msg1.Length - 1; Assert.Equal(expectedRead, await server.ReadAsync(received6, 0, expectedRead)); // read one less than message Assert.False(server.IsMessageComplete); for (int i = 0; i < expectedRead; ++i) { Assert.Equal(msg1[i], received6[i]); } expectedRead = msg1.Length - expectedRead; Assert.Equal(expectedRead, await server.ReadAsync(received6, msg1.Length - expectedRead, expectedRead)); Assert.True(server.IsMessageComplete); Assert.Equal(msg1, received6); }); Assert.True(Task.WaitAll(new[] { clientTask, serverTask }, TimeSpan.FromSeconds(15))); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix doesn't support MaxNumberOfServerInstances public async Task Windows_Get_NumberOfServerInstances_Succeed() { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 3)) { using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation)) { Task serverTask = server.WaitForConnectionAsync(); client.Connect(); await serverTask; Assert.True(InteropTest.TryGetNumberOfServerInstances(client.SafePipeHandle, out uint expectedNumberOfServerInstances), "GetNamedPipeHandleState failed"); Assert.Equal(expectedNumberOfServerInstances, (uint)client.NumberOfServerInstances); } } } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] [InlineData(TokenImpersonationLevel.None, false)] [InlineData(TokenImpersonationLevel.Anonymous, false)] [InlineData(TokenImpersonationLevel.Identification, true)] [InlineData(TokenImpersonationLevel.Impersonation, true)] [InlineData(TokenImpersonationLevel.Delegation, true)] [PlatformSpecific(TestPlatforms.Windows)] // Win32 P/Invokes to verify the user name public async Task Windows_GetImpersonationUserName_Succeed(TokenImpersonationLevel level, bool expectedResult) { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName)) { using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, level)) { string expectedUserName; Task serverTask = server.WaitForConnectionAsync(); client.Connect(); await serverTask; Assert.Equal(expectedResult, InteropTest.TryGetImpersonationUserName(server.SafePipeHandle, out expectedUserName)); if (!expectedResult) { Assert.Equal(string.Empty, expectedUserName); Assert.Throws<IOException>(() => server.GetImpersonationUserName()); } else { string actualUserName = server.GetImpersonationUserName(); Assert.NotNull(actualUserName); Assert.False(string.IsNullOrWhiteSpace(actualUserName)); Assert.Equal(expectedUserName, actualUserName); } } } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invoke to verify the user name public async Task Unix_GetImpersonationUserName_Succeed() { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation)) { Task serverTask = server.WaitForConnectionAsync(); client.Connect(); await serverTask; string name = server.GetImpersonationUserName(); Assert.NotNull(name); Assert.False(string.IsNullOrWhiteSpace(name)); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix currently doesn't support message mode public void Unix_MessagePipeTransmissionMode() { Assert.Throws<PlatformNotSupportedException>(() => new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.InOut, 1, PipeTransmissionMode.Message)); } [Theory] [InlineData(PipeDirection.In)] [InlineData(PipeDirection.Out)] [InlineData(PipeDirection.InOut)] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix implementation uses bidirectional sockets public static void Unix_BufferSizeRoundtripping(PipeDirection direction) { int desiredBufferSize = 0; string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); desiredBufferSize = server.OutBufferSize * 2; } using (var server = new NamedPipeServerStream(pipeName, direction, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, direction == PipeDirection.In ? PipeDirection.Out : PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); if ((direction & PipeDirection.Out) != 0) { Assert.InRange(server.OutBufferSize, desiredBufferSize, int.MaxValue); } if ((direction & PipeDirection.In) != 0) { Assert.InRange(server.InBufferSize, desiredBufferSize, int.MaxValue); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix implementation uses bidirectional sockets public static void Windows_BufferSizeRoundtripping() { int desiredBufferSize = 10; string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Equal(desiredBufferSize, server.OutBufferSize); Assert.Equal(desiredBufferSize, client.InBufferSize); } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, desiredBufferSize, desiredBufferSize)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Equal(desiredBufferSize, server.InBufferSize); Assert.Equal(0, client.OutBufferSize); } } [Fact] public void PipeTransmissionMode_Returns_Byte() { using (ServerClientPair pair = CreateServerClientPair()) { Assert.Equal(PipeTransmissionMode.Byte, pair.writeablePipe.TransmissionMode); Assert.Equal(PipeTransmissionMode.Byte, pair.readablePipe.TransmissionMode); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix doesn't currently support message mode public void Windows_SetReadModeTo__PipeTransmissionModeByte() { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); // Throws regardless of connection status for the pipe that is set to PipeDirection.In Assert.Throws<UnauthorizedAccessException>(() => server.ReadMode = PipeTransmissionMode.Byte); client.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); // Throws regardless of connection status for the pipe that is set to PipeDirection.In Assert.Throws<UnauthorizedAccessException>(() => client.ReadMode = PipeTransmissionMode.Byte); server.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); server.ReadMode = PipeTransmissionMode.Byte; client.ReadMode = PipeTransmissionMode.Byte; } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix doesn't currently support message mode public void Unix_SetReadModeTo__PipeTransmissionModeByte() { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); server.ReadMode = PipeTransmissionMode.Byte; client.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.In)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); client.ReadMode = PipeTransmissionMode.Byte; server.ReadMode = PipeTransmissionMode.Byte; } using (var server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); server.ReadMode = PipeTransmissionMode.Byte; client.ReadMode = PipeTransmissionMode.Byte; } } [Theory] [InlineData(PipeDirection.Out, PipeDirection.In)] [InlineData(PipeDirection.In, PipeDirection.Out)] public void InvalidReadMode_Throws_ArgumentOutOfRangeException(PipeDirection serverDirection, PipeDirection clientDirection) { string pipeName = GetUniquePipeName(); using (var server = new NamedPipeServerStream(pipeName, serverDirection, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) using (var client = new NamedPipeClientStream(".", pipeName, clientDirection)) { Task clientConnect = client.ConnectAsync(); server.WaitForConnection(); clientConnect.Wait(); Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999); Assert.Throws<ArgumentOutOfRangeException>(() => client.ReadMode = (PipeTransmissionMode)999); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Checks MaxLength for PipeName on Unix public void NameTooLong_MaxLengthPerPlatform() { // Increase a name's length until it fails ArgumentOutOfRangeException e = null; string name = Path.GetRandomFileName(); for (int i = 0; ; i++) { try { name += 'c'; using (var s = new NamedPipeServerStream(name)) using (var c = new NamedPipeClientStream(name)) { Task t = s.WaitForConnectionAsync(); c.Connect(); t.GetAwaiter().GetResult(); } } catch (ArgumentOutOfRangeException exc) { e = exc; break; } } Assert.NotNull(e); Assert.NotNull(e.ActualValue); // Validate the length was expected string path = (string)e.ActualValue; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.Equal(108, path.Length); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Equal(104, path.Length); } else { Assert.InRange(path.Length, 92, int.MaxValue); } } [Fact] public void ClientConnect_Throws_Timeout_When_Pipe_Not_Found() { string pipeName = GetUniquePipeName(); using (NamedPipeClientStream client = new NamedPipeClientStream(pipeName)) { Assert.Throws<TimeoutException>(() => client.Connect(91)); } } [Theory] [MemberData(nameof(GetCancellationTokens))] public async Task ClientConnectAsync_Throws_Timeout_When_Pipe_Not_Found(CancellationToken cancellationToken) { string pipeName = GetUniquePipeName(); using (NamedPipeClientStream client = new NamedPipeClientStream(pipeName)) { Task waitingClient = client.ConnectAsync(92, cancellationToken); await Assert.ThrowsAsync<TimeoutException>(() => { return waitingClient; }); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix ignores MaxNumberOfServerInstances and second client also connects. public void ClientConnect_Throws_Timeout_When_Pipe_Busy() { string pipeName = GetUniquePipeName(); using (NamedPipeServerStream server = new NamedPipeServerStream(pipeName)) using (NamedPipeClientStream firstClient = new NamedPipeClientStream(pipeName)) using (NamedPipeClientStream secondClient = new NamedPipeClientStream(pipeName)) { const int timeout = 10_000; Task[] clientAndServerTasks = new[] { firstClient.ConnectAsync(timeout), Task.Run(() => server.WaitForConnection()) }; Assert.True(Task.WaitAll(clientAndServerTasks, timeout)); Assert.Throws<TimeoutException>(() => secondClient.Connect(93)); } } [Theory] [MemberData(nameof(GetCancellationTokens))] [PlatformSpecific(TestPlatforms.Windows)] // Unix ignores MaxNumberOfServerInstances and second client also connects. public async Task ClientConnectAsync_With_Cancellation_Throws_Timeout_When_Pipe_Busy(CancellationToken cancellationToken) { string pipeName = GetUniquePipeName(); using (NamedPipeServerStream server = new NamedPipeServerStream(pipeName)) using (NamedPipeClientStream firstClient = new NamedPipeClientStream(pipeName)) using (NamedPipeClientStream secondClient = new NamedPipeClientStream(pipeName)) { const int timeout = 10_000; Task[] clientAndServerTasks = new[] { firstClient.ConnectAsync(timeout), Task.Run(() => server.WaitForConnection()) }; Assert.True(Task.WaitAll(clientAndServerTasks, timeout)); Task waitingClient = secondClient.ConnectAsync(94, cancellationToken); await Assert.ThrowsAsync<TimeoutException>(() => { return waitingClient; }); } } public static IEnumerable<object[]> GetCancellationTokens => new [] { new object[] { CancellationToken.None }, new object[] { new CancellationTokenSource().Token }, }; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// DropDown Menu Control /// </summary> [AddComponentMenu("2D Toolkit/UI/tk2dUIDropDownMenu")] public class tk2dUIDropDownMenu : MonoBehaviour { /// <summary> /// Button that controls, dropdown list from appearing /// </summary> public tk2dUIItem dropDownButton; /// <summary> /// Primary textMesh, this will read what DropDownItem is selected /// </summary> public tk2dTextMesh selectedTextMesh; /// <summary> /// Visual height of this ui item, used for spacing /// </summary> [HideInInspector] public float height; /// <summary> /// Template for each drop down item. Will be cloned. /// </summary> public tk2dUIDropDownItem dropDownItemTemplate; /// <summary> /// List all all the text for the dropdown list /// </summary> [SerializeField] #pragma warning disable 649 private string[] startingItemList; #pragma warning restore 649 /// <summary> /// Index of which item in the dropdown list will be selected first /// </summary> [SerializeField] private int startingIndex = 0; private List<string> itemList = new List<string>(); /// <summary> /// List of all text item in dropdown menu /// </summary> public List<string> ItemList { get { return itemList; } set { itemList = value; } } /// <summary> /// Event, if different item is selected /// </summary> public event System.Action OnSelectedItemChange; public string SendMessageOnSelectedItemChangeMethodName = ""; private int index; /// <summary> /// Which list index is currently selected /// </summary> public int Index { get { return index; } set { index = Mathf.Clamp(value, 0, ItemList.Count - 1); SetSelectedItem(); } } /// <summary> /// Text of the currently selected dropdown list item /// </summary> public string SelectedItem { get { if (index >= 0 && index < itemList.Count) { return itemList[index]; } else { return ""; } } } public GameObject SendMessageTarget { get { if (dropDownButton != null) { return dropDownButton.sendMessageTarget; } else return null; } set { if (dropDownButton != null && dropDownButton.sendMessageTarget != value) { dropDownButton.sendMessageTarget = value; #if UNITY_EDITOR tk2dUtil.SetDirty(dropDownButton); #endif } } } private List<tk2dUIDropDownItem> dropDownItems = new List<tk2dUIDropDownItem>(); private bool isExpanded = false; //is currently in expanded state [SerializeField] [HideInInspector] private tk2dUILayout menuLayoutItem = null; public tk2dUILayout MenuLayoutItem { get { return menuLayoutItem; } set { menuLayoutItem = value; } } [SerializeField] [HideInInspector] private tk2dUILayout templateLayoutItem = null; public tk2dUILayout TemplateLayoutItem { get { return templateLayoutItem; } set { templateLayoutItem = value; } } void Awake() { foreach (string itemStr in startingItemList) { itemList.Add(itemStr); } index = startingIndex; #if UNITY_3_5 //disable all items in template, do make it so Unity 4.x works nicely dropDownItemTemplate.gameObject.SetActiveRecursively(false); #else dropDownItemTemplate.gameObject.SetActive(false); #endif UpdateList(); } void OnEnable() { dropDownButton.OnDown += ExpandButtonPressed; } void OnDisable() { dropDownButton.OnDown -= ExpandButtonPressed; } /// <summary> /// Updates all items in list. Need to call this after manipulating strings /// </summary> public void UpdateList() { Vector3 localPos; tk2dUIDropDownItem item; if (dropDownItems.Count > ItemList.Count) { for (int n = ItemList.Count; n < dropDownItems.Count; n++) { #if UNITY_3_5 dropDownItems[n].gameObject.SetActiveRecursively(false); #else dropDownItems[n].gameObject.SetActive(false); #endif } } while (dropDownItems.Count < ItemList.Count) { dropDownItems.Add(CreateAnotherDropDownItem()); } for (int p = 0; p < ItemList.Count; p++) { item = dropDownItems[p]; localPos = item.transform.localPosition; if (menuLayoutItem != null && templateLayoutItem != null) localPos.y = menuLayoutItem.bMin.y - (p * (templateLayoutItem.bMax.y - templateLayoutItem.bMin.y)); else localPos.y = -height - (p * item.height); item.transform.localPosition = localPos; if (item.label != null) { item.LabelText = itemList[p]; } item.Index = p; } SetSelectedItem(); } /// <summary> /// Sets the selected item (based on index) /// </summary> public void SetSelectedItem() { if (index < 0 || index >= ItemList.Count) { index = 0; } if (index >= 0 && index < ItemList.Count) { selectedTextMesh.text = ItemList[index]; selectedTextMesh.Commit(); } else { selectedTextMesh.text = ""; selectedTextMesh.Commit(); } if (OnSelectedItemChange != null) { OnSelectedItemChange(); } if (SendMessageTarget != null && SendMessageOnSelectedItemChangeMethodName.Length > 0) { SendMessageTarget.SendMessage( SendMessageOnSelectedItemChangeMethodName, this, SendMessageOptions.RequireReceiver ); } } //clones another dropdown item from template private tk2dUIDropDownItem CreateAnotherDropDownItem() { GameObject go = Instantiate(dropDownItemTemplate.gameObject) as GameObject; go.name = "DropDownItem"; go.transform.parent = transform; go.transform.localPosition = dropDownItemTemplate.transform.localPosition; go.transform.localRotation = dropDownItemTemplate.transform.localRotation; go.transform.localScale = dropDownItemTemplate.transform.localScale; tk2dUIDropDownItem item = go.GetComponent<tk2dUIDropDownItem>(); item.OnItemSelected += ItemSelected; tk2dUIUpDownHoverButton itemUpDownHoverBtn = go.GetComponent<tk2dUIUpDownHoverButton>(); item.upDownHoverBtn = itemUpDownHoverBtn; itemUpDownHoverBtn.OnToggleOver += DropDownItemHoverBtnToggle; #if UNITY_3_5 go.SetActiveRecursively(false); #endif return item; } //when an item in list is selected private void ItemSelected(tk2dUIDropDownItem item) { if (isExpanded) { CollapseList(); } Index = item.Index; } private void ExpandButtonPressed() { if (isExpanded) { CollapseList(); } else { ExpandList(); } } //drops list down private void ExpandList() { isExpanded = true; int count = Mathf.Min( ItemList.Count, dropDownItems.Count ); for(int i = 0; i < count; ++i) { #if UNITY_3_5 dropDownItems[i].gameObject.SetActiveRecursively(true); dropDownItems[i].upDownHoverBtn.SetState(); //deals with how active recursive needs to work in Unity 3.x #else dropDownItems[i].gameObject.SetActive(true); #endif } tk2dUIDropDownItem selectedItem = dropDownItems[index]; if (selectedItem.upDownHoverBtn != null) { selectedItem.upDownHoverBtn.IsOver = true; } } //collapses list on selecting item or closing private void CollapseList() { isExpanded = false; foreach (tk2dUIDropDownItem item in dropDownItems) { #if UNITY_3_5 item.gameObject.SetActiveRecursively(false); #else item.gameObject.SetActive(false); #endif } } private void DropDownItemHoverBtnToggle(tk2dUIUpDownHoverButton upDownHoverButton) { if (upDownHoverButton.IsOver) { foreach (tk2dUIDropDownItem item in dropDownItems) { if (item.upDownHoverBtn != upDownHoverButton && item.upDownHoverBtn != null) { item.upDownHoverBtn.IsOver = false; } } } } void OnDestroy() { foreach (tk2dUIDropDownItem item in dropDownItems) { item.OnItemSelected -= ItemSelected; if (item.upDownHoverBtn != null) { item.upDownHoverBtn.OnToggleOver -= DropDownItemHoverBtnToggle; } } } }
using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; using DG.Tweening; using System; public class MenuButtonPanelScript : MonoBehaviour { // Both of those below are dictated by this, those are only precentages while this controls all timings float animTime = 0.4f; // The time gap between the in and out animation happend float inOtDelay = 0.2f; // The time gap between the buttons going in and out float gapBetween = 0.2f; [Tooltip("Which button is pressed in order to birng out second panel")] public MenuButton mainButton; [Tooltip("The back button of the second panel")] public MenuButton backButton; [Tooltip("All of the buttons of the main button panel")] public MenuButton[] firstPanelButtons; [Tooltip("The buttons to bring out")] public MenuButton[] secondPanelButtons; private bool isSecondPanelShown = false; private int backButtonStackActionId; void Awake() { // If we haven't completed the tutorial don't bring in the menus if (!PreferencesScript.Instance.IsTutorialCompleted()) GetComponent<DOTweenAnimation>().DOKill(); } void Start () { // Get canvasgroup mainButton.canavasGroup = mainButton.rectTransform.GetComponent<CanvasGroup>(); backButton.canavasGroup = backButton.rectTransform.GetComponent<CanvasGroup>(); int mainAt = -1; for (int i = 0; i < firstPanelButtons.Length; i++) { firstPanelButtons[i].canavasGroup = firstPanelButtons[i].rectTransform.GetComponent<CanvasGroup>(); if (firstPanelButtons[i] == mainButton) { mainAt = i; } } // If the main button is not at the start of the array bring it there if (mainAt != 0) { MenuButton[] temp = new MenuButton[firstPanelButtons.Length]; temp[0] = firstPanelButtons[mainAt]; int at = 0; while (at < firstPanelButtons.Length) { if (at < mainAt) { temp[at + 1] = firstPanelButtons[at]; } else if (at == mainAt) { at++; } else { temp[at] = firstPanelButtons[at]; } at++; } firstPanelButtons = temp; } for (int i = 0; i < secondPanelButtons.Length; i++) secondPanelButtons[i].canavasGroup = secondPanelButtons[i].rectTransform.GetComponent<CanvasGroup>(); // Assign events mainButton.rectTransform.GetComponent<Button>().onClick.AddListener(new UnityAction(() => { ShowSecondPanel(); })); backButton.rectTransform.GetComponent<Button>().onClick.AddListener(new UnityAction(() => { HideSecondPanel(); })); } public void ShowSecondPanel() { if (isSecondPanelShown) return; isSecondPanelShown = true; Sequence seq = DOTween.Sequence() // Prepare for aniamtion .OnStart(new TweenCallback(() => { // Set all to starting pos and make it interactable for (int i = 0; i < secondPanelButtons.Length; i++) { secondPanelButtons[i].rectTransform.localPosition = new Vector3(secondPanelButtons[i].rectTransform.rect.width / 2f, secondPanelButtons[i].rectTransform.localPosition.y); secondPanelButtons[i].canavasGroup.interactable = true; secondPanelButtons[i].canavasGroup.blocksRaycasts = true; } // Set main buttons to uninteractable for (int i = 0; i < firstPanelButtons.Length; i++) { firstPanelButtons[i].canavasGroup.interactable = false; firstPanelButtons[i].canavasGroup.blocksRaycasts = false; } })) // Put everything in place - Afetr part .OnComplete(new TweenCallback(() => { for (int i = 0; i < firstPanelButtons.Length; i++) { firstPanelButtons[i].rectTransform.localPosition = new Vector3(-firstPanelButtons[i].rectTransform.rect.width * 2f, firstPanelButtons[i].rectTransform.localPosition.y); } })); // out animation (move and fade) for (int i = 0; i < firstPanelButtons.Length; i++) { float atTime = animTime * (i * gapBetween); seq.Insert(atTime, firstPanelButtons[i].rectTransform.DOLocalMoveX(-firstPanelButtons[i].rectTransform.rect.width / 2f, animTime)); seq.Insert(atTime, firstPanelButtons[i].canavasGroup.DOFade(0f, animTime)); } // in animations (move and fade) for (int i = 0; i < secondPanelButtons.Length; i++) { float atTime = (animTime * (((firstPanelButtons.Length - 1 + i) * gapBetween) + inOtDelay)); seq.Insert(atTime, secondPanelButtons[i].rectTransform.DOLocalMoveX(0, animTime)); seq.Insert(atTime, secondPanelButtons[i].canavasGroup.DOFade(1f, animTime)); } backButtonStackActionId = ScaneManager.Instance.AddToBackStack(() => { HideSecondPanel(); }); } public void HideSecondPanel() { if (!isSecondPanelShown) return; isSecondPanelShown = false; Sequence seq = DOTween.Sequence() // Prepare for aniamtion .OnStart(new TweenCallback(() => { // Set all to starting pos and make it interactable for (int i = 0; i < firstPanelButtons.Length; i++) { firstPanelButtons[i].rectTransform.localPosition = new Vector3(-firstPanelButtons[i].rectTransform.rect.width / 2f, firstPanelButtons[i].rectTransform.localPosition.y); firstPanelButtons[i].canavasGroup.interactable = true; firstPanelButtons[i].canavasGroup.blocksRaycasts = true; } // Set second buttons to uninteractable for (int i = 0; i < secondPanelButtons.Length; i++) { secondPanelButtons[i].canavasGroup.interactable = false; secondPanelButtons[i].canavasGroup.blocksRaycasts = false; } })) // Put everything in place - Afetr part .OnComplete(new TweenCallback(() => { for (int i = 0; i < secondPanelButtons.Length; i++) { secondPanelButtons[i].rectTransform.localPosition = new Vector3(0, secondPanelButtons[i].rectTransform.localPosition.y); } })); // out animation (move and fade) for (int i = 0; i < secondPanelButtons.Length; i++) { float atTime = animTime * (i * gapBetween); seq.Insert(atTime, secondPanelButtons[i].rectTransform.DOLocalMoveX(secondPanelButtons[i].rectTransform.rect.width / 2f, animTime)); seq.Insert(atTime, secondPanelButtons[i].canavasGroup.DOFade(0f, animTime)); } // in animations (move and fade) for (int i = 0; i < firstPanelButtons.Length; i++) { float atTime = (animTime * (((secondPanelButtons.Length - 1 + i) * gapBetween) + inOtDelay)); seq.Insert(atTime, firstPanelButtons[i].rectTransform.DOLocalMoveX(0, animTime)); seq.Insert(atTime, firstPanelButtons[i].canavasGroup.DOFade(1f, animTime)); } ScaneManager.Instance.RemoveFromBackStack(backButtonStackActionId); } } [Serializable] public struct MenuButton { public RectTransform rectTransform; [HideInInspector] public CanvasGroup canavasGroup; public MenuButton(RectTransform rectTransform, CanvasGroup canvasGroup) { this.rectTransform = rectTransform; this.canavasGroup = canvasGroup; } public static bool operator ==(MenuButton one, MenuButton two) { return one.rectTransform.gameObject.name == two.rectTransform.gameObject.name; } public static bool operator !=(MenuButton one, MenuButton two) { return one.rectTransform.gameObject.name != two.rectTransform.gameObject.name; } public override bool Equals(object obj) { if (obj is MenuButton) { return this == (MenuButton) obj; } return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MGTK.EventArguments; using MGTK.Services; using MGTK.Messaging; namespace MGTK.Controls { public class ComboBox : Control { protected InnerTextBox innerTextBox; protected ListBox listBox; protected Button btnExpand; protected int InitialWidth; protected int InitialHeight; protected int ListBoxHeight = 64; protected bool ShowingListBox = false; private int MsToNextIndex = 150; private double LastUpdateIndexChange; public object SelectedValue { get { return listBox.SelectedValue; } set { listBox.SelectedValue = value; } } public int SelectedIndex { get { return listBox.SelectedIndex; } set { listBox.SelectedIndex = value; } } public List<ListBoxItem> Items { get { return listBox.Items; } set { listBox.Items = value; } } public event EventHandler SelectedIndexChanged; public ComboBox(Form formowner) : base(formowner) { btnExpand = new Button(formowner); listBox = new ListBox(formowner); innerTextBox = new InnerTextBox(formowner); btnExpand.Parent = listBox.Parent = innerTextBox.Parent = this; innerTextBox.MultiLine = false; btnExpand.Image = Theme.ComboButton; btnExpand.Click += new EventHandler(btnExpand_Click); listBox.ListItemClick += new EventHandler(listBox_ListItemClick); listBox.SelectedIndexChanged += new EventHandler(listBox_SelectedIndexChanged); listBox.KeyDown += new ControlKeyEventHandler(listBox_KeyDown); this.Controls.AddRange(new Control[] { btnExpand, listBox, innerTextBox }); this.Init += new EventHandler(ComboBox_Init); this.WidthChanged += new EventHandler(ComboBox_SizeChanged); this.HeightChanged += new EventHandler(ComboBox_SizeChanged); this.KeyDown += new ControlKeyEventHandler(ComboBox_KeyDown); innerTextBox.KeyDown += new ControlKeyEventHandler(ComboBox_KeyDown); } void listBox_ListItemClick(object sender, EventArgs e) { SelectListItem(); } void listBox_SelectedIndexChanged(object sender, EventArgs e) { if (SelectedIndexChanged != null) SelectedIndexChanged(this, new EventArgs()); SelectListItem(); } private void SelectListItem() { if (listBox.SelectedIndex < 0) return; ToggleListBox(false); innerTextBox.Text = listBox.Items[listBox.SelectedIndex].Text; innerTextBox.ScrollX = 0; innerTextBox.CursorX = 0; } public override bool ReceiveMessage(MessageEnum message, object msgTag) { if (message == MessageEnum.MouseLeftPressed) if (!MouseIsOnControl(false)) ToggleListBox(false); return base.ReceiveMessage(message, msgTag); } void listBox_KeyDown(object sender, ControlKeyEventArgs e) { if (e.Key == Keys.Enter) { SelectListItem(); } } void btnExpand_Click(object sender, EventArgs e) { btnExpand.Focused = false; ToggleListBox(!ShowingListBox); } void ComboBox_KeyDown(object sender, ControlKeyEventArgs e) { if (e.Key == Keys.Up || e.Key == Keys.Down) { if (gameTime.TotalGameTime.TotalMilliseconds - LastUpdateIndexChange > MsToNextIndex) { SelectedIndex += e.Key == Keys.Up ? -1 : 1; LastUpdateIndexChange = gameTime.TotalGameTime.TotalMilliseconds; } } } void ComboBox_SizeChanged(object sender, EventArgs e) { if (!ShowingListBox) { InitialWidth = this.Width; InitialHeight = this.Height; } } void ComboBox_Init(object sender, EventArgs e) { ConfigureCoordinatesAndSizes(); } public override void Draw() { DrawingService.DrawFrame(SpriteBatchProvider, Theme.ComboFrame, OwnerX + X, OwnerY + Y, InitialWidth, InitialHeight, Z - 0.001f); base.Draw(); } public override void Update() { btnExpand.Z = Z - 0.0015f; listBox.Z = Z - 0.0015f; base.Update(); } public void ToggleListBox(bool Show) { ShowingListBox = Show; listBox.Visible = Show; if (Show) { listBox.Y = InitialHeight; InitialHeight = Height; listBox.Focus(); btnExpand.Anchor = AnchorStyles.Top | AnchorStyles.Right; innerTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; } else { btnExpand.Anchor = AnchorStyles.Top | AnchorStyles.Left; innerTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left; } Height = (Show ? ListBoxHeight : 0) + InitialHeight; if (!Show) { btnExpand.Anchor = AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Top; innerTextBox.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; } } private void ConfigureCoordinatesAndSizes() { listBox.X = 0; listBox.Y = InitialHeight; listBox.Width = InitialWidth; listBox.Height = ListBoxHeight; listBox.Visible = false; listBox.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; btnExpand.Y = 2; btnExpand.Height = InitialHeight - 4; btnExpand.Width = btnExpand.Height; btnExpand.X = InitialWidth - btnExpand.Width - 2; btnExpand.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right; innerTextBox.Y = 2; innerTextBox.X = 2; innerTextBox.Width = InitialWidth - btnExpand.Width - 2 - 3; innerTextBox.Height = InitialHeight - 4; innerTextBox.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; using Encoding = System.Text.Encoding; namespace System.Xml.Linq { /// <summary> /// Represents an XML document. /// </summary> /// <remarks> /// An <see cref="XDocument"/> can contain: /// <list> /// <item> /// A Document Type Declaration (DTD), see <see cref="XDocumentType"/> /// </item> /// <item>One root element.</item> /// <item>Zero or more <see cref="XComment"/> objects.</item> /// <item>Zero or more <see cref="XProcessingInstruction"/> objects.</item> /// </list> /// </remarks> public class XDocument : XContainer { XDeclaration declaration; ///<overloads> /// Initializes a new instance of the <see cref="XDocument"/> class. /// Overloaded constructors are provided for creating a new empty /// <see cref="XDocument"/>, creating an <see cref="XDocument"/> with /// a parameter list of initial content, and as a copy of another /// <see cref="XDocument"/> object. /// </overloads> /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class. /// </summary> public XDocument() { } /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class with the specified content. /// </summary> /// <param name="content"> /// A parameter list of content objects to add to this document. /// </param> /// <remarks> /// Valid content includes: /// <list> /// <item>Zero or one <see cref="XDocumentType"/> objects</item> /// <item>Zero or one elements</item> /// <item>Zero or more comments</item> /// <item>Zero or more processing instructions</item> /// </list> /// See <see cref="XContainer.Add(object)"/> for details about the content that can be added /// using this method. /// </remarks> public XDocument(params object[] content) : this() { AddContentSkipNotify(content); } /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class /// with the specified <see cref="XDeclaration"/> and content. /// </summary> /// <param name="declaration"> /// The XML declaration for the document. /// </param> /// <param name="content"> /// The contents of the document. /// </param> /// <remarks> /// Valid content includes: /// <list> /// <item>Zero or one <see cref="XDocumentType"/> objects</item> /// <item>Zero or one elements</item> /// <item>Zero or more comments</item> /// <item>Zero or more processing instructions</item> /// <item></item> /// </list> /// See <see cref="XContainer.Add(object)"/> for details about the content that can be added /// using this method. /// </remarks> public XDocument(XDeclaration declaration, params object[] content) : this(content) { this.declaration = declaration; } /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class from an /// existing XDocument object. /// </summary> /// <param name="other"> /// The <see cref="XDocument"/> object that will be copied. /// </param> public XDocument(XDocument other) : base(other) { if (other.declaration != null) { declaration = new XDeclaration(other.declaration); } } /// <summary> /// Gets the XML declaration for this document. /// </summary> public XDeclaration Declaration { get { return declaration; } set { declaration = value; } } /// <summary> /// Gets the Document Type Definition (DTD) for this document. /// </summary> public XDocumentType DocumentType { get { return GetFirstNode<XDocumentType>(); } } /// <summary> /// Gets the node type for this node. /// </summary> /// <remarks> /// This property will always return XmlNodeType.Document. /// </remarks> public override XmlNodeType NodeType { get { return XmlNodeType.Document; } } /// <summary> /// Gets the root element of the XML Tree for this document. /// </summary> public XElement Root { get { return GetFirstNode<XElement>(); } } /// <overloads> /// The Load method provides multiple strategies for creating a new /// <see cref="XDocument"/> and initializing it from a data source containing /// raw XML. Load from a file (passing in a URI to the file), a /// <see cref="Stream"/>, a <see cref="TextReader"/>, or an /// <see cref="XmlReader"/>. Note: Use <see cref="XDocument.Parse(string)"/> /// to create an <see cref="XDocument"/> from a string containing XML. /// <seealso cref="XDocument.Parse(string)"/> /// </overloads> /// <summary> /// Create a new <see cref="XDocument"/> based on the contents of the file /// referenced by the URI parameter passed in. Note: Use /// <see cref="XDocument.Parse(string)"/> to create an <see cref="XDocument"/> from /// a string containing XML. /// <seealso cref="XmlReader.Create(string)"/> /// <seealso cref="XDocument.Parse(string)"/> /// </summary> /// <remarks> /// This method uses the <see cref="XmlReader.Create(string)"/> method to create /// an <see cref="XmlReader"/> to read the raw XML into the underlying /// XML tree. /// </remarks> /// <param name="uri"> /// A URI string referencing the file to load into a new <see cref="XDocument"/>. /// </param> /// <returns> /// An <see cref="XDocument"/> initialized with the contents of the file referenced /// in the passed in uri parameter. /// </returns> [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Back-compat with System.Xml.")] public static XDocument Load(string uri) { return Load(uri, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> based on the contents of the file /// referenced by the URI parameter passed in. Optionally, whitespace can be preserved. /// <see cref="XmlReader.Create(string)"/> /// </summary> /// <remarks> /// This method uses the <see cref="XmlReader.Create(string)"/> method to create /// an <see cref="XmlReader"/> to read the raw XML into an underlying /// XML tree. If LoadOptions.PreserveWhitespace is enabled then /// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/> /// is set to false. /// </remarks> /// <param name="uri"> /// A string representing the URI of the file to be loaded into a new <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// An <see cref="XDocument"/> initialized with the contents of the file referenced /// in the passed uri parameter. If LoadOptions.PreserveWhitespace is enabled then /// all whitespace will be preserved. /// </returns> [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Back-compat with System.Xml.")] public static XDocument Load(string uri, LoadOptions options) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(uri, rs)) { return Load(r, options); } } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="Stream"/> parameter. /// </summary> /// <param name="stream"> /// A <see cref="Stream"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="Stream"/>. /// </returns> public static XDocument Load(Stream stream) { return Load(stream, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="Stream"/> parameter. Optionally whitespace handling /// can be preserved. /// </summary> /// <remarks> /// If LoadOptions.PreserveWhitespace is enabled then /// the underlying <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/> /// is set to false. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="Stream"/>. /// </returns> public static XDocument Load(Stream stream, LoadOptions options) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(stream, rs)) { return Load(r, options); } } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="TextReader"/> parameter. /// </summary> /// <param name="textReader"> /// A <see cref="TextReader"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="TextReader"/>. /// </returns> public static XDocument Load(TextReader textReader) { return Load(textReader, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="TextReader"/> parameter. Optionally whitespace handling /// can be preserved. /// </summary> /// <remarks> /// If LoadOptions.PreserveWhitespace is enabled then /// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/> /// is set to false. /// </remarks> /// <param name="textReader"> /// A <see cref="TextReader"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="TextReader"/>. /// </returns> public static XDocument Load(TextReader textReader, LoadOptions options) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(textReader, rs)) { return Load(r, options); } } /// <summary> /// Create a new <see cref="XDocument"/> containing the contents of the /// passed in <see cref="XmlReader"/>. /// </summary> /// <param name="reader"> /// An <see cref="XmlReader"/> containing the XML to be read into the new /// <see cref="XDocument"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed /// in <see cref="XmlReader"/>. /// </returns> public static XDocument Load(XmlReader reader) { return Load(reader, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> containing the contents of the /// passed in <see cref="XmlReader"/>. /// </summary> /// <param name="reader"> /// An <see cref="XmlReader"/> containing the XML to be read into the new /// <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed /// in <see cref="XmlReader"/>. /// </returns> public static XDocument Load(XmlReader reader, LoadOptions options) { if (reader == null) throw new ArgumentNullException("reader"); if (reader.ReadState == ReadState.Initial) reader.Read(); XDocument d = new XDocument(); if ((options & LoadOptions.SetBaseUri) != 0) { string baseUri = reader.BaseURI; if (baseUri != null && baseUri.Length != 0) { d.SetBaseUri(baseUri); } } if ((options & LoadOptions.SetLineInfo) != 0) { IXmlLineInfo li = reader as IXmlLineInfo; if (li != null && li.HasLineInfo()) { d.SetLineInfo(li.LineNumber, li.LinePosition); } } if (reader.NodeType == XmlNodeType.XmlDeclaration) { d.Declaration = new XDeclaration(reader); } d.ReadContentFrom(reader, options); if (!reader.EOF) throw new InvalidOperationException(SR.InvalidOperation_ExpectedEndOfFile); if (d.Root == null) throw new InvalidOperationException(SR.InvalidOperation_MissingRoot); return d; } /// <overloads> /// Create a new <see cref="XDocument"/> from a string containing /// XML. Optionally whitespace can be preserved. /// </overloads> /// <summary> /// Create a new <see cref="XDocument"/> from a string containing /// XML. /// </summary> /// <param name="text"> /// A string containing XML. /// </param> /// <returns> /// An <see cref="XDocument"/> containing an XML tree initialized from the /// passed in XML string. /// </returns> public static XDocument Parse(string text) { return Parse(text, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> from a string containing /// XML. Optionally whitespace can be preserved. /// </summary> /// <remarks> /// This method uses <see cref="XmlReader.Create(TextReader, XmlReaderSettings)"/>, /// passing it a StringReader constructed from the passed in XML String. If /// <see cref="LoadOptions.PreserveWhitespace"/> is enabled then /// <see cref="XmlReaderSettings.IgnoreWhitespace"/> is set to false. See /// <see cref="XmlReaderSettings.IgnoreWhitespace"/> for more information on /// whitespace handling. /// </remarks> /// <param name="text"> /// A string containing XML. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// An <see cref="XDocument"/> containing an XML tree initialized from the /// passed in XML string. /// </returns> public static XDocument Parse(string text, LoadOptions options) { using (StringReader sr = new StringReader(text)) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(sr, rs)) { return Load(r, options); } } } /// <summary> /// Output this <see cref="XDocument"/> to the passed in <see cref="Stream"/>. /// </summary> /// <remarks> /// The format will be indented by default. If you want /// no indenting then use the SaveOptions version of Save (see /// <see cref="XDocument.Save(Stream, SaveOptions)"/>) enabling /// SaveOptions.DisableFormatting /// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations. /// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options. /// </remarks> /// <param name="stream"> /// The <see cref="Stream"/> to output this <see cref="XDocument"/> to. /// </param> public void Save(Stream stream) { Save(stream, GetSaveOptionsFromAnnotations()); } /// <summary> /// Output this <see cref="XDocument"/> to a <see cref="Stream"/>. /// </summary> /// <param name="stream"> /// The <see cref="Stream"/> to output the XML to. /// </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(Stream stream, SaveOptions options) { XmlWriterSettings ws = GetXmlWriterSettings(options); if (declaration != null && !string.IsNullOrEmpty(declaration.Encoding)) { try { ws.Encoding = Encoding.GetEncoding(declaration.Encoding); } catch (ArgumentException) { } } using (XmlWriter w = XmlWriter.Create(stream, ws)) { Save(w); } } /// <summary> /// Output this <see cref="XDocument"/> to the passed in <see cref="TextWriter"/>. /// </summary> /// <remarks> /// The format will be indented by default. If you want /// no indenting then use the SaveOptions version of Save (see /// <see cref="XDocument.Save(TextWriter, SaveOptions)"/>) enabling /// SaveOptions.DisableFormatting /// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations. /// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options. /// </remarks> /// <param name="textWriter"> /// The <see cref="TextWriter"/> to output this <see cref="XDocument"/> to. /// </param> public void Save(TextWriter textWriter) { Save(textWriter, GetSaveOptionsFromAnnotations()); } /// <summary> /// Output this <see cref="XDocument"/> to a <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter"> /// The <see cref="TextWriter"/> to output the XML to. /// </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(TextWriter textWriter, SaveOptions options) { XmlWriterSettings ws = GetXmlWriterSettings(options); using (XmlWriter w = XmlWriter.Create(textWriter, ws)) { Save(w); } } /// <summary> /// Output this <see cref="XDocument"/> to an <see cref="XmlWriter"/>. /// </summary> /// <param name="writer"> /// The <see cref="XmlWriter"/> to output the XML to. /// </param> public void Save(XmlWriter writer) { WriteTo(writer); } /// <summary> /// Output this <see cref="XDocument"/>'s underlying XML tree to the /// passed in <see cref="XmlWriter"/>. /// <seealso cref="XDocument.Save(XmlWriter)"/> /// </summary> /// <param name="writer"> /// The <see cref="XmlWriter"/> to output the content of this /// <see cref="XDocument"/>. /// </param> public override void WriteTo(XmlWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); if (declaration != null && declaration.Standalone == "yes") { writer.WriteStartDocument(true); } else if (declaration != null && declaration.Standalone == "no") { writer.WriteStartDocument(false); } else { writer.WriteStartDocument(); } WriteContentTo(writer); writer.WriteEndDocument(); } internal override void AddAttribute(XAttribute a) { throw new ArgumentException(SR.Argument_AddAttribute); } internal override void AddAttributeSkipNotify(XAttribute a) { throw new ArgumentException(SR.Argument_AddAttribute); } internal override XNode CloneNode() { return new XDocument(this); } internal override bool DeepEquals(XNode node) { XDocument other = node as XDocument; return other != null && ContentsEqual(other); } internal override int GetDeepHashCode() { return ContentsHashCode(); } T GetFirstNode<T>() where T : XNode { XNode n = content as XNode; if (n != null) { do { n = n.next; T e = n as T; if (e != null) return e; } while (n != content); } return null; } internal static bool IsWhitespace(string s) { foreach (char ch in s) { if (ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n') return false; } return true; } internal override void ValidateNode(XNode node, XNode previous) { switch (node.NodeType) { case XmlNodeType.Text: ValidateString(((XText)node).Value); break; case XmlNodeType.Element: ValidateDocument(previous, XmlNodeType.DocumentType, XmlNodeType.None); break; case XmlNodeType.DocumentType: ValidateDocument(previous, XmlNodeType.None, XmlNodeType.Element); break; case XmlNodeType.CDATA: throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.CDATA)); case XmlNodeType.Document: throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.Document)); } } void ValidateDocument(XNode previous, XmlNodeType allowBefore, XmlNodeType allowAfter) { XNode n = content as XNode; if (n != null) { if (previous == null) allowBefore = allowAfter; do { n = n.next; XmlNodeType nt = n.NodeType; if (nt == XmlNodeType.Element || nt == XmlNodeType.DocumentType) { if (nt != allowBefore) throw new InvalidOperationException(SR.InvalidOperation_DocumentStructure); allowBefore = XmlNodeType.None; } if (n == previous) allowBefore = allowAfter; } while (n != content); } } internal override void ValidateString(string s) { if (!IsWhitespace(s)) throw new ArgumentException(SR.Argument_AddNonWhitespace); } } }
/* * 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 elasticache-2015-02-02.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.ElastiCache.Model; namespace Amazon.ElastiCache { /// <summary> /// Interface for accessing ElastiCache /// /// Amazon ElastiCache /// <para> /// Amazon ElastiCache is a web service that makes it easier to set up, operate, and scale /// a distributed cache in the cloud. /// </para> /// /// <para> /// With ElastiCache, customers gain all of the benefits of a high-performance, in-memory /// cache with far less of the administrative burden of launching and managing a distributed /// cache. The service makes setup, scaling, and cluster failure handling much simpler /// than in a self-managed cache deployment. /// </para> /// /// <para> /// In addition, through integration with Amazon CloudWatch, customers get enhanced visibility /// into the key performance statistics associated with their cache and can receive alarms /// if a part of their cache runs hot. /// </para> /// </summary> public partial interface IAmazonElastiCache : IDisposable { #region AddTagsToResource /// <summary> /// Initiates the asynchronous execution of the AddTagsToResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AddTagsToResource 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> Task<AddTagsToResourceResponse> AddTagsToResourceAsync(AddTagsToResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region AuthorizeCacheSecurityGroupIngress /// <summary> /// Initiates the asynchronous execution of the AuthorizeCacheSecurityGroupIngress operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AuthorizeCacheSecurityGroupIngress 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> Task<AuthorizeCacheSecurityGroupIngressResponse> AuthorizeCacheSecurityGroupIngressAsync(AuthorizeCacheSecurityGroupIngressRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CopySnapshot /// <summary> /// Initiates the asynchronous execution of the CopySnapshot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CopySnapshot 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> Task<CopySnapshotResponse> CopySnapshotAsync(CopySnapshotRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateCacheCluster /// <summary> /// Initiates the asynchronous execution of the CreateCacheCluster operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateCacheCluster 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> Task<CreateCacheClusterResponse> CreateCacheClusterAsync(CreateCacheClusterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateCacheParameterGroup /// <summary> /// Initiates the asynchronous execution of the CreateCacheParameterGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateCacheParameterGroup 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> Task<CreateCacheParameterGroupResponse> CreateCacheParameterGroupAsync(CreateCacheParameterGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateCacheSecurityGroup /// <summary> /// Initiates the asynchronous execution of the CreateCacheSecurityGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateCacheSecurityGroup 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> Task<CreateCacheSecurityGroupResponse> CreateCacheSecurityGroupAsync(CreateCacheSecurityGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateCacheSubnetGroup /// <summary> /// Initiates the asynchronous execution of the CreateCacheSubnetGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateCacheSubnetGroup 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> Task<CreateCacheSubnetGroupResponse> CreateCacheSubnetGroupAsync(CreateCacheSubnetGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateReplicationGroup /// <summary> /// Initiates the asynchronous execution of the CreateReplicationGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateReplicationGroup 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> Task<CreateReplicationGroupResponse> CreateReplicationGroupAsync(CreateReplicationGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateSnapshot /// <summary> /// Initiates the asynchronous execution of the CreateSnapshot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateSnapshot 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> Task<CreateSnapshotResponse> CreateSnapshotAsync(CreateSnapshotRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteCacheCluster /// <summary> /// Initiates the asynchronous execution of the DeleteCacheCluster operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteCacheCluster 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> Task<DeleteCacheClusterResponse> DeleteCacheClusterAsync(DeleteCacheClusterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteCacheParameterGroup /// <summary> /// Initiates the asynchronous execution of the DeleteCacheParameterGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteCacheParameterGroup 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> Task<DeleteCacheParameterGroupResponse> DeleteCacheParameterGroupAsync(DeleteCacheParameterGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteCacheSecurityGroup /// <summary> /// Initiates the asynchronous execution of the DeleteCacheSecurityGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteCacheSecurityGroup 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> Task<DeleteCacheSecurityGroupResponse> DeleteCacheSecurityGroupAsync(DeleteCacheSecurityGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteCacheSubnetGroup /// <summary> /// Initiates the asynchronous execution of the DeleteCacheSubnetGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteCacheSubnetGroup 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> Task<DeleteCacheSubnetGroupResponse> DeleteCacheSubnetGroupAsync(DeleteCacheSubnetGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteReplicationGroup /// <summary> /// Initiates the asynchronous execution of the DeleteReplicationGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteReplicationGroup 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> Task<DeleteReplicationGroupResponse> DeleteReplicationGroupAsync(DeleteReplicationGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteSnapshot /// <summary> /// Initiates the asynchronous execution of the DeleteSnapshot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteSnapshot 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> Task<DeleteSnapshotResponse> DeleteSnapshotAsync(DeleteSnapshotRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeCacheClusters /// <summary> /// The <i>DescribeCacheClusters</i> action returns information about all provisioned /// cache clusters if no cache cluster identifier is specified, or about a specific cache /// cluster if a cache cluster identifier is supplied. /// /// /// <para> /// By default, abbreviated information about the cache clusters(s) will be returned. /// You can use the optional <i>ShowDetails</i> flag to retrieve detailed information /// about the cache nodes associated with the cache clusters. These details include the /// DNS address and port for the cache node endpoint. /// </para> /// /// <para> /// If the cluster is in the CREATING state, only cluster level information will be displayed /// until all of the nodes are successfully provisioned. /// </para> /// /// <para> /// If the cluster is in the DELETING state, only cluster level information will be displayed. /// </para> /// /// <para> /// If cache nodes are currently being added to the cache cluster, node endpoint information /// and creation time for the additional nodes will not be displayed until they are completely /// provisioned. When the cache cluster state is <i>available</i>, the cluster is ready /// for use. /// </para> /// /// <para> /// If cache nodes are currently being removed from the cache cluster, no endpoint information /// for the removed nodes is displayed. /// </para> /// </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 DescribeCacheClusters service method, as returned by ElastiCache.</returns> /// <exception cref="Amazon.ElastiCache.Model.CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> Task<DescribeCacheClustersResponse> DescribeCacheClustersAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeCacheClusters operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheClusters 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> Task<DescribeCacheClustersResponse> DescribeCacheClustersAsync(DescribeCacheClustersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeCacheEngineVersions /// <summary> /// The <i>DescribeCacheEngineVersions</i> action returns a list of the available cache /// engines and their versions. /// </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 DescribeCacheEngineVersions service method, as returned by ElastiCache.</returns> Task<DescribeCacheEngineVersionsResponse> DescribeCacheEngineVersionsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeCacheEngineVersions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheEngineVersions 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> Task<DescribeCacheEngineVersionsResponse> DescribeCacheEngineVersionsAsync(DescribeCacheEngineVersionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeCacheParameterGroups /// <summary> /// The <i>DescribeCacheParameterGroups</i> action returns a list of cache parameter group /// descriptions. If a cache parameter group name is specified, the list will contain /// only the descriptions for that group. /// </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 DescribeCacheParameterGroups service method, as returned by ElastiCache.</returns> /// <exception cref="Amazon.ElastiCache.Model.CacheParameterGroupNotFoundException"> /// The requested cache parameter group name does not refer to an existing cache parameter /// group. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> Task<DescribeCacheParameterGroupsResponse> DescribeCacheParameterGroupsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeCacheParameterGroups operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheParameterGroups 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> Task<DescribeCacheParameterGroupsResponse> DescribeCacheParameterGroupsAsync(DescribeCacheParameterGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeCacheParameters /// <summary> /// Initiates the asynchronous execution of the DescribeCacheParameters operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheParameters 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> Task<DescribeCacheParametersResponse> DescribeCacheParametersAsync(DescribeCacheParametersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeCacheSecurityGroups /// <summary> /// The <i>DescribeCacheSecurityGroups</i> action returns a list of cache security group /// descriptions. If a cache security group name is specified, the list will contain only /// the description of that group. /// </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 DescribeCacheSecurityGroups service method, as returned by ElastiCache.</returns> /// <exception cref="Amazon.ElastiCache.Model.CacheSecurityGroupNotFoundException"> /// The requested cache security group name does not refer to an existing cache security /// group. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> Task<DescribeCacheSecurityGroupsResponse> DescribeCacheSecurityGroupsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeCacheSecurityGroups operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheSecurityGroups 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> Task<DescribeCacheSecurityGroupsResponse> DescribeCacheSecurityGroupsAsync(DescribeCacheSecurityGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeCacheSubnetGroups /// <summary> /// The <i>DescribeCacheSubnetGroups</i> action returns a list of cache subnet group descriptions. /// If a subnet group name is specified, the list will contain only the description of /// that group. /// </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 DescribeCacheSubnetGroups service method, as returned by ElastiCache.</returns> /// <exception cref="Amazon.ElastiCache.Model.CacheSubnetGroupNotFoundException"> /// The requested cache subnet group name does not refer to an existing cache subnet group. /// </exception> Task<DescribeCacheSubnetGroupsResponse> DescribeCacheSubnetGroupsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeCacheSubnetGroups operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheSubnetGroups 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> Task<DescribeCacheSubnetGroupsResponse> DescribeCacheSubnetGroupsAsync(DescribeCacheSubnetGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeEngineDefaultParameters /// <summary> /// Initiates the asynchronous execution of the DescribeEngineDefaultParameters operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEngineDefaultParameters 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> Task<DescribeEngineDefaultParametersResponse> DescribeEngineDefaultParametersAsync(DescribeEngineDefaultParametersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeEvents /// <summary> /// The <i>DescribeEvents</i> action returns events related to cache clusters, cache security /// groups, and cache parameter groups. You can obtain events specific to a particular /// cache cluster, cache security group, or cache parameter group by providing the name /// as a parameter. /// /// /// <para> /// By default, only the events occurring within the last hour are returned; however, /// you can retrieve up to 14 days' worth of events if necessary. /// </para> /// </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 DescribeEvents service method, as returned by ElastiCache.</returns> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> Task<DescribeEventsResponse> DescribeEventsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeEvents operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEvents 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> Task<DescribeEventsResponse> DescribeEventsAsync(DescribeEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeReplicationGroups /// <summary> /// The <i>DescribeReplicationGroups</i> action returns information about a particular /// replication group. If no identifier is specified, <i>DescribeReplicationGroups</i> /// returns information about all replication groups. /// </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 DescribeReplicationGroups service method, as returned by ElastiCache.</returns> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.ReplicationGroupNotFoundException"> /// The specified replication group does not exist. /// </exception> Task<DescribeReplicationGroupsResponse> DescribeReplicationGroupsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeReplicationGroups operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationGroups 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> Task<DescribeReplicationGroupsResponse> DescribeReplicationGroupsAsync(DescribeReplicationGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeReservedCacheNodes /// <summary> /// The <i>DescribeReservedCacheNodes</i> action returns information about reserved cache /// nodes for this account, or about a specified reserved cache node. /// </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 DescribeReservedCacheNodes service method, as returned by ElastiCache.</returns> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.ReservedCacheNodeNotFoundException"> /// The requested reserved cache node was not found. /// </exception> Task<DescribeReservedCacheNodesResponse> DescribeReservedCacheNodesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeReservedCacheNodes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReservedCacheNodes 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> Task<DescribeReservedCacheNodesResponse> DescribeReservedCacheNodesAsync(DescribeReservedCacheNodesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeReservedCacheNodesOfferings /// <summary> /// The <i>DescribeReservedCacheNodesOfferings</i> action lists available reserved cache /// node offerings. /// </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 DescribeReservedCacheNodesOfferings service method, as returned by ElastiCache.</returns> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.ReservedCacheNodesOfferingNotFoundException"> /// The requested cache node offering does not exist. /// </exception> Task<DescribeReservedCacheNodesOfferingsResponse> DescribeReservedCacheNodesOfferingsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeReservedCacheNodesOfferings operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReservedCacheNodesOfferings 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> Task<DescribeReservedCacheNodesOfferingsResponse> DescribeReservedCacheNodesOfferingsAsync(DescribeReservedCacheNodesOfferingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeSnapshots /// <summary> /// The <i>DescribeSnapshots</i> action returns information about cache cluster snapshots. /// By default, <i>DescribeSnapshots</i> lists all of your snapshots; it can optionally /// describe a single snapshot, or just the snapshots associated with a particular cache /// cluster. /// </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 DescribeSnapshots service method, as returned by ElastiCache.</returns> /// <exception cref="Amazon.ElastiCache.Model.CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="Amazon.ElastiCache.Model.SnapshotNotFoundException"> /// The requested snapshot name does not refer to an existing snapshot. /// </exception> Task<DescribeSnapshotsResponse> DescribeSnapshotsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeSnapshots operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots 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> Task<DescribeSnapshotsResponse> DescribeSnapshotsAsync(DescribeSnapshotsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListTagsForResource /// <summary> /// Initiates the asynchronous execution of the ListTagsForResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListTagsForResource 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> Task<ListTagsForResourceResponse> ListTagsForResourceAsync(ListTagsForResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ModifyCacheCluster /// <summary> /// Initiates the asynchronous execution of the ModifyCacheCluster operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyCacheCluster 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> Task<ModifyCacheClusterResponse> ModifyCacheClusterAsync(ModifyCacheClusterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ModifyCacheParameterGroup /// <summary> /// Initiates the asynchronous execution of the ModifyCacheParameterGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyCacheParameterGroup 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> Task<ModifyCacheParameterGroupResponse> ModifyCacheParameterGroupAsync(ModifyCacheParameterGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ModifyCacheSubnetGroup /// <summary> /// Initiates the asynchronous execution of the ModifyCacheSubnetGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyCacheSubnetGroup 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> Task<ModifyCacheSubnetGroupResponse> ModifyCacheSubnetGroupAsync(ModifyCacheSubnetGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ModifyReplicationGroup /// <summary> /// Initiates the asynchronous execution of the ModifyReplicationGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyReplicationGroup 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> Task<ModifyReplicationGroupResponse> ModifyReplicationGroupAsync(ModifyReplicationGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PurchaseReservedCacheNodesOffering /// <summary> /// Initiates the asynchronous execution of the PurchaseReservedCacheNodesOffering operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PurchaseReservedCacheNodesOffering 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> Task<PurchaseReservedCacheNodesOfferingResponse> PurchaseReservedCacheNodesOfferingAsync(PurchaseReservedCacheNodesOfferingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RebootCacheCluster /// <summary> /// Initiates the asynchronous execution of the RebootCacheCluster operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RebootCacheCluster 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> Task<RebootCacheClusterResponse> RebootCacheClusterAsync(RebootCacheClusterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RemoveTagsFromResource /// <summary> /// Initiates the asynchronous execution of the RemoveTagsFromResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RemoveTagsFromResource 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> Task<RemoveTagsFromResourceResponse> RemoveTagsFromResourceAsync(RemoveTagsFromResourceRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ResetCacheParameterGroup /// <summary> /// Initiates the asynchronous execution of the ResetCacheParameterGroup operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ResetCacheParameterGroup 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> Task<ResetCacheParameterGroupResponse> ResetCacheParameterGroupAsync(ResetCacheParameterGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RevokeCacheSecurityGroupIngress /// <summary> /// Initiates the asynchronous execution of the RevokeCacheSecurityGroupIngress operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RevokeCacheSecurityGroupIngress 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> Task<RevokeCacheSecurityGroupIngressResponse> RevokeCacheSecurityGroupIngressAsync(RevokeCacheSecurityGroupIngressRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Management.Automation; using Microsoft.Management.Infrastructure; using Microsoft.Management.Infrastructure.Options; using Microsoft.PowerShell.Cim; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Cmdletization.Cim { /// <summary> /// Job wrapping invocation of an extrinsic CIM method. /// </summary> internal abstract class MethodInvocationJobBase<T> : CimChildJobBase<T> { internal MethodInvocationJobBase(CimJobContext jobContext, bool passThru, string methodSubject, MethodInvocationInfo methodInvocationInfo) : base(jobContext) { Dbg.Assert(methodInvocationInfo != null, "Caller should verify methodInvocationInfo != null"); Dbg.Assert(methodSubject != null, "Caller should verify methodSubject != null"); _passThru = passThru; MethodSubject = methodSubject; _methodInvocationInfo = methodInvocationInfo; } private readonly bool _passThru; private readonly MethodInvocationInfo _methodInvocationInfo; internal string MethodName { get { return _methodInvocationInfo.MethodName; } } private const string CustomOperationOptionPrefix = "cim:operationOption:"; private IEnumerable<MethodParameter> GetMethodInputParametersCore(Func<MethodParameter, bool> filter) { IEnumerable<MethodParameter> inputParameters = _methodInvocationInfo.Parameters.Where(filter); var result = new List<MethodParameter>(); foreach (MethodParameter inputParameter in inputParameters) { object cimValue = CimSensitiveValueConverter.ConvertFromDotNetToCim(inputParameter.Value); Type cimType = CimSensitiveValueConverter.GetCimType(inputParameter.ParameterType); CimValueConverter.AssertIntrinsicCimType(cimType); result.Add(new MethodParameter { Name = inputParameter.Name, ParameterType = cimType, Bindings = inputParameter.Bindings, Value = cimValue, IsValuePresent = inputParameter.IsValuePresent }); } return result; } internal IEnumerable<MethodParameter> GetMethodInputParameters() { var allMethodParameters = this.GetMethodInputParametersCore(static p => !p.Name.StartsWith(CustomOperationOptionPrefix, StringComparison.OrdinalIgnoreCase)); var methodParametersWithInputValue = allMethodParameters.Where(static p => p.IsValuePresent); return methodParametersWithInputValue; } internal IEnumerable<CimInstance> GetCimInstancesFromArguments() { return _methodInvocationInfo.GetArgumentsOfType<CimInstance>(); } internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() { IDictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); IEnumerable<MethodParameter> customOptions = this .GetMethodInputParametersCore(static p => p.Name.StartsWith(CustomOperationOptionPrefix, StringComparison.OrdinalIgnoreCase)); foreach (MethodParameter customOption in customOptions) { if (customOption.Value == null) { continue; } result.Add(customOption.Name.Substring(CustomOperationOptionPrefix.Length), customOption.Value); } return CimCustomOptionsDictionary.Create(result); } internal IEnumerable<MethodParameter> GetMethodOutputParameters() { IEnumerable<MethodParameter> allParameters_plus_returnValue = _methodInvocationInfo.Parameters; if (_methodInvocationInfo.ReturnValue != null) { allParameters_plus_returnValue = allParameters_plus_returnValue.Append(_methodInvocationInfo.ReturnValue); } var outParameters = allParameters_plus_returnValue .Where(static p => ((p.Bindings & (MethodParameterBindings.Out | MethodParameterBindings.Error)) != 0)); return outParameters; } internal string MethodSubject { get; } internal bool ShouldProcess() { Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); if (!this.JobContext.CmdletInvocationContext.CmdletDefinitionContext.ClientSideShouldProcess) { return true; } bool shouldProcess; if (!this.JobContext.SupportsShouldProcess) { shouldProcess = true; this.WriteVerboseStartOfCimOperation(); } else { string target = this.MethodSubject; string action = this.MethodName; CimResponseType cimResponseType = this.ShouldProcess(target, action); switch (cimResponseType) { case CimResponseType.Yes: case CimResponseType.YesToAll: shouldProcess = true; break; default: shouldProcess = false; break; } } if (!shouldProcess) { this.SetCompletedJobState(JobState.Completed, null); } return shouldProcess; } #region PassThru functionality internal abstract object PassThruObject { get; } internal bool IsPassThruObjectNeeded() { return (_passThru) && (!this.DidUserSuppressTheOperation) && (!this.JobHadErrors); } public override void OnCompleted() { this.ExceptionSafeWrapper( delegate { Dbg.Assert(this.MethodSubject != null, "MethodSubject property should be initialized before starting main job processing"); if (this.IsPassThruObjectNeeded()) { object passThruObject = this.PassThruObject; if (passThruObject != null) { this.WriteObject(passThruObject); } } }); base.OnCompleted(); } #endregion #region Job descriptions internal override string Description { get { return string.Format( CultureInfo.InvariantCulture, CmdletizationResources.CimJob_MethodDescription, this.MethodSubject, this.MethodName); } } internal override string FailSafeDescription { get { return string.Format( CultureInfo.InvariantCulture, CmdletizationResources.CimJob_SafeMethodDescription, this.JobContext.CmdletizationClassName, this.JobContext.Session.ComputerName, this.MethodName); } } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.SS.UserModel { using System; using NUnit.Framework; using TestCases.SS; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.HSSF.Util; using NPOI.HSSF.UserModel; using System.Text; using NPOI.SS; /** * Common superclass for testing implementatiosn of * {@link NPOI.SS.usermodel.Cell} */ public class BaseTestCell { protected ITestDataProvider _testDataProvider; public BaseTestCell() : this(TestCases.HSSF.HSSFITestDataProvider.Instance) { } /** * @param testDataProvider an object that provides test data in HSSF / XSSF specific way */ protected BaseTestCell(ITestDataProvider testDataProvider) { // One or more test methods depends on the american culture. System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); _testDataProvider = testDataProvider; } [Test] public void TestSetValues() { IWorkbook book = _testDataProvider.CreateWorkbook(); ISheet sheet = book.CreateSheet("test"); IRow row = sheet.CreateRow(0); ICreationHelper factory = book.GetCreationHelper(); ICell cell = row.CreateCell(0); cell.SetCellValue(1.2); Assert.AreEqual(1.2, cell.NumericCellValue, 0.0001); Assert.AreEqual(CellType.Numeric, cell.CellType); AssertProhibitedValueAccess(cell, CellType.Boolean, CellType.String, CellType.Formula, CellType.Error); cell.SetCellValue(false); Assert.AreEqual(false, cell.BooleanCellValue); Assert.AreEqual(CellType.Boolean, cell.CellType); cell.SetCellValue(true); Assert.AreEqual(true, cell.BooleanCellValue); AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.String, CellType.Formula, CellType.Error); cell.SetCellValue(factory.CreateRichTextString("Foo")); Assert.AreEqual("Foo", cell.RichStringCellValue.String); Assert.AreEqual("Foo", cell.StringCellValue); Assert.AreEqual(CellType.String, cell.CellType); AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.Boolean, CellType.Formula, CellType.Error); cell.SetCellValue("345"); Assert.AreEqual("345", cell.RichStringCellValue.String); Assert.AreEqual("345", cell.StringCellValue); Assert.AreEqual(CellType.String, cell.CellType); AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.Boolean, CellType.Formula, CellType.Error); DateTime dt = DateTime.Now.AddMilliseconds(123456789); cell.SetCellValue(dt); Assert.IsTrue((dt.Ticks - cell.DateCellValue.Ticks) >= -20000); Assert.AreEqual(CellType.Numeric, cell.CellType); AssertProhibitedValueAccess(cell, CellType.Boolean, CellType.String, CellType.Formula, CellType.Error); cell.SetCellValue(dt); Assert.IsTrue((dt.Ticks - cell.DateCellValue.Ticks) >= -20000); Assert.AreEqual(CellType.Numeric, cell.CellType); AssertProhibitedValueAccess(cell, CellType.Boolean, CellType.String, CellType.Formula, CellType.Error); cell.SetCellErrorValue(FormulaError.NA.Code); Assert.AreEqual(FormulaError.NA.Code, cell.ErrorCellValue); Assert.AreEqual(CellType.Error, cell.CellType); AssertProhibitedValueAccess(cell, CellType.Numeric, CellType.Boolean, CellType.Formula, CellType.String); } private static void AssertProhibitedValueAccess(ICell cell, params CellType[] types) { object a; foreach (CellType type in types) { try { switch (type) { case CellType.Numeric: a = cell.NumericCellValue; break; case CellType.String: a = cell.StringCellValue; break; case CellType.Boolean: a = cell.BooleanCellValue; break; case CellType.Formula: a = cell.CellFormula; break; case CellType.Error: a = cell.ErrorCellValue; break; } Assert.Fail("Should get exception when Reading cell type (" + type + ")."); } catch (InvalidOperationException e) { // expected during successful test Assert.IsTrue(e.Message.StartsWith("Cannot get a")); } } } /** * test that Boolean and Error types (BoolErrRecord) are supported properly. */ [Test] public void TestBoolErr() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet s = wb.CreateSheet("testSheet1"); IRow r; ICell c; r = s.CreateRow(0); c = r.CreateCell(1); //c.SetCellType(HSSFCellType.Boolean); c.SetCellValue(true); c = r.CreateCell(2); //c.SetCellType(HSSFCellType.Boolean); c.SetCellValue(false); r = s.CreateRow(1); c = r.CreateCell(1); //c.SetCellType(HSSFCellType.Error); c.SetCellErrorValue((byte)0); c = r.CreateCell(2); //c.SetCellType(HSSFCellType.Error); c.SetCellErrorValue((byte)7); wb = _testDataProvider.WriteOutAndReadBack(wb); s = wb.GetSheetAt(0); r = s.GetRow(0); c = r.GetCell(1); Assert.IsTrue(c.BooleanCellValue, "bool value 0,1 = true"); c = r.GetCell(2); Assert.IsTrue(c.BooleanCellValue == false, "bool value 0,2 = false"); r = s.GetRow(1); c = r.GetCell(1); Assert.IsTrue(c.ErrorCellValue == 0, "bool value 0,1 = 0"); c = r.GetCell(2); Assert.IsTrue(c.ErrorCellValue == 7, "bool value 0,2 = 7"); } /** * test that Cell Styles being applied to formulas remain intact */ [Test] public void TestFormulaStyle() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet s = wb.CreateSheet("testSheet1"); IRow r = null; ICell c = null; ICellStyle cs = wb.CreateCellStyle(); IFont f = wb.CreateFont(); f.FontHeightInPoints = 20; f.Color = (HSSFColor.Red.Index); f.Boldweight = (int)FontBoldWeight.Bold; f.FontName = "Arial Unicode MS"; cs.FillBackgroundColor = 3; cs.SetFont(f); cs.BorderTop = BorderStyle.Thin; cs.BorderRight = BorderStyle.Thin; cs.BorderLeft = BorderStyle.Thin; cs.BorderBottom = BorderStyle.Thin; r = s.CreateRow(0); c = r.CreateCell(0); c.CellStyle = cs; c.CellFormula = ("2*3"); wb = _testDataProvider.WriteOutAndReadBack(wb); s = wb.GetSheetAt(0); r = s.GetRow(0); c = r.GetCell(0); Assert.IsTrue((c.CellType == CellType.Formula), "Formula Cell at 0,0"); cs = c.CellStyle; Assert.IsNotNull(cs, "Formula Cell Style"); Assert.AreEqual(f.Index, cs.FontIndex, "Font Index Matches"); Assert.AreEqual(BorderStyle.Thin, cs.BorderTop , "Top Border"); Assert.AreEqual(BorderStyle.Thin, cs.BorderLeft, "Left Border"); Assert.AreEqual(BorderStyle.Thin, cs.BorderRight, "Right Border"); Assert.AreEqual(BorderStyle.Thin, cs.BorderBottom, "Bottom Border"); } /**tests the ToString() method of HSSFCell*/ [Test] public void TestToString() { IWorkbook wb = _testDataProvider.CreateWorkbook(); IRow r = wb.CreateSheet("Sheet1").CreateRow(0); ICreationHelper factory = wb.GetCreationHelper(); r.CreateCell(0).SetCellValue(true); r.CreateCell(1).SetCellValue(1.5); r.CreateCell(2).SetCellValue(factory.CreateRichTextString("Astring")); r.CreateCell(3).SetCellErrorValue((byte)ErrorConstants.ERROR_DIV_0); r.CreateCell(4).CellFormula = ("A1+B1"); Assert.AreEqual("TRUE", r.GetCell(0).ToString(), "Boolean"); Assert.AreEqual("1.5", r.GetCell(1).ToString(), "Numeric"); Assert.AreEqual("Astring", r.GetCell(2).ToString(), "String"); Assert.AreEqual("#DIV/0!", r.GetCell(3).ToString(), "Error"); Assert.AreEqual("A1+B1", r.GetCell(4).ToString(), "Formula"); //Write out the file, read it in, and then check cell values wb = _testDataProvider.WriteOutAndReadBack(wb); r = wb.GetSheetAt(0).GetRow(0); Assert.AreEqual("TRUE", r.GetCell(0).ToString(), "Boolean"); Assert.AreEqual("1.5", r.GetCell(1).ToString(), "Numeric"); Assert.AreEqual("Astring", r.GetCell(2).ToString(), "String"); Assert.AreEqual("#DIV/0!", r.GetCell(3).ToString(), "Error"); Assert.AreEqual("A1+B1", r.GetCell(4).ToString(), "Formula"); } /** * Test that Setting cached formula result keeps the cell type */ [Test] public void TestSetFormulaValue() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet s = wb.CreateSheet(); IRow r = s.CreateRow(0); ICell c1 = r.CreateCell(0); c1.CellFormula = ("NA()"); Assert.AreEqual(0.0, c1.NumericCellValue, 0.0); Assert.AreEqual(CellType.Numeric, c1.CachedFormulaResultType); c1.SetCellValue(10); Assert.AreEqual(10.0, c1.NumericCellValue, 0.0); Assert.AreEqual(CellType.Formula, c1.CellType); Assert.AreEqual(CellType.Numeric, c1.CachedFormulaResultType); ICell c2 = r.CreateCell(1); c2.CellFormula = ("NA()"); Assert.AreEqual(0.0, c2.NumericCellValue, 0.0); Assert.AreEqual(CellType.Numeric, c2.CachedFormulaResultType); c2.SetCellValue("I Changed!"); Assert.AreEqual("I Changed!", c2.StringCellValue); Assert.AreEqual(CellType.Formula, c2.CellType); Assert.AreEqual(CellType.String, c2.CachedFormulaResultType); //calglin Cell.CellFormula = (null) for a non-formula cell ICell c3 = r.CreateCell(2); c3.CellFormula = (null); Assert.AreEqual(CellType.Blank, c3.CellType); } private ICell CreateACell() { return _testDataProvider.CreateWorkbook().CreateSheet("Sheet1").CreateRow(0).CreateCell(0); } [Test] public void TestChangeTypeStringToBool() { ICell cell = CreateACell(); cell.SetCellValue("TRUE"); Assert.AreEqual(CellType.String, cell.CellType); try { cell.SetCellType(CellType.Boolean); } catch (InvalidCastException) { throw new AssertionException( "Identified bug in conversion of cell from text to bool"); } Assert.AreEqual(CellType.Boolean, cell.CellType); Assert.AreEqual(true, cell.BooleanCellValue); cell.SetCellType(CellType.String); Assert.AreEqual("TRUE", cell.RichStringCellValue.String); // 'false' text to bool and back cell.SetCellValue("FALSE"); cell.SetCellType(CellType.Boolean); Assert.AreEqual(CellType.Boolean, cell.CellType); Assert.AreEqual(false, cell.BooleanCellValue); cell.SetCellType(CellType.String); Assert.AreEqual("FALSE", cell.RichStringCellValue.String); } [Test] public void TestChangeTypeBoolToString() { ICell cell = CreateACell(); cell.SetCellValue(true); try { cell.SetCellType(CellType.String); } catch (InvalidOperationException e) { if (e.Message.Equals("Cannot get a text value from a bool cell")) { throw new AssertionException( "Identified bug in conversion of cell from bool to text"); } throw e; } Assert.AreEqual("TRUE", cell.RichStringCellValue.String); } [Test] public void TestChangeTypeErrorToNumber() { ICell cell = CreateACell(); cell.SetCellErrorValue((byte)ErrorConstants.ERROR_NAME); try { cell.SetCellValue(2.5); } catch (InvalidCastException) { throw new AssertionException("Identified bug 46479b"); } Assert.AreEqual(2.5, cell.NumericCellValue, 0.0); } [Test] public void TestChangeTypeErrorToBoolean() { ICell cell = CreateACell(); cell.SetCellErrorValue((byte)ErrorConstants.ERROR_NAME); cell.SetCellValue(true); try { object a = cell.BooleanCellValue; } catch (InvalidOperationException e) { if (e.Message.Equals("Cannot get a bool value from a error cell")) { throw new AssertionException("Identified bug 46479c"); } throw e; } Assert.AreEqual(true, cell.BooleanCellValue); } /** * Test for a bug observed around svn r886733 when using * {@link FormulaEvaluator#EvaluateInCell(Cell)} with a * string result type. */ [Test] public void TestConvertStringFormulaCell() { ICell cellA1 = CreateACell(); cellA1.CellFormula = ("\"abc\""); // default cached formula result is numeric zero Assert.AreEqual(0.0, cellA1.NumericCellValue, 0.0); IFormulaEvaluator fe = cellA1.Sheet.Workbook.GetCreationHelper().CreateFormulaEvaluator(); fe.EvaluateFormulaCell(cellA1); Assert.AreEqual("abc", cellA1.StringCellValue); fe.EvaluateInCell(cellA1); if (cellA1.StringCellValue.Equals("")) { throw new AssertionException("Identified bug with writing back formula result of type string"); } Assert.AreEqual("abc", cellA1.StringCellValue); } /** * similar to {@link #testConvertStringFormulaCell()} but Checks at a * lower level that {#link {@link Cell#SetCellType(int)} works properly */ [Test] public void TestSetTypeStringOnFormulaCell() { ICell cellA1 = CreateACell(); IFormulaEvaluator fe = cellA1.Sheet.Workbook.GetCreationHelper().CreateFormulaEvaluator(); cellA1.CellFormula = ("\"DEF\""); fe.ClearAllCachedResultValues(); fe.EvaluateFormulaCell(cellA1); Assert.AreEqual("DEF", cellA1.StringCellValue); cellA1.SetCellType(CellType.String); Assert.AreEqual("DEF", cellA1.StringCellValue); cellA1.CellFormula = ("25.061"); fe.ClearAllCachedResultValues(); fe.EvaluateFormulaCell(cellA1); ConfirmCannotReadString(cellA1); Assert.AreEqual(25.061, cellA1.NumericCellValue, 0.0); cellA1.SetCellType(CellType.String); Assert.AreEqual("25.061", cellA1.StringCellValue); cellA1.CellFormula = ("TRUE"); fe.ClearAllCachedResultValues(); fe.EvaluateFormulaCell(cellA1); ConfirmCannotReadString(cellA1); Assert.AreEqual(true, cellA1.BooleanCellValue); cellA1.SetCellType(CellType.String); Assert.AreEqual("TRUE", cellA1.StringCellValue); cellA1.CellFormula = ("#NAME?"); fe.ClearAllCachedResultValues(); fe.EvaluateFormulaCell(cellA1); ConfirmCannotReadString(cellA1); Assert.AreEqual(ErrorConstants.ERROR_NAME, cellA1.ErrorCellValue); cellA1.SetCellType(CellType.String); Assert.AreEqual("#NAME?", cellA1.StringCellValue); } private static void ConfirmCannotReadString(ICell cell) { AssertProhibitedValueAccess(cell, CellType.String); } /** * Test for bug in ConvertCellValueToBoolean to make sure that formula results get Converted */ [Test] public void TestChangeTypeFormulaToBoolean() { ICell cell = CreateACell(); cell.CellFormula = ("1=1"); cell.SetCellValue(true); cell.SetCellType(CellType.Boolean); if (cell.BooleanCellValue == false) { throw new AssertionException("Identified bug 46479d"); } Assert.AreEqual(true, cell.BooleanCellValue); } /** * Bug 40296: HSSFCell.CellFormula = throws * InvalidCastException if cell is Created using HSSFRow.CreateCell(short column, int type) */ [Test] public void Test40296() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet workSheet = wb.CreateSheet("Sheet1"); ICell cell; IRow row = workSheet.CreateRow(0); cell = row.CreateCell(0, CellType.Numeric); cell.SetCellValue(1.0); Assert.AreEqual(CellType.Numeric, cell.CellType); Assert.AreEqual(1.0, cell.NumericCellValue, 0.0); cell = row.CreateCell(1, CellType.Numeric); cell.SetCellValue(2.0); Assert.AreEqual(CellType.Numeric, cell.CellType); Assert.AreEqual(2.0, cell.NumericCellValue, 0.0); cell = row.CreateCell(2, CellType.Formula); cell.CellFormula = ("SUM(A1:B1)"); Assert.AreEqual(CellType.Formula, cell.CellType); Assert.AreEqual("SUM(A1:B1)", cell.CellFormula); //serialize and check again wb = _testDataProvider.WriteOutAndReadBack(wb); row = wb.GetSheetAt(0).GetRow(0); cell = row.GetCell(0); Assert.AreEqual(CellType.Numeric, cell.CellType); Assert.AreEqual(1.0, cell.NumericCellValue, 0.0); cell = row.GetCell(1); Assert.AreEqual(CellType.Numeric, cell.CellType); Assert.AreEqual(2.0, cell.NumericCellValue, 0.0); cell = row.GetCell(2); Assert.AreEqual(CellType.Formula, cell.CellType); Assert.AreEqual("SUM(A1:B1)", cell.CellFormula); } [Test] public void TestSetStringInFormulaCell_bug44606() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ICell cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0); cell.CellFormula = ("B1&C1"); try { cell.SetCellValue(wb.GetCreationHelper().CreateRichTextString("hello")); } catch (InvalidCastException) { throw new AssertionException("Identified bug 44606"); } } /** * Make sure that cell.SetCellType(Cell.CELL_TYPE_BLANK) preserves the cell style */ [Test] public void TestSetBlank_bug47028() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ICellStyle style = wb.CreateCellStyle(); ICell cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0); cell.CellStyle = (style); int i1 = cell.CellStyle.Index; cell.SetCellType(CellType.Blank); int i2 = cell.CellStyle.Index; Assert.AreEqual(i1, i2); } /** * Excel's implementation of floating number arithmetic does not fully adhere to IEEE 754: * * From http://support.microsoft.com/kb/78113: * * <ul> * <li> Positive/Negative InfInities: * InfInities occur when you divide by 0. Excel does not support infInities, rather, * it gives a #DIV/0! error in these cases. * </li> * <li> * Not-a-Number (NaN): * NaN is used to represent invalid operations (such as infInity/infinity, * infInity-infinity, or the square root of -1). NaNs allow a program to * continue past an invalid operation. Excel instead immediately generates * an error such as #NUM! or #DIV/0!. * </li> * </ul> */ [Test] public void TestNanAndInfInity() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet workSheet = wb.CreateSheet("Sheet1"); IRow row = workSheet.CreateRow(0); ICell cell0 = row.CreateCell(0); cell0.SetCellValue(Double.NaN); Assert.AreEqual(CellType.Error, cell0.CellType, "Double.NaN should change cell type to CELL_TYPE_ERROR"); Assert.AreEqual(ErrorConstants.ERROR_NUM, cell0.ErrorCellValue, "Double.NaN should change cell value to #NUM!"); ICell cell1 = row.CreateCell(1); cell1.SetCellValue(Double.PositiveInfinity); Assert.AreEqual(CellType.Error, cell1.CellType, "Double.PositiveInfinity should change cell type to CELL_TYPE_ERROR"); Assert.AreEqual(ErrorConstants.ERROR_DIV_0, cell1.ErrorCellValue, "Double.POSITIVE_INFINITY should change cell value to #DIV/0!"); ICell cell2 = row.CreateCell(2); cell2.SetCellValue(Double.NegativeInfinity); Assert.AreEqual(CellType.Error, cell2.CellType, "Double.NegativeInfinity should change cell type to CELL_TYPE_ERROR"); Assert.AreEqual(ErrorConstants.ERROR_DIV_0, cell2.ErrorCellValue, "Double.NEGATIVE_INFINITY should change cell value to #DIV/0!"); wb = _testDataProvider.WriteOutAndReadBack(wb); row = wb.GetSheetAt(0).GetRow(0); cell0 = row.GetCell(0); Assert.AreEqual(CellType.Error, cell0.CellType); Assert.AreEqual(ErrorConstants.ERROR_NUM, cell0.ErrorCellValue); cell1 = row.GetCell(1); Assert.AreEqual(CellType.Error, cell1.CellType); Assert.AreEqual(ErrorConstants.ERROR_DIV_0, cell1.ErrorCellValue); cell2 = row.GetCell(2); Assert.AreEqual(CellType.Error, cell2.CellType); Assert.AreEqual(ErrorConstants.ERROR_DIV_0, cell2.ErrorCellValue); } [Test] public void TestDefaultStyleProperties() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ICell cell = wb.CreateSheet("Sheet1").CreateRow(0).CreateCell(0); ICellStyle style = cell.CellStyle; Assert.IsTrue(style.IsLocked); Assert.IsFalse(style.IsHidden); Assert.AreEqual(0, style.Indention); Assert.AreEqual(0, style.FontIndex); Assert.AreEqual(0, (int)style.Alignment); Assert.AreEqual(0, style.DataFormat); Assert.AreEqual(false, style.WrapText); ICellStyle style2 = wb.CreateCellStyle(); Assert.IsTrue(style2.IsLocked); Assert.IsFalse(style2.IsHidden); style2.IsLocked = (/*setter*/false); style2.IsHidden = (/*setter*/true); Assert.IsFalse(style2.IsLocked); Assert.IsTrue(style2.IsHidden); wb = _testDataProvider.WriteOutAndReadBack(wb); cell = wb.GetSheetAt(0).GetRow(0).GetCell(0); style = cell.CellStyle; Assert.IsFalse(style2.IsLocked); Assert.IsTrue(style2.IsHidden); style2.IsLocked = (/*setter*/true); style2.IsHidden = (/*setter*/false); Assert.IsTrue(style2.IsLocked); Assert.IsFalse(style2.IsHidden); } [Test] public void TestBug55658SetNumericValue() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); IRow row = sh.CreateRow(0); ICell cell = row.CreateCell(0); cell.SetCellValue(23); cell.SetCellValue("some"); cell = row.CreateCell(1); cell.SetCellValue(23); cell.SetCellValue("24"); wb = _testDataProvider.WriteOutAndReadBack(wb); Assert.AreEqual("some", wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue); Assert.AreEqual("24", wb.GetSheetAt(0).GetRow(0).GetCell(1).StringCellValue); } [Test] public void TestRemoveHyperlink() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet("test"); IRow row = sh.CreateRow(0); ICreationHelper helper = wb.GetCreationHelper(); ICell cell1 = row.CreateCell(1); IHyperlink link1 = helper.CreateHyperlink(HyperlinkType.Url); cell1.Hyperlink = (/*setter*/link1); Assert.IsNotNull(cell1.Hyperlink); cell1.RemoveHyperlink(); Assert.IsNull(cell1.Hyperlink); ICell cell2 = row.CreateCell(0); IHyperlink link2 = helper.CreateHyperlink(HyperlinkType.Url); cell2.Hyperlink = (/*setter*/link2); Assert.IsNotNull(cell2.Hyperlink); cell2.Hyperlink = (/*setter*/null); Assert.IsNull(cell2.Hyperlink); ICell cell3 = row.CreateCell(2); IHyperlink link3 = helper.CreateHyperlink(HyperlinkType.Url); link3.Address = (/*setter*/"http://poi.apache.org/"); cell3.Hyperlink = (/*setter*/link3); Assert.IsNotNull(cell3.Hyperlink); IWorkbook wbBack = _testDataProvider.WriteOutAndReadBack(wb); Assert.IsNotNull(wbBack); cell1 = wbBack.GetSheet("test").GetRow(0).GetCell(1); Assert.IsNull(cell1.Hyperlink); cell2 = wbBack.GetSheet("test").GetRow(0).GetCell(0); Assert.IsNull(cell2.Hyperlink); cell3 = wbBack.GetSheet("test").GetRow(0).GetCell(2); Assert.IsNotNull(cell3.Hyperlink); } /** * Cell with the formula that returns error must return error code(There was * an problem that cell could not return error value form formula cell). * @ */ [Test] public void TestGetErrorCellValueFromFormulaCell() { IWorkbook wb = _testDataProvider.CreateWorkbook(); try { ISheet sheet = wb.CreateSheet(); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); cell.CellFormula = (/*setter*/"SQRT(-1)"); wb.GetCreationHelper().CreateFormulaEvaluator().EvaluateFormulaCell(cell); Assert.AreEqual(36, cell.ErrorCellValue); } finally { wb.Close(); } } [Test] public void TestSetRemoveStyle() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); // different default style indexes for HSSF and XSSF/SXSSF ICellStyle defaultStyle = wb.GetCellStyleAt(wb is HSSFWorkbook ? (short)15 : (short)0); // Starts out with the default style Assert.AreEqual(defaultStyle, cell.CellStyle); // Create some styles, no change ICellStyle style1 = wb.CreateCellStyle(); ICellStyle style2 = wb.CreateCellStyle(); style1.DataFormat = (/*setter*/(short)2); style2.DataFormat = (/*setter*/(short)3); Assert.AreEqual(defaultStyle, cell.CellStyle); // Apply one, Changes cell.CellStyle = (/*setter*/style1); Assert.AreEqual(style1, cell.CellStyle); // Apply the other, Changes cell.CellStyle = (/*setter*/style2); Assert.AreEqual(style2, cell.CellStyle); // Remove, goes back to default cell.CellStyle = (/*setter*/null); Assert.AreEqual(defaultStyle, cell.CellStyle); // Add back, returns cell.CellStyle = (/*setter*/style2); Assert.AreEqual(style2, cell.CellStyle); wb.Close(); } [Test] public void Test57008() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); IRow row0 = sheet.CreateRow(0); ICell cell0 = row0.CreateCell(0); cell0.SetCellValue("row 0, cell 0 _x0046_ without Changes"); ICell cell1 = row0.CreateCell(1); cell1.SetCellValue("row 0, cell 1 _x005fx0046_ with Changes"); ICell cell2 = row0.CreateCell(2); cell2.SetCellValue("hgh_x0041_**_x0100_*_x0101_*_x0190_*_x0200_*_x0300_*_x0427_*"); CheckUnicodeValues(wb); // String fname = "/tmp/Test_xNNNN_inCell" + (wb is HSSFWorkbook ? ".xls" : ".xlsx"); // FileOutputStream out1 = new FileOutputStream(fname); // try { // wb.Write(out1); // } finally { // out1.Close(); // } IWorkbook wbBack = _testDataProvider.WriteOutAndReadBack(wb); CheckUnicodeValues(wbBack); } protected void CheckUnicodeValues(IWorkbook wb) { Assert.AreEqual((wb is HSSFWorkbook ? "row 0, cell 0 _x0046_ without Changes" : "row 0, cell 0 F without Changes"), wb.GetSheetAt(0).GetRow(0).GetCell(0).ToString()); Assert.AreEqual((wb is HSSFWorkbook ? "row 0, cell 1 _x005fx0046_ with Changes" : "row 0, cell 1 _x005fx0046_ with Changes"), wb.GetSheetAt(0).GetRow(0).GetCell(1).ToString()); Assert.AreEqual((wb is HSSFWorkbook ? "hgh_x0041_**_x0100_*_x0101_*_x0190_*_x0200_*_x0300_*_x0427_*" : "hghA**\u0100*\u0101*\u0190*\u0200*\u0300*\u0427*"), wb.GetSheetAt(0).GetRow(0).GetCell(2).ToString()); } /** * The maximum length of cell contents (text) is 32,767 characters. * @ */ [Test] public void TestMaxTextLength() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); ICell cell = sheet.CreateRow(0).CreateCell(0); int maxlen = wb is HSSFWorkbook ? SpreadsheetVersion.EXCEL97.MaxTextLength : SpreadsheetVersion.EXCEL2007.MaxTextLength; Assert.AreEqual(32767, maxlen); StringBuilder b = new StringBuilder(); // 32767 is okay for (int i = 0; i < maxlen; i++) { b.Append("X"); } cell.SetCellValue(b.ToString()); b.Append("X"); // 32768 produces an invalid XLS file try { cell.SetCellValue(b.ToString()); Assert.Fail("Expected exception"); } catch (ArgumentException e) { Assert.AreEqual("The maximum length of cell contents (text) is 32,767 characters", e.Message); } wb.Close(); } } }
// 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. //Testing simple math on local vars and fields - sub #pragma warning disable 0414 using System; internal class lclfldsub { //user-defined class that overloads operator - public class numHolder { private int _i_num; private uint _ui_num; private long _l_num; private ulong _ul_num; private float _f_num; private double _d_num; private decimal _m_num; public numHolder(int i_num) { _i_num = Convert.ToInt32(i_num); _ui_num = Convert.ToUInt32(i_num); _l_num = Convert.ToInt64(i_num); _ul_num = Convert.ToUInt64(i_num); _f_num = Convert.ToSingle(i_num); _d_num = Convert.ToDouble(i_num); _m_num = Convert.ToDecimal(i_num); } public static int operator -(numHolder a, int b) { return a._i_num - b; } public numHolder(uint ui_num) { _i_num = Convert.ToInt32(ui_num); _ui_num = Convert.ToUInt32(ui_num); _l_num = Convert.ToInt64(ui_num); _ul_num = Convert.ToUInt64(ui_num); _f_num = Convert.ToSingle(ui_num); _d_num = Convert.ToDouble(ui_num); _m_num = Convert.ToDecimal(ui_num); } public static uint operator -(numHolder a, uint b) { return a._ui_num - b; } public numHolder(long l_num) { _i_num = Convert.ToInt32(l_num); _ui_num = Convert.ToUInt32(l_num); _l_num = Convert.ToInt64(l_num); _ul_num = Convert.ToUInt64(l_num); _f_num = Convert.ToSingle(l_num); _d_num = Convert.ToDouble(l_num); _m_num = Convert.ToDecimal(l_num); } public static long operator -(numHolder a, long b) { return a._l_num - b; } public numHolder(ulong ul_num) { _i_num = Convert.ToInt32(ul_num); _ui_num = Convert.ToUInt32(ul_num); _l_num = Convert.ToInt64(ul_num); _ul_num = Convert.ToUInt64(ul_num); _f_num = Convert.ToSingle(ul_num); _d_num = Convert.ToDouble(ul_num); _m_num = Convert.ToDecimal(ul_num); } public static long operator -(numHolder a, ulong b) { return (long)(a._ul_num - b); } public numHolder(float f_num) { _i_num = Convert.ToInt32(f_num); _ui_num = Convert.ToUInt32(f_num); _l_num = Convert.ToInt64(f_num); _ul_num = Convert.ToUInt64(f_num); _f_num = Convert.ToSingle(f_num); _d_num = Convert.ToDouble(f_num); _m_num = Convert.ToDecimal(f_num); } public static float operator -(numHolder a, float b) { return a._f_num - b; } public numHolder(double d_num) { _i_num = Convert.ToInt32(d_num); _ui_num = Convert.ToUInt32(d_num); _l_num = Convert.ToInt64(d_num); _ul_num = Convert.ToUInt64(d_num); _f_num = Convert.ToSingle(d_num); _d_num = Convert.ToDouble(d_num); _m_num = Convert.ToDecimal(d_num); } public static double operator -(numHolder a, double b) { return a._d_num - b; } public numHolder(decimal m_num) { _i_num = Convert.ToInt32(m_num); _ui_num = Convert.ToUInt32(m_num); _l_num = Convert.ToInt64(m_num); _ul_num = Convert.ToUInt64(m_num); _f_num = Convert.ToSingle(m_num); _d_num = Convert.ToDouble(m_num); _m_num = Convert.ToDecimal(m_num); } public static int operator -(numHolder a, decimal b) { return (int)(a._m_num - b); } public static int operator -(numHolder a, numHolder b) { return a._i_num - b._i_num; } } private static int s_i_s_op1 = 16; private static uint s_ui_s_op1 = 16; private static long s_l_s_op1 = 16; private static ulong s_ul_s_op1 = 16; private static float s_f_s_op1 = 16; private static double s_d_s_op1 = 16; private static decimal s_m_s_op1 = 16; private static int s_i_s_op2 = 15; private static uint s_ui_s_op2 = 15; private static long s_l_s_op2 = 15; private static ulong s_ul_s_op2 = 15; private static float s_f_s_op2 = 15; private static double s_d_s_op2 = 15; private static decimal s_m_s_op2 = 15; private static numHolder s_nHldr_s_op2 = new numHolder(15); public static int i_f(String s) { if (s == "op1") return 16; else return 15; } public static uint ui_f(String s) { if (s == "op1") return 16; else return 15; } public static long l_f(String s) { if (s == "op1") return 16; else return 15; } public static ulong ul_f(String s) { if (s == "op1") return 16; else return 15; } public static float f_f(String s) { if (s == "op1") return 16; else return 15; } public static double d_f(String s) { if (s == "op1") return 16; else return 15; } public static decimal m_f(String s) { if (s == "op1") return 16; else return 15; } public static numHolder nHldr_f(String s) { if (s == "op1") return new numHolder(16); else return new numHolder(15); } private class CL { public int i_cl_op1 = 16; public uint ui_cl_op1 = 16; public long l_cl_op1 = 16; public ulong ul_cl_op1 = 16; public float f_cl_op1 = 16; public double d_cl_op1 = 16; public decimal m_cl_op1 = 16; public int i_cl_op2 = 15; public uint ui_cl_op2 = 15; public long l_cl_op2 = 15; public ulong ul_cl_op2 = 15; public float f_cl_op2 = 15; public double d_cl_op2 = 15; public decimal m_cl_op2 = 15; public numHolder nHldr_cl_op2 = new numHolder(15); } private struct VT { public int i_vt_op1; public uint ui_vt_op1; public long l_vt_op1; public ulong ul_vt_op1; public float f_vt_op1; public double d_vt_op1; public decimal m_vt_op1; public int i_vt_op2; public uint ui_vt_op2; public long l_vt_op2; public ulong ul_vt_op2; public float f_vt_op2; public double d_vt_op2; public decimal m_vt_op2; public numHolder nHldr_vt_op2; } public static int Main() { bool passed = true; //initialize class CL cl1 = new CL(); //initialize struct VT vt1; vt1.i_vt_op1 = 16; vt1.ui_vt_op1 = 16; vt1.l_vt_op1 = 16; vt1.ul_vt_op1 = 16; vt1.f_vt_op1 = 16; vt1.d_vt_op1 = 16; vt1.m_vt_op1 = 16; vt1.i_vt_op2 = 15; vt1.ui_vt_op2 = 15; vt1.l_vt_op2 = 15; vt1.ul_vt_op2 = 15; vt1.f_vt_op2 = 15; vt1.d_vt_op2 = 15; vt1.m_vt_op2 = 15; vt1.nHldr_vt_op2 = new numHolder(15); int[] i_arr1d_op1 = { 0, 16 }; int[,] i_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; int[,,] i_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; uint[] ui_arr1d_op1 = { 0, 16 }; uint[,] ui_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; uint[,,] ui_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; long[] l_arr1d_op1 = { 0, 16 }; long[,] l_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; long[,,] l_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; ulong[] ul_arr1d_op1 = { 0, 16 }; ulong[,] ul_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; ulong[,,] ul_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; float[] f_arr1d_op1 = { 0, 16 }; float[,] f_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; float[,,] f_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; double[] d_arr1d_op1 = { 0, 16 }; double[,] d_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; double[,,] d_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; decimal[] m_arr1d_op1 = { 0, 16 }; decimal[,] m_arr2d_op1 = { { 0, 16 }, { 1, 1 } }; decimal[,,] m_arr3d_op1 = { { { 0, 16 }, { 1, 1 } } }; int[] i_arr1d_op2 = { 15, 0, 1 }; int[,] i_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; int[,,] i_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; uint[] ui_arr1d_op2 = { 15, 0, 1 }; uint[,] ui_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; uint[,,] ui_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; long[] l_arr1d_op2 = { 15, 0, 1 }; long[,] l_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; long[,,] l_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; ulong[] ul_arr1d_op2 = { 15, 0, 1 }; ulong[,] ul_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; ulong[,,] ul_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; float[] f_arr1d_op2 = { 15, 0, 1 }; float[,] f_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; float[,,] f_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; double[] d_arr1d_op2 = { 15, 0, 1 }; double[,] d_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; double[,,] d_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; decimal[] m_arr1d_op2 = { 15, 0, 1 }; decimal[,] m_arr2d_op2 = { { 0, 15 }, { 1, 1 } }; decimal[,,] m_arr3d_op2 = { { { 0, 15 }, { 1, 1 } } }; numHolder[] nHldr_arr1d_op2 = { new numHolder(15), new numHolder(0), new numHolder(1) }; numHolder[,] nHldr_arr2d_op2 = { { new numHolder(0), new numHolder(15) }, { new numHolder(1), new numHolder(1) } }; numHolder[,,] nHldr_arr3d_op2 = { { { new numHolder(0), new numHolder(15) }, { new numHolder(1), new numHolder(1) } } }; int[,] index = { { 0, 0 }, { 1, 1 } }; { int i_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((i_l_op1 - i_l_op2 != i_l_op1 - ui_l_op2) || (i_l_op1 - ui_l_op2 != i_l_op1 - l_l_op2) || (i_l_op1 - l_l_op2 != i_l_op1 - (int)ul_l_op2) || (i_l_op1 - (int)ul_l_op2 != i_l_op1 - f_l_op2) || (i_l_op1 - f_l_op2 != i_l_op1 - d_l_op2) || ((decimal)(i_l_op1 - d_l_op2) != i_l_op1 - m_l_op2) || (i_l_op1 - m_l_op2 != i_l_op1 - i_l_op2) || (i_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 1 failed"); passed = false; } if ((i_l_op1 - s_i_s_op2 != i_l_op1 - s_ui_s_op2) || (i_l_op1 - s_ui_s_op2 != i_l_op1 - s_l_s_op2) || (i_l_op1 - s_l_s_op2 != i_l_op1 - (int)s_ul_s_op2) || (i_l_op1 - (int)s_ul_s_op2 != i_l_op1 - s_f_s_op2) || (i_l_op1 - s_f_s_op2 != i_l_op1 - s_d_s_op2) || ((decimal)(i_l_op1 - s_d_s_op2) != i_l_op1 - s_m_s_op2) || (i_l_op1 - s_m_s_op2 != i_l_op1 - s_i_s_op2) || (i_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 2 failed"); passed = false; } if ((s_i_s_op1 - i_l_op2 != s_i_s_op1 - ui_l_op2) || (s_i_s_op1 - ui_l_op2 != s_i_s_op1 - l_l_op2) || (s_i_s_op1 - l_l_op2 != s_i_s_op1 - (int)ul_l_op2) || (s_i_s_op1 - (int)ul_l_op2 != s_i_s_op1 - f_l_op2) || (s_i_s_op1 - f_l_op2 != s_i_s_op1 - d_l_op2) || ((decimal)(s_i_s_op1 - d_l_op2) != s_i_s_op1 - m_l_op2) || (s_i_s_op1 - m_l_op2 != s_i_s_op1 - i_l_op2) || (s_i_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 3 failed"); passed = false; } if ((s_i_s_op1 - s_i_s_op2 != s_i_s_op1 - s_ui_s_op2) || (s_i_s_op1 - s_ui_s_op2 != s_i_s_op1 - s_l_s_op2) || (s_i_s_op1 - s_l_s_op2 != s_i_s_op1 - (int)s_ul_s_op2) || (s_i_s_op1 - (int)s_ul_s_op2 != s_i_s_op1 - s_f_s_op2) || (s_i_s_op1 - s_f_s_op2 != s_i_s_op1 - s_d_s_op2) || ((decimal)(s_i_s_op1 - s_d_s_op2) != s_i_s_op1 - s_m_s_op2) || (s_i_s_op1 - s_m_s_op2 != s_i_s_op1 - s_i_s_op2) || (s_i_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 4 failed"); passed = false; } } { uint ui_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((ui_l_op1 - i_l_op2 != ui_l_op1 - ui_l_op2) || (ui_l_op1 - ui_l_op2 != ui_l_op1 - l_l_op2) || ((ulong)(ui_l_op1 - l_l_op2) != ui_l_op1 - ul_l_op2) || (ui_l_op1 - ul_l_op2 != ui_l_op1 - f_l_op2) || (ui_l_op1 - f_l_op2 != ui_l_op1 - d_l_op2) || ((decimal)(ui_l_op1 - d_l_op2) != ui_l_op1 - m_l_op2) || (ui_l_op1 - m_l_op2 != ui_l_op1 - i_l_op2) || (ui_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 5 failed"); passed = false; } if ((ui_l_op1 - s_i_s_op2 != ui_l_op1 - s_ui_s_op2) || (ui_l_op1 - s_ui_s_op2 != ui_l_op1 - s_l_s_op2) || ((ulong)(ui_l_op1 - s_l_s_op2) != ui_l_op1 - s_ul_s_op2) || (ui_l_op1 - s_ul_s_op2 != ui_l_op1 - s_f_s_op2) || (ui_l_op1 - s_f_s_op2 != ui_l_op1 - s_d_s_op2) || ((decimal)(ui_l_op1 - s_d_s_op2) != ui_l_op1 - s_m_s_op2) || (ui_l_op1 - s_m_s_op2 != ui_l_op1 - s_i_s_op2) || (ui_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 6 failed"); passed = false; } if ((s_ui_s_op1 - i_l_op2 != s_ui_s_op1 - ui_l_op2) || (s_ui_s_op1 - ui_l_op2 != s_ui_s_op1 - l_l_op2) || ((ulong)(s_ui_s_op1 - l_l_op2) != s_ui_s_op1 - ul_l_op2) || (s_ui_s_op1 - ul_l_op2 != s_ui_s_op1 - f_l_op2) || (s_ui_s_op1 - f_l_op2 != s_ui_s_op1 - d_l_op2) || ((decimal)(s_ui_s_op1 - d_l_op2) != s_ui_s_op1 - m_l_op2) || (s_ui_s_op1 - m_l_op2 != s_ui_s_op1 - i_l_op2) || (s_ui_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 7 failed"); passed = false; } if ((s_ui_s_op1 - s_i_s_op2 != s_ui_s_op1 - s_ui_s_op2) || (s_ui_s_op1 - s_ui_s_op2 != s_ui_s_op1 - s_l_s_op2) || ((ulong)(s_ui_s_op1 - s_l_s_op2) != s_ui_s_op1 - s_ul_s_op2) || (s_ui_s_op1 - s_ul_s_op2 != s_ui_s_op1 - s_f_s_op2) || (s_ui_s_op1 - s_f_s_op2 != s_ui_s_op1 - s_d_s_op2) || ((decimal)(s_ui_s_op1 - s_d_s_op2) != s_ui_s_op1 - s_m_s_op2) || (s_ui_s_op1 - s_m_s_op2 != s_ui_s_op1 - s_i_s_op2) || (s_ui_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 8 failed"); passed = false; } } { long l_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((l_l_op1 - i_l_op2 != l_l_op1 - ui_l_op2) || (l_l_op1 - ui_l_op2 != l_l_op1 - l_l_op2) || (l_l_op1 - l_l_op2 != l_l_op1 - (long)ul_l_op2) || (l_l_op1 - (long)ul_l_op2 != l_l_op1 - f_l_op2) || (l_l_op1 - f_l_op2 != l_l_op1 - d_l_op2) || ((decimal)(l_l_op1 - d_l_op2) != l_l_op1 - m_l_op2) || (l_l_op1 - m_l_op2 != l_l_op1 - i_l_op2) || (l_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 9 failed"); passed = false; } if ((l_l_op1 - s_i_s_op2 != l_l_op1 - s_ui_s_op2) || (l_l_op1 - s_ui_s_op2 != l_l_op1 - s_l_s_op2) || (l_l_op1 - s_l_s_op2 != l_l_op1 - (long)s_ul_s_op2) || (l_l_op1 - (long)s_ul_s_op2 != l_l_op1 - s_f_s_op2) || (l_l_op1 - s_f_s_op2 != l_l_op1 - s_d_s_op2) || ((decimal)(l_l_op1 - s_d_s_op2) != l_l_op1 - s_m_s_op2) || (l_l_op1 - s_m_s_op2 != l_l_op1 - s_i_s_op2) || (l_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 10 failed"); passed = false; } if ((s_l_s_op1 - i_l_op2 != s_l_s_op1 - ui_l_op2) || (s_l_s_op1 - ui_l_op2 != s_l_s_op1 - l_l_op2) || (s_l_s_op1 - l_l_op2 != s_l_s_op1 - (long)ul_l_op2) || (s_l_s_op1 - (long)ul_l_op2 != s_l_s_op1 - f_l_op2) || (s_l_s_op1 - f_l_op2 != s_l_s_op1 - d_l_op2) || ((decimal)(s_l_s_op1 - d_l_op2) != s_l_s_op1 - m_l_op2) || (s_l_s_op1 - m_l_op2 != s_l_s_op1 - i_l_op2) || (s_l_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 11 failed"); passed = false; } if ((s_l_s_op1 - s_i_s_op2 != s_l_s_op1 - s_ui_s_op2) || (s_l_s_op1 - s_ui_s_op2 != s_l_s_op1 - s_l_s_op2) || (s_l_s_op1 - s_l_s_op2 != s_l_s_op1 - (long)s_ul_s_op2) || (s_l_s_op1 - (long)s_ul_s_op2 != s_l_s_op1 - s_f_s_op2) || (s_l_s_op1 - s_f_s_op2 != s_l_s_op1 - s_d_s_op2) || ((decimal)(s_l_s_op1 - s_d_s_op2) != s_l_s_op1 - s_m_s_op2) || (s_l_s_op1 - s_m_s_op2 != s_l_s_op1 - s_i_s_op2) || (s_l_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 12 failed"); passed = false; } } { ulong ul_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((ul_l_op1 - (ulong)i_l_op2 != ul_l_op1 - ui_l_op2) || (ul_l_op1 - ui_l_op2 != ul_l_op1 - (ulong)l_l_op2) || (ul_l_op1 - (ulong)l_l_op2 != ul_l_op1 - ul_l_op2) || (ul_l_op1 - ul_l_op2 != ul_l_op1 - f_l_op2) || (ul_l_op1 - f_l_op2 != ul_l_op1 - d_l_op2) || ((decimal)(ul_l_op1 - d_l_op2) != ul_l_op1 - m_l_op2) || (ul_l_op1 - m_l_op2 != ul_l_op1 - (ulong)i_l_op2) || (ul_l_op1 - (ulong)i_l_op2 != 1)) { Console.WriteLine("testcase 13 failed"); passed = false; } if ((ul_l_op1 - (ulong)s_i_s_op2 != ul_l_op1 - s_ui_s_op2) || (ul_l_op1 - s_ui_s_op2 != ul_l_op1 - (ulong)s_l_s_op2) || (ul_l_op1 - (ulong)s_l_s_op2 != ul_l_op1 - s_ul_s_op2) || (ul_l_op1 - s_ul_s_op2 != ul_l_op1 - s_f_s_op2) || (ul_l_op1 - s_f_s_op2 != ul_l_op1 - s_d_s_op2) || ((decimal)(ul_l_op1 - s_d_s_op2) != ul_l_op1 - s_m_s_op2) || (ul_l_op1 - s_m_s_op2 != ul_l_op1 - (ulong)s_i_s_op2) || (ul_l_op1 - (ulong)s_i_s_op2 != 1)) { Console.WriteLine("testcase 14 failed"); passed = false; } if ((s_ul_s_op1 - (ulong)i_l_op2 != s_ul_s_op1 - ui_l_op2) || (s_ul_s_op1 - ui_l_op2 != s_ul_s_op1 - (ulong)l_l_op2) || (s_ul_s_op1 - (ulong)l_l_op2 != s_ul_s_op1 - ul_l_op2) || (s_ul_s_op1 - ul_l_op2 != s_ul_s_op1 - f_l_op2) || (s_ul_s_op1 - f_l_op2 != s_ul_s_op1 - d_l_op2) || ((decimal)(s_ul_s_op1 - d_l_op2) != s_ul_s_op1 - m_l_op2) || (s_ul_s_op1 - m_l_op2 != s_ul_s_op1 - (ulong)i_l_op2) || (s_ul_s_op1 - (ulong)i_l_op2 != 1)) { Console.WriteLine("testcase 15 failed"); passed = false; } if ((s_ul_s_op1 - (ulong)s_i_s_op2 != s_ul_s_op1 - s_ui_s_op2) || (s_ul_s_op1 - s_ui_s_op2 != s_ul_s_op1 - (ulong)s_l_s_op2) || (s_ul_s_op1 - (ulong)s_l_s_op2 != s_ul_s_op1 - s_ul_s_op2) || (s_ul_s_op1 - s_ul_s_op2 != s_ul_s_op1 - s_f_s_op2) || (s_ul_s_op1 - s_f_s_op2 != s_ul_s_op1 - s_d_s_op2) || ((decimal)(s_ul_s_op1 - s_d_s_op2) != s_ul_s_op1 - s_m_s_op2) || (s_ul_s_op1 - s_m_s_op2 != s_ul_s_op1 - (ulong)s_i_s_op2) || (s_ul_s_op1 - (ulong)s_i_s_op2 != 1)) { Console.WriteLine("testcase 16 failed"); passed = false; } } { float f_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((f_l_op1 - i_l_op2 != f_l_op1 - ui_l_op2) || (f_l_op1 - ui_l_op2 != f_l_op1 - l_l_op2) || (f_l_op1 - l_l_op2 != f_l_op1 - ul_l_op2) || (f_l_op1 - ul_l_op2 != f_l_op1 - f_l_op2) || (f_l_op1 - f_l_op2 != f_l_op1 - d_l_op2) || (f_l_op1 - d_l_op2 != f_l_op1 - (float)m_l_op2) || (f_l_op1 - (float)m_l_op2 != f_l_op1 - i_l_op2) || (f_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 17 failed"); passed = false; } if ((f_l_op1 - s_i_s_op2 != f_l_op1 - s_ui_s_op2) || (f_l_op1 - s_ui_s_op2 != f_l_op1 - s_l_s_op2) || (f_l_op1 - s_l_s_op2 != f_l_op1 - s_ul_s_op2) || (f_l_op1 - s_ul_s_op2 != f_l_op1 - s_f_s_op2) || (f_l_op1 - s_f_s_op2 != f_l_op1 - s_d_s_op2) || (f_l_op1 - s_d_s_op2 != f_l_op1 - (float)s_m_s_op2) || (f_l_op1 - (float)s_m_s_op2 != f_l_op1 - s_i_s_op2) || (f_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 18 failed"); passed = false; } if ((s_f_s_op1 - i_l_op2 != s_f_s_op1 - ui_l_op2) || (s_f_s_op1 - ui_l_op2 != s_f_s_op1 - l_l_op2) || (s_f_s_op1 - l_l_op2 != s_f_s_op1 - ul_l_op2) || (s_f_s_op1 - ul_l_op2 != s_f_s_op1 - f_l_op2) || (s_f_s_op1 - f_l_op2 != s_f_s_op1 - d_l_op2) || (s_f_s_op1 - d_l_op2 != s_f_s_op1 - (float)m_l_op2) || (s_f_s_op1 - (float)m_l_op2 != s_f_s_op1 - i_l_op2) || (s_f_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 19 failed"); passed = false; } if ((s_f_s_op1 - s_i_s_op2 != s_f_s_op1 - s_ui_s_op2) || (s_f_s_op1 - s_ui_s_op2 != s_f_s_op1 - s_l_s_op2) || (s_f_s_op1 - s_l_s_op2 != s_f_s_op1 - s_ul_s_op2) || (s_f_s_op1 - s_ul_s_op2 != s_f_s_op1 - s_f_s_op2) || (s_f_s_op1 - s_f_s_op2 != s_f_s_op1 - s_d_s_op2) || (s_f_s_op1 - s_d_s_op2 != s_f_s_op1 - (float)s_m_s_op2) || (s_f_s_op1 - (float)s_m_s_op2 != s_f_s_op1 - s_i_s_op2) || (s_f_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 20 failed"); passed = false; } } { double d_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((d_l_op1 - i_l_op2 != d_l_op1 - ui_l_op2) || (d_l_op1 - ui_l_op2 != d_l_op1 - l_l_op2) || (d_l_op1 - l_l_op2 != d_l_op1 - ul_l_op2) || (d_l_op1 - ul_l_op2 != d_l_op1 - f_l_op2) || (d_l_op1 - f_l_op2 != d_l_op1 - d_l_op2) || (d_l_op1 - d_l_op2 != d_l_op1 - (double)m_l_op2) || (d_l_op1 - (double)m_l_op2 != d_l_op1 - i_l_op2) || (d_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 21 failed"); passed = false; } if ((d_l_op1 - s_i_s_op2 != d_l_op1 - s_ui_s_op2) || (d_l_op1 - s_ui_s_op2 != d_l_op1 - s_l_s_op2) || (d_l_op1 - s_l_s_op2 != d_l_op1 - s_ul_s_op2) || (d_l_op1 - s_ul_s_op2 != d_l_op1 - s_f_s_op2) || (d_l_op1 - s_f_s_op2 != d_l_op1 - s_d_s_op2) || (d_l_op1 - s_d_s_op2 != d_l_op1 - (double)s_m_s_op2) || (d_l_op1 - (double)s_m_s_op2 != d_l_op1 - s_i_s_op2) || (d_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 22 failed"); passed = false; } if ((s_d_s_op1 - i_l_op2 != s_d_s_op1 - ui_l_op2) || (s_d_s_op1 - ui_l_op2 != s_d_s_op1 - l_l_op2) || (s_d_s_op1 - l_l_op2 != s_d_s_op1 - ul_l_op2) || (s_d_s_op1 - ul_l_op2 != s_d_s_op1 - f_l_op2) || (s_d_s_op1 - f_l_op2 != s_d_s_op1 - d_l_op2) || (s_d_s_op1 - d_l_op2 != s_d_s_op1 - (double)m_l_op2) || (s_d_s_op1 - (double)m_l_op2 != s_d_s_op1 - i_l_op2) || (s_d_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 23 failed"); passed = false; } if ((s_d_s_op1 - s_i_s_op2 != s_d_s_op1 - s_ui_s_op2) || (s_d_s_op1 - s_ui_s_op2 != s_d_s_op1 - s_l_s_op2) || (s_d_s_op1 - s_l_s_op2 != s_d_s_op1 - s_ul_s_op2) || (s_d_s_op1 - s_ul_s_op2 != s_d_s_op1 - s_f_s_op2) || (s_d_s_op1 - s_f_s_op2 != s_d_s_op1 - s_d_s_op2) || (s_d_s_op1 - s_d_s_op2 != s_d_s_op1 - (double)s_m_s_op2) || (s_d_s_op1 - (double)s_m_s_op2 != s_d_s_op1 - s_i_s_op2) || (s_d_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 24 failed"); passed = false; } } { decimal m_l_op1 = 16; int i_l_op2 = 15; uint ui_l_op2 = 15; long l_l_op2 = 15; ulong ul_l_op2 = 15; float f_l_op2 = 15; double d_l_op2 = 15; decimal m_l_op2 = 15; numHolder nHldr_l_op2 = new numHolder(15); if ((m_l_op1 - i_l_op2 != m_l_op1 - ui_l_op2) || (m_l_op1 - ui_l_op2 != m_l_op1 - l_l_op2) || (m_l_op1 - l_l_op2 != m_l_op1 - ul_l_op2) || (m_l_op1 - ul_l_op2 != m_l_op1 - (decimal)f_l_op2) || (m_l_op1 - (decimal)f_l_op2 != m_l_op1 - (decimal)d_l_op2) || (m_l_op1 - (decimal)d_l_op2 != m_l_op1 - m_l_op2) || (m_l_op1 - m_l_op2 != m_l_op1 - i_l_op2) || (m_l_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 25 failed"); passed = false; } if ((m_l_op1 - s_i_s_op2 != m_l_op1 - s_ui_s_op2) || (m_l_op1 - s_ui_s_op2 != m_l_op1 - s_l_s_op2) || (m_l_op1 - s_l_s_op2 != m_l_op1 - s_ul_s_op2) || (m_l_op1 - s_ul_s_op2 != m_l_op1 - (decimal)s_f_s_op2) || (m_l_op1 - (decimal)s_f_s_op2 != m_l_op1 - (decimal)s_d_s_op2) || (m_l_op1 - (decimal)s_d_s_op2 != m_l_op1 - s_m_s_op2) || (m_l_op1 - s_m_s_op2 != m_l_op1 - s_i_s_op2) || (m_l_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 26 failed"); passed = false; } if ((s_m_s_op1 - i_l_op2 != s_m_s_op1 - ui_l_op2) || (s_m_s_op1 - ui_l_op2 != s_m_s_op1 - l_l_op2) || (s_m_s_op1 - l_l_op2 != s_m_s_op1 - ul_l_op2) || (s_m_s_op1 - ul_l_op2 != s_m_s_op1 - (decimal)f_l_op2) || (s_m_s_op1 - (decimal)f_l_op2 != s_m_s_op1 - (decimal)d_l_op2) || (s_m_s_op1 - (decimal)d_l_op2 != s_m_s_op1 - m_l_op2) || (s_m_s_op1 - m_l_op2 != s_m_s_op1 - i_l_op2) || (s_m_s_op1 - i_l_op2 != 1)) { Console.WriteLine("testcase 27 failed"); passed = false; } if ((s_m_s_op1 - s_i_s_op2 != s_m_s_op1 - s_ui_s_op2) || (s_m_s_op1 - s_ui_s_op2 != s_m_s_op1 - s_l_s_op2) || (s_m_s_op1 - s_l_s_op2 != s_m_s_op1 - s_ul_s_op2) || (s_m_s_op1 - s_ul_s_op2 != s_m_s_op1 - (decimal)s_f_s_op2) || (s_m_s_op1 - (decimal)s_f_s_op2 != s_m_s_op1 - (decimal)s_d_s_op2) || (s_m_s_op1 - (decimal)s_d_s_op2 != s_m_s_op1 - s_m_s_op2) || (s_m_s_op1 - s_m_s_op2 != s_m_s_op1 - s_i_s_op2) || (s_m_s_op1 - s_i_s_op2 != 1)) { Console.WriteLine("testcase 28 failed"); passed = false; } } if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The Windows Forms user interface layer for the DotSpatial.Symbology library. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 9/27/2009 8:23:44 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Drawing; using System.Drawing.Drawing2D; namespace DotSpatial.Symbology.Forms { /// <summary> /// BreakSlider /// </summary> public class BreakSlider : IComparable<BreakSlider> { #region Private Variables private ICategory _category; private Color _color; private int _count; private Rectangle _graphBounds; private double _max; private double _min; private ICategory _nextCategory; private ColorRange _range; private Color _selectColor; private bool _selected; private double _value; #endregion #region Constructors /// <summary> /// Creates a new instance of BreakSlider /// </summary> /// <param name="graphBounds">The bounds of the graph to draw in relative to the control.</param> /// <param name="minimum">The minimum value currently in view</param> /// <param name="maximum">The maximum value currently in view</param> /// <param name="range">The color range to connect to this slider.</param> public BreakSlider(Rectangle graphBounds, double minimum, double maximum, ColorRange range) { _color = Color.Blue; _selectColor = Color.Red; _graphBounds = graphBounds; _min = minimum; _max = maximum; _range = range; } #endregion #region Methods /// <summary> /// Compares this value to the other value. /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(BreakSlider other) { return _value.CompareTo(other._value); } /// <summary> /// This sets the values for the parental bounds, as well as the double /// values for the maximum and minimum values visible on the graph. /// </summary> /// <param name="graphBounds"></param> /// <param name="min"></param> /// <param name="max"></param> public void Setup(Rectangle graphBounds, double min, double max) { _min = min; _max = max; _graphBounds = graphBounds; } /// <summary> /// Causes this slider to draw itself to the specified graphics surface. /// </summary> /// <param name="g"></param> public void Draw(Graphics g) { OnDraw(g); } /// <summary> /// Custom drawing /// </summary> /// <param name="g">The Graphics surface to draw to</param> protected virtual void OnDraw(Graphics g) { if (_value < _min || _value > _max) return; float pos = Position; RectangleF rectF = new RectangleF(pos - 1, _graphBounds.Y, 3, _graphBounds.Height); RectangleF topF = new RectangleF(pos - 4, _graphBounds.Y - 8, 8, 8); if (_selected) { LinearGradientBrush top = new LinearGradientBrush(topF, _selectColor.Lighter(.2F), _selectColor.Darker(.2F), LinearGradientMode.ForwardDiagonal); g.FillEllipse(top, topF); top.Dispose(); LinearGradientBrush lgb = new LinearGradientBrush(rectF, _selectColor.Lighter(.2f), _selectColor.Darker(.2f), LinearGradientMode.Horizontal); g.FillRectangle(lgb, rectF); lgb.Dispose(); } else { LinearGradientBrush top = new LinearGradientBrush(topF, _color.Lighter(.2F), _color.Darker(.2F), LinearGradientMode.ForwardDiagonal); g.FillEllipse(top, topF); top.Dispose(); LinearGradientBrush lgb = new LinearGradientBrush(rectF, _color.Lighter(.2f), _color.Darker(.2f), LinearGradientMode.Horizontal); g.FillRectangle(lgb, rectF); lgb.Dispose(); } } #endregion #region Properties /// <summary> /// Gets or sets the color range that this break is the maximum value for. /// </summary> public ColorRange Range { get { return _range; } set { _range = value; } } /// <summary> /// Gets the bounds of the handle that extends above the graph /// </summary> public Rectangle HandleBounds { get { return new Rectangle((int)Position - 4, _graphBounds.Y - 8, 8, 8); } } /// <summary> /// Gets a bounding rectangle in coordinates relative to the parent /// </summary> public Rectangle Bounds { get { return new Rectangle((int)Position - 5, _graphBounds.Top + 5, 10, _graphBounds.Height - 5); } } /// <summary> /// Gets or sets the category that has a maximum value equal to this break. /// </summary> public ICategory Category { get { return _category; } set { _category = value; } } /// <summary> /// Gets or sets the color of this slider /// </summary> public Color Color { get { return _color; } set { _color = value; } } /// <summary> /// Gets or sets the integer count representing the number of members in the class. /// (Technically represented left of the line. /// </summary> public int Count { get { return _count; } set { _count = value; } } /// <summary> /// Gets or sets the next category, which should have a minimum corresponding to this break. /// </summary> public ICategory NextCategory { get { return _nextCategory; } set { _nextCategory = value; } } /// <summary> /// Gets or sets the position of this slider /// </summary> public float Position { get { return (float)(_graphBounds.Width * (_value - _min) / (_max - _min) + _graphBounds.X); } set { _value = ((value - _graphBounds.X) / _graphBounds.Width) * (_max - _min) + _min; _range.Range.Maximum = _value; if (_nextCategory != null) _nextCategory.Range.Minimum = _value; } } /// <summary> /// Gets or sets whether or not this slider is selected. /// </summary> public bool Selected { get { return _selected; } set { _selected = value; } } /// <summary> /// Gets or sets the selected color /// </summary> public Color SelectColor { get { return _selectColor; } set { _selectColor = value; } } /// <summary> /// Gets or sets the double value where this break should occur. /// </summary> public double Value { get { return _value; } set { _value = value; } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { [ExportWorkspaceService(typeof(ISolutionCrawlerRegistrationService), ServiceLayer.Host), Shared] internal partial class SolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService { private const string Default = "*"; private readonly object _gate; private readonly SolutionCrawlerProgressReporter _progressReporter; private readonly IAsynchronousOperationListener _listener; private readonly Dictionary<Workspace, WorkCoordinator> _documentWorkCoordinatorMap; private ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> _analyzerProviders; [ImportingConstructor] public SolutionCrawlerRegistrationService( [ImportMany] IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, [ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners) { _gate = new object(); _analyzerProviders = analyzerProviders.GroupBy(kv => kv.Metadata.Name).ToImmutableDictionary(g => g.Key, g => g.ToImmutableArray()); AssertAnalyzerProviders(_analyzerProviders); _documentWorkCoordinatorMap = new Dictionary<Workspace, WorkCoordinator>(ReferenceEqualityComparer.Instance); _listener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.SolutionCrawler); _progressReporter = new SolutionCrawlerProgressReporter(_listener); } public void Register(Workspace workspace) { var correlationId = LogAggregator.GetNextId(); lock (_gate) { if (_documentWorkCoordinatorMap.ContainsKey(workspace)) { // already registered. return; } var coordinator = new WorkCoordinator( _listener, GetAnalyzerProviders(workspace), new Registration(correlationId, workspace, _progressReporter)); _documentWorkCoordinatorMap.Add(workspace, coordinator); } SolutionCrawlerLogger.LogRegistration(correlationId, workspace); } public void Unregister(Workspace workspace, bool blockingShutdown = false) { var coordinator = default(WorkCoordinator); lock (_gate) { if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out coordinator)) { // already unregistered return; } _documentWorkCoordinatorMap.Remove(workspace); coordinator.Shutdown(blockingShutdown); } SolutionCrawlerLogger.LogUnregistration(coordinator.CorrelationId); } public void AddAnalyzerProvider(IIncrementalAnalyzerProvider provider, IncrementalAnalyzerProviderMetadata metadata) { // now update all existing work coordinator lock (_gate) { var lazyProvider = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => provider, metadata); // update existing map for future solution crawler registration - no need for interlock but this makes add or update easier ImmutableInterlocked.AddOrUpdate(ref _analyzerProviders, metadata.Name, (n) => ImmutableArray.Create(lazyProvider), (n, v) => v.Add(lazyProvider)); // assert map integrity AssertAnalyzerProviders(_analyzerProviders); // find existing coordinator to update var lazyProviders = _analyzerProviders[metadata.Name]; foreach (var kv in _documentWorkCoordinatorMap) { var workspace = kv.Key; var coordinator = kv.Value; if (!TryGetProvider(workspace.Kind, lazyProviders, out var picked) || picked != lazyProvider) { // check whether new provider belong to current workspace continue; } var analyzer = lazyProvider.Value.CreateIncrementalAnalyzer(workspace); coordinator.AddAnalyzer(analyzer, metadata.HighPriorityForActiveFile); } } } public void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable<ProjectId> projectIds, IEnumerable<DocumentId> documentIds, bool highPriority) { lock (_gate) { if (!_documentWorkCoordinatorMap.TryGetValue(workspace, out var coordinator)) { // this can happen if solution crawler is already unregistered from workspace. // one of those example will be VS shutting down so roslyn package is disposed but there is a pending // async operation. return; } // no specific projects or documents provided if (projectIds == null && documentIds == null) { coordinator.Reanalyze(analyzer, workspace.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet(), highPriority); return; } // specific documents provided if (projectIds == null) { coordinator.Reanalyze(analyzer, documentIds.ToSet(), highPriority); return; } var solution = workspace.CurrentSolution; var set = new HashSet<DocumentId>(documentIds ?? SpecializedCollections.EmptyEnumerable<DocumentId>()); set.UnionWith(projectIds.Select(id => solution.GetProject(id)).SelectMany(p => p.DocumentIds)); coordinator.Reanalyze(analyzer, set, highPriority); } } internal void WaitUntilCompletion_ForTestingPurposesOnly(Workspace workspace, ImmutableArray<IIncrementalAnalyzer> workers) { if (_documentWorkCoordinatorMap.ContainsKey(workspace)) { _documentWorkCoordinatorMap[workspace].WaitUntilCompletion_ForTestingPurposesOnly(workers); } } internal void WaitUntilCompletion_ForTestingPurposesOnly(Workspace workspace) { if (_documentWorkCoordinatorMap.ContainsKey(workspace)) { _documentWorkCoordinatorMap[workspace].WaitUntilCompletion_ForTestingPurposesOnly(); } } private IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> GetAnalyzerProviders(Workspace workspace) { foreach (var kv in _analyzerProviders) { var lazyProviders = kv.Value; // try get provider for the specific workspace kind if (TryGetProvider(workspace.Kind, lazyProviders, out var lazyProvider)) { yield return lazyProvider; continue; } // try get default provider if (TryGetProvider(Default, lazyProviders, out lazyProvider)) { yield return lazyProvider; } } } private bool TryGetProvider( string kind, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> lazyProviders, out Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata> lazyProvider) { // set out param lazyProvider = null; // try find provider for specific workspace kind if (kind != Default) { foreach (var provider in lazyProviders) { if (provider.Metadata.WorkspaceKinds?.Any(wk => wk == kind) == true) { lazyProvider = provider; return true; } } return false; } // try find default provider foreach (var provider in lazyProviders) { if (IsDefaultProvider(provider.Metadata)) { lazyProvider = provider; return true; } return false; } return false; } [Conditional("DEBUG")] private static void AssertAnalyzerProviders( ImmutableDictionary<string, ImmutableArray<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>> analyzerProviders) { #if DEBUG // make sure there is duplicated provider defined for same workspace. var set = new HashSet<string>(); foreach (var kv in analyzerProviders) { foreach (var lazyProvider in kv.Value) { if (IsDefaultProvider(lazyProvider.Metadata)) { Contract.Requires(set.Add(Default)); continue; } foreach (var kind in lazyProvider.Metadata.WorkspaceKinds) { Contract.Requires(set.Add(kind)); } } set.Clear(); } #endif } private static bool IsDefaultProvider(IncrementalAnalyzerProviderMetadata providerMetadata) { return providerMetadata.WorkspaceKinds == null || providerMetadata.WorkspaceKinds.Length == 0; } private class Registration { public readonly int CorrelationId; public readonly Workspace Workspace; public readonly SolutionCrawlerProgressReporter ProgressReporter; public Registration(int correlationId, Workspace workspace, SolutionCrawlerProgressReporter progressReporter) { CorrelationId = correlationId; Workspace = workspace; ProgressReporter = progressReporter; } public Solution CurrentSolution { get { return Workspace.CurrentSolution; } } public TService GetService<TService>() where TService : IWorkspaceService { return Workspace.Services.GetService<TService>(); } } } }
// Copyright (C) 2016 Moriyoshi Koizumi <mozo@mozo.jp> // // 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.Security; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; namespace Win32API { public sealed class Win32APIException: Exception { int code; string message; string[] arguments; public int Code { get { return code; } set { code = value; } } public override string Message { get { if (message == null) { IntPtr messageText = IntPtr.Zero; IntPtr[] _arguments = null; if (arguments != null) { _arguments = new IntPtr[arguments.Length]; for (var i = 0; i < arguments.Length; i++) { _arguments[i] = Marshal.StringToHGlobalUni(arguments[i]); } } try { uint messageTextLen = Kernel32.FormatMessage( Kernel32.FormatMessageFlags.ALLOCATE_BUFFER | Kernel32.FormatMessageFlags.FROM_SYSTEM | Kernel32.FormatMessageFlags.ARGUMENT_ARRAY, IntPtr.Zero, (uint)Code, 0, ref messageText, 0, _arguments ); if (messageTextLen != 0) { message = Marshal.PtrToStringUni(messageText, (int)messageTextLen).Trim(); } } finally { if (messageText != IntPtr.Zero) { Marshal.FreeHGlobal(messageText); } if (_arguments != null) { foreach (IntPtr a in _arguments) { Marshal.FreeHGlobal(a); } } } } return message; } } public Win32APIException(int code, params string[] arguments) { this.code = code; this.arguments = arguments; } } public sealed class UserEnv { [DllImport("userenv.dll", EntryPoint="CreateEnvironmentBlock", SetLastError=true)] public static extern bool _CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit); public static IntPtr CreateEnvironmentBlock(IntPtr hToken, bool bInherit) { IntPtr retval; if (!_CreateEnvironmentBlock(out retval, hToken, bInherit)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } [DllImport("userenv.dll", EntryPoint="DestroyEnvironmentBlock", SetLastError=true)] public static extern bool _DestroyEnvironmentBlock(IntPtr lpEnvironment); public static void DestroyEnvironmentBlock(IntPtr lpEnvironment) { if (!_DestroyEnvironmentBlock(lpEnvironment)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } } [StructLayout(LayoutKind.Sequential)] public struct PROFILEINFO { public int dwSize; public int dwFlags; public string lpUserName; public string lpProfilePath; public string lpDefaultPath; public string lpServerName; public string lpPolicyPath; public IntPtr hProfile; } [DllImport("userenv.dll", EntryPoint="LoadUserProfile", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool _LoadUserProfile(IntPtr hToken, ref PROFILEINFO lpProfileInfo); public static PROFILEINFO LoadUserProfile(IntPtr hToken, string userName) { PROFILEINFO retval = new PROFILEINFO(); retval.dwSize = Marshal.SizeOf(typeof(PROFILEINFO)); retval.lpUserName = userName; if (!_LoadUserProfile(hToken, ref retval)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } [DllImport("userenv.dll", EntryPoint="UnloadUserProfile", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool _UnloadUserProfile(IntPtr hToken, IntPtr hProfile); public static void UnloadUserProfile(IntPtr hToken, ref PROFILEINFO lpProfileInfo) { if (!_UnloadUserProfile(hToken, lpProfileInfo.hProfile)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } } } public sealed class Kernel32 { [Flags] public enum FormatMessageFlags: uint { ALLOCATE_BUFFER = 0x00000100, IGNORE_INSERTS = 0x00000200, FROM_SYSTEM = 0x00001000, ARGUMENT_ARRAY = 0x00002000, FROM_HMODULE = 0x00000800, FROM_STRING = 0x00000400 } [DllImport("Kernel32.dll", EntryPoint="FormatMessageW", SetLastError=true)] public static extern uint FormatMessage( FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer, uint nSize, IntPtr[] Arguments ); [Flags] public enum CreateProcessFlags: uint { CREATE_BREAKAWAY_FROM_JOB = 0x01000000, CREATE_DEFAULT_ERROR_MODE = 0x04000000, CREATE_NEW_CONSOLE = 0x00000010, CREATE_NEW_PROCESS_GROUP = 0x00000200, CREATE_NO_WINDOW = 0x08000000, CREATE_PROTECTED_PROCESS = 0x00040000, CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000, CREATE_SEPARATE_WOW_VDM = 0x00000800, CREATE_SHARED_WOW_VDM = 0x00001000, CREATE_SUSPENDED = 0x00000004, CREATE_UNICODE_ENVIRONMENT = 0x00000400, DEBUG_ONLY_THIS_PROCESS = 0x00000002, DEBUG_PROCESS = 0x00000001, DETACHED_PROCESS = 0x00000008, EXTENDED_STARTUPINFO_PRESENT = 0x00080000, INHERIT_PARENT_AFFINITY = 0x00010000 } [Flags] public enum StartUpInfoFlags: uint { STARTF_USESHOWWINDOW = 0x00000001, STARTF_USESIZE = 0x00000002, STARTF_USEPOSITION = 0x00000004, STARTF_USECOUNTCHARS = 0x00000008, STARTF_USEFILLATTRIBUTE = 0x00000010, STARTF_RUNFULLSCREEN = 0x00000020, // ignored for non-x86 platforms STARTF_FORCEONFEEDBACK = 0x00000040, STARTF_FORCEOFFFEEDBACK = 0x00000080, STARTF_USESTDHANDLES = 0x00000100, } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct STARTUPINFO { public int cb; public IntPtr lpReserved; public string lpDesktop; public string lpTitle; public int dwX; public int dwY; public int dwXSize; public int dwYSize; public int dwXCountChars; public int dwYCountChars; public int dwFillAttribute; public StartUpInfoFlags dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; public STARTUPINFO( StartUpInfoFlags dwFlags = 0, string lpDesktop = null, string lpTitle = null, int dwX = CW_USEDEFAULT, int dwY = CW_USEDEFAULT, int dwXSize = CW_USEDEFAULT, int dwYSize = CW_USEDEFAULT, int dwXCountChars = 0, int dwYCountChars = 0, int dwFillAttribute = 0, short wShowWindow = 0, IntPtr hStdInput = default(IntPtr), IntPtr hStdOutput = default(IntPtr), IntPtr hStdError = default(IntPtr) ) { this.lpReserved = IntPtr.Zero; this.lpDesktop = lpDesktop; this.lpTitle = lpTitle; this.dwX = dwX; this.dwY = dwY; this.dwXSize = dwXSize; this.dwYSize = dwYSize; this.dwXCountChars = dwXCountChars; this.dwYCountChars = dwYCountChars; this.dwFillAttribute = dwFillAttribute; this.dwFlags = dwFlags; this.wShowWindow = wShowWindow; this.cbReserved2 = 0; this.lpReserved2 = IntPtr.Zero; this.hStdInput = hStdInput; this.hStdOutput = hStdOutput; this.hStdError = hStdError; this.cb = Marshal.SizeOf(typeof(STARTUPINFO)); } } [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } public const int CW_USEDEFAULT = -1; [DllImport("kernel32.dll", EntryPoint="CreateProcessW", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool _CreateProcess( string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation ); public static PROCESS_INFORMATION CreateProcess( string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo ) { PROCESS_INFORMATION retval; if (!_CreateProcess( lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, ref lpStartupInfo, out retval )) { throw new Win32APIException(Marshal.GetLastWin32Error(), lpApplicationName); } return retval; } [DllImport("kernel32.dll", EntryPoint="CloseHandle", SetLastError=true)] public static extern bool _CloseHandle(IntPtr hObject); public static void CloseHandle(IntPtr hObject) { if (!_CloseHandle(hObject)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } } [DllImport("Kernel32.dll", EntryPoint="RtlMoveMemory", SetLastError=false)] public static extern void MoveMemory(IntPtr dest, IntPtr src, uint size); public enum WaitCode: uint { OBJECT_0 = 0x00000000, ABANDONED = 0x00000080, TIMEOUT = 0x00000102, FAILED = 0xFFFFFFFF } [DllImport("kernel32.dll", EntryPoint="WaitForSingleObject", SetLastError=true)] public static extern WaitCode _WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds); public static WaitCode WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds) { WaitCode retval = _WaitForSingleObject(hHandle, dwMilliseconds); if (retval == WaitCode.FAILED) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } [DllImport("kernel32.dll", EntryPoint="WaitForInputIdle", SetLastError=true)] public static extern WaitCode _WaitForInputIdle(IntPtr hHandle, uint dwMilliseconds); public static WaitCode WaitForInputIdle(IntPtr hHandle, uint dwMilliseconds) { WaitCode retval = _WaitForInputIdle(hHandle, dwMilliseconds); if (retval == WaitCode.FAILED) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } [DllImport("kernel32.dll", EntryPoint="GetExitCodeProcess", SetLastError=true)] public static extern bool _GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode); public static uint GetExitCodeProcess(IntPtr hProcess) { uint retval; if (!_GetExitCodeProcess(hProcess, out retval)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } [DllImport("kernel32.dll", EntryPoint="GetCurrentProcess", SetLastError=false)] public static extern IntPtr GetCurrentProcess(); [DllImport("kernel32.dll", EntryPoint="GetProcessId", SetLastError=false)] public static extern uint GetProcessId(IntPtr hProcess); } public sealed class User32 { public enum ShowWindowCommand { SW_HIDE = 0, SW_SHOWNORMAL = 1, SW_NORMAL = 1, SW_SHOWMINIMIZED = 2, SW_SHOWMAXIMIZED = 3, SW_MAXIMIZE = 3, SW_SHOWNOACTIVATE = 4, SW_SHOW = 5, SW_MINIMIZE = 6, SW_SHOWMINNOACTIVE = 7, SW_SHOWNA = 8, SW_RESTORE = 9, SW_SHOWDEFAULT = 10, SW_MAX = 10 } [DllImport("user32.dll", EntryPoint="GetProcessWindowStation", SetLastError=true)] public static extern IntPtr GetProcessWindowStation(); public enum UserObjectInformationIndex: int { UOI_FLAGS = 1, UOI_NAME, UOI_TYPE, UOI_USER_SID, UOI_HEAPSIZE, UOI_IO } public struct USEROBJECTFLAGS { public bool fInherit; public bool fReserved; public uint dwFlags; }; [DllImport("user32.dll", EntryPoint="GetUserObjectInformation", SetLastError=true)] public static extern bool _GetUserObjectInformation( IntPtr hObj, UserObjectInformationIndex nIndex, IntPtr pvInfo, uint nLength, out uint lpnLengthNeeded ); public static object GetUserObjectInformation(IntPtr hObj, UserObjectInformationIndex nIndex) { uint len; _GetUserObjectInformation(hObj, nIndex, IntPtr.Zero, (uint)0, out len); IntPtr buf = Marshal.AllocHGlobal((int)len); try { if (!_GetUserObjectInformation(hObj, nIndex, buf, len, out len)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } if (nIndex == UserObjectInformationIndex.UOI_FLAGS) { return Marshal.PtrToStructure<USEROBJECTFLAGS>(buf); } else { byte[] retval = new byte[len]; Marshal.Copy(buf, retval, 0, (int)len); return retval; } } finally { Marshal.FreeHGlobal(buf); } } public delegate bool EnumDesktopProc( [MarshalAs(UnmanagedType.LPWStr)] string lpszDesktop, uint lParam ); [DllImport("user32.dll", EntryPoint="EnumDesktopsW", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool _EnumDesktops( IntPtr hwinsta, [MarshalAs(UnmanagedType.FunctionPtr)] EnumDesktopProc lpEnumFunc, uint lParam ); public static IList<string> EnumDesktops(IntPtr hwinsta) { List<string> retval = new List<string>(); if (!_EnumDesktops( hwinsta, delegate (string lpszDesktop, uint lParam) { retval.Add(lpszDesktop); return true; }, 0)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } [DllImport("user32.dll", EntryPoint="OpenDesktopW", SetLastError=true, CharSet=CharSet.Unicode)] public static extern IntPtr _OpenDesktop( string lpszDesktop, uint dwFlags, bool fInherit, AdvApi32.ACCESS_MASK dwDesiredAccess ); public static IntPtr OpenDesktop(string lpszDesktop, uint dwFlags, bool fInherit, AdvApi32.ACCESS_MASK dwDesiredAccess) { IntPtr retval = _OpenDesktop(lpszDesktop, dwFlags, fInherit, dwDesiredAccess); if (retval == IntPtr.Zero) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } [DllImport("user32.dll", EntryPoint="CloseDesktop", SetLastError=true)] public static extern bool _CloseDesktop(IntPtr hDesktop); public static void CloseDesktop(IntPtr hDesktop) { if (!_CloseDesktop(hDesktop)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } } [Flags] public enum DESKTOP_ACCESS_MASK: uint { DESKTOP_READOBJECTS = 0x0001, DESKTOP_CREATEWINDOW = 0x0002, DESKTOP_CREATEMENU = 0x0004, DESKTOP_HOOKCONTROL = 0x0008, DESKTOP_JOURNALRECORD = 0x0010, DESKTOP_JOURNALPLAYBACK = 0x0020, DESKTOP_ENUMERATE = 0x0040, DESKTOP_WRITEOBJECTS = 0x0080, DESKTOP_SWITCHDESKTOP = 0x0100 } } public sealed class AdvApi32 { [StructLayout(LayoutKind.Sequential)] public struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public int bInheritHandle; } public enum LogonType: int { INTERACTIVE = 2, NETWORK, BATCH, SERVICE, UNLOCK = 7, NETWORK_CLEARTEXT, NEW_CREDENTIALS } public enum LogonProvider: int { DEFAULT = 0, WINNT35 = 1, WINNT40 = 2, WINNT50 = 3 } [DllImport("advapi32.dll", EntryPoint="LogonUserW", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool _LogonUser( string pszUserName, string pszDomain, string pszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken ); [DllImport("advapi32.dll", EntryPoint="LogonUserW", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool _LogonUser( string pszUserName, string pszDomain, IntPtr pszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken ); public static bool _LogonUser( string pszUserName, string pszDomain, SecureString pszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out IntPtr phToken ) { IntPtr password = Marshal.SecureStringToCoTaskMemUnicode(pszPassword); try { return _LogonUser( pszUserName, pszDomain, password, dwLogonType, dwLogonProvider, out phToken ); } finally { Marshal.ZeroFreeCoTaskMemUnicode(password); } } public static IntPtr LogonUser( string pszUserName, string pszDomain, string pszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider ) { IntPtr token = IntPtr.Zero; if (!_LogonUser(pszUserName, pszDomain, pszPassword, dwLogonType, dwLogonProvider, out token)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return token; } public static IntPtr LogonUser( string pszUserName, string pszDomain, SecureString pszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider ) { IntPtr token = IntPtr.Zero; if (!_LogonUser(pszUserName, pszDomain, pszPassword, dwLogonType, dwLogonProvider, out token)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return token; } [DllImport("advapi32.dll", EntryPoint="CreateProcessAsUserW", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool _CreateProcessAsUser( IntPtr hToken, string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, Kernel32.CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref Kernel32.STARTUPINFO lpStartupInfo, out Kernel32.PROCESS_INFORMATION lpProcessInformation ); public static Kernel32.PROCESS_INFORMATION CreateProcessAsUser( IntPtr hToken, string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, Kernel32.CreateProcessFlags dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref Kernel32.STARTUPINFO lpStartupInfo ) { Kernel32.PROCESS_INFORMATION retval; if (!_CreateProcessAsUser( hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, ref lpStartupInfo, out retval )) { throw new Win32APIException(Marshal.GetLastWin32Error(), lpApplicationName); } return retval; } [DllImport("advapi32.dll", EntryPoint="ImpersonateLoggedOnUser", SetLastError=true)] public static extern bool _ImpersonateLoggedOnUser(IntPtr hToken); public static void ImpersonateLoggedOnUser(IntPtr hToken) { if (!_ImpersonateLoggedOnUser(hToken)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } } [DllImport("advapi32.dll", EntryPoint="ConvertSidToStringSidW", SetLastError=true)] public static extern bool _ConvertSidToStringSid(IntPtr sid, out IntPtr stringSid); public static string ConvertSidToStringSid(IntPtr sid) { IntPtr str; if (!_ConvertSidToStringSid(sid, out str)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } try { return Marshal.PtrToStringUni(str); } finally { Marshal.FreeHGlobal(str); } } [Flags] public enum SECURITY_INFORMATION: uint { OWNER = 0x00000001, GROUP = 0x00000002, DACL = 0x00000004, SACL = 0x00000008, UNPROTECTED_SACL = 0x10000000, UNPROTECTED_DACL = 0x20000000, PROTECTED_SACL = 0x40000000, PROTECTED_DACL = 0x80000000 } public enum SE_OBJECT_TYPE { UNKNOWN_OBJECT_TYPE = 0, FILE_OBJECT, SERVICE, PRINTER, REGISTRY_KEY, LMSHARE, KERNEL_OBJECT, WINDOW_OBJECT, DS_OBJECT, DS_OBJECT_ALL, PROVIDER_DEFINED_OBJECT, WMIGUID_OBJECT, REGISTRY_WOW64_32KEY } [DllImport("advapi32.dll", EntryPoint="FreeSid", SetLastError=true)] public static extern IntPtr FreeSid(IntPtr sid); [DllImport("advapi32.dll", EntryPoint="GetLengthSid", SetLastError=true)] public static extern uint GetLengthSid(IntPtr sid); [DllImport("advapi32.dll", EntryPoint="ConvertStringSidToSidW", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool _ConvertStringSidToSid(string stringSid, out IntPtr sid); public static IntPtr ConvertStringSidToSid(string stringSid) { IntPtr retval; if (!_ConvertStringSidToSid(stringSid, out retval)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } public static int ConvertStringSidToSid(string stringSid, IntPtr buf) { string[] components = stringSid.Split('-'); if (components.Length < 3 || components.Length > 10 || components[0] != "S") { throw new ArgumentException(string.Format("Specified string ({}) is not a valid string SID", stringSid)); } int nSubauthorities = components.Length - 3; int size = 8 + nSubauthorities * 4; if (buf != IntPtr.Zero) { int revision = int.Parse(components[1]); long identifierAuthority = long.Parse(components[2]); Marshal.WriteByte(buf + 0, (byte)revision); Marshal.WriteByte(buf + 1, (byte)nSubauthorities); Marshal.WriteByte(buf + 2, (byte)((identifierAuthority >> 40) & 255)); Marshal.WriteByte(buf + 3, (byte)((identifierAuthority >> 32) & 255)); Marshal.WriteByte(buf + 4, (byte)((identifierAuthority >> 24) & 255)); Marshal.WriteByte(buf + 5, (byte)((identifierAuthority >> 16) & 255)); Marshal.WriteByte(buf + 6, (byte)((identifierAuthority >> 8) & 255)); Marshal.WriteByte(buf + 7, (byte)((identifierAuthority >> 0) & 255)); for (int i = 0; i < nSubauthorities; i++) { Marshal.WriteInt32(buf + 8 + i * 4, (int)uint.Parse(components[i + 3])); } } return size; } [StructLayout(LayoutKind.Sequential)] public struct _ACL { byte AclRevision; byte Sbz1; ushort AclSize; ushort AceCount; ushort Sbz2; } public enum AceType: byte { ACCESS_ALLOWED_ACE_TYPE = 0x0, ACCESS_MIN_MS_ACE_TYPE = 0x0, ACCESS_DENIED_ACE_TYPE = 0x1, SYSTEM_AUDIT_ACE_TYPE = 0x2, SYSTEM_ALARM_ACE_TYPE = 0x3, ACCESS_MAX_MS_V2_ACE_TYPE = 0x3, ACCESS_ALLOWED_COMPOUND_ACE_TYPE = 0x4, ACCESS_MAX_MS_V3_ACE_TYPE = 0x4, ACCESS_ALLOWED_OBJECT_ACE_TYPE = 0x5, ACCESS_MIN_MS_OBJECT_ACE_TYPE = 0x5, ACCESS_DENIED_OBJECT_ACE_TYPE = 0x6, SYSTEM_AUDIT_OBJECT_ACE_TYPE = 0x7, SYSTEM_ALARM_OBJECT_ACE_TYPE = 0x8, ACCESS_MAX_MS_OBJECT_ACE_TYPE = 0x8, ACCESS_MAX_MS_V4_ACE_TYPE = 0x8, ACCESS_MAX_MS_ACE_TYPE = 0x8, ACCESS_ALLOWED_CALLBACK_ACE_TYPE = 0x9, ACCESS_DENIED_CALLBACK_ACE_TYPE = 0xA, ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE = 0xB, ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE = 0xC, SYSTEM_AUDIT_CALLBACK_ACE_TYPE = 0xD, SYSTEM_ALARM_CALLBACK_ACE_TYPE = 0xE, SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE = 0xF, SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE = 0x10, SYSTEM_MANDATORY_LABEL_ACE_TYPE = 0x11, SYSTEM_RESOURCE_ATTRIBUTE_ACE_TYPE = 0x12, SYSTEM_SCOPED_POLICY_ID_ACE_TYPE = 0x13, ACCESS_MAX_MS_V5_ACE_TYPE = 0x13 } [Flags] public enum AceFlags: byte { OBJECT_INHERIT_ACE = 0x1, CONTAINER_INHERIT_ACE = 0x2, NO_PROPAGATE_INHERIT_ACE = 0x4, INHERIT_ONLY_ACE = 0x8, INHERITED_ACE = 0x10, VALID_INHERIT_FLAGS = 0x1F, SUCCESSFUL_ACCESS_ACE_FLAG = 0x40, FAILED_ACCESS_ACE_FLAG = 0x80 } [Flags] public enum ACCESS_MASK: uint { DELETE = 0x00010000, READ_CONTROL = 0x00020000, WRITE_DAC = 0x00040000, WRITE_OWNER = 0x00080000, SYNCHRONIZE = 0x00100000, STANDARD_RIGHTS_REQUIRED = 0x000F0000, STANDARD_RIGHTS_READ = READ_CONTROL, STANDARD_RIGHTS_WRITE = READ_CONTROL, STANDARD_RIGHTS_EXECUTE = READ_CONTROL, STANDARD_RIGHTS_ALL = 0x001F0000, SPECIFIC_RIGHTS_ALL = 0x0000FFFF, ACCESS_SYSTEM_SECURITY = 0x01000000, MAXIMUM_ALLOWED = 0x02000000, GENERIC_READ = 0x80000000, GENERIC_WRITE = 0x40000000, GENERIC_EXECUTE = 0x20000000, GENERIC_ALL = 0x10000000 } [StructLayout(LayoutKind.Sequential)] struct _ACE_HEADER { AceType AceType; AceFlags AceFlags; ushort AceSize; } [StructLayout(LayoutKind.Sequential)] public struct _ACCESS_ALLOWED_ACE { _ACE_HEADER Header; ACCESS_MASK Mask; uint SidStart; } [StructLayout(LayoutKind.Sequential)] public struct _ACCESS_ALLOWED_CALLBACK_ACE { _ACE_HEADER Header; ACCESS_MASK Mask; uint SidStart; } public interface IACE { AceType AceType { get; } AceFlags AceFlags { get; } int Length { get; } int Render(IntPtr p); } public abstract class ACE: IACE { AceFlags aceFlags; public abstract AceType AceType { get; } public AceFlags AceFlags { get { return aceFlags; } set { aceFlags = value; } } public abstract int Length { get; } public abstract int Render(IntPtr p); protected ACE(AceFlags aceFlags) { this.aceFlags = aceFlags; } } public class OpaqueACE: IACE { IntPtr ptr; public AceType AceType { get { return (AceType)Marshal.ReadByte(ptr, 0); } } public AceFlags AceFlags { get { return (AceFlags)Marshal.ReadByte(ptr, 1); } } public int Length { get { return (int)(ushort)Marshal.ReadInt16(ptr, 2); } } public int Render(IntPtr buf) { int length = Length; Kernel32.MoveMemory(buf, ptr, (uint)length); return length; } public OpaqueACE(IntPtr ptr) { this.ptr = ptr; } } public class AccessAllowed: ACE { public override AceType AceType { get { return AceType.ACCESS_ALLOWED_ACE_TYPE; } } public ACCESS_MASK AccessMask; public string SID; public override int Length { get { return 4 + 4 + ConvertStringSidToSid(SID, IntPtr.Zero); } } public override int Render(IntPtr buf) { Marshal.WriteByte(buf + 0, (byte)AceType); Marshal.WriteByte(buf + 1, (byte)AceFlags); Marshal.WriteInt32(buf + 4, (int)AccessMask); int aceSize = 8 + ConvertStringSidToSid(SID, buf + 8); Marshal.WriteInt16(buf + 2, (short)(ushort)aceSize); return aceSize; } public AccessAllowed(AceFlags aceFlags, ACCESS_MASK accessMask, string sid): base(aceFlags) { this.AccessMask = accessMask; this.SID = sid; } } public const int MIN_ACL_REVISION = 2; public const int MAX_ACL_REVISION = 4; public interface IACL: IEnumerable<IACE> { IntPtr Render(); int Count { get; } int Length { get; } } public class ACEEnumerator: IEnumerator<IACE> { IACE current; IntPtr pAcl; IntPtr pEnd; IntPtr p; int i; int count; public IACE Current { get { return current; } } object IEnumerator.Current { get { return Current; } } public bool MoveNext() { if (i >= count || (long)p >= (long)pEnd) { return false; } AceType aceType = (AceType)Marshal.ReadByte(p, 0); AceFlags aceFlags = (AceFlags)Marshal.ReadByte(p, 1); int aceSize = (int)(ushort)Marshal.ReadInt16(p, 2); IACE ace = null; switch (aceType) { case AceType.ACCESS_ALLOWED_ACE_TYPE: ACCESS_MASK accessMask = (ACCESS_MASK)Marshal.ReadInt32(p, 4); ace = new AccessAllowed(aceFlags, accessMask, ConvertSidToStringSid(p + 8)); break; default: ace = new OpaqueACE(p); break; } current = ace; p += aceSize; i++; return true; } public void Reset() { this.p = pAcl + 8; this.i = 0; } public void Dispose() { } public ACEEnumerator(IntPtr pAcl, int count) { int aclRevision = (int)Marshal.ReadByte(pAcl, 0); if (aclRevision < MIN_ACL_REVISION || aclRevision > MAX_ACL_REVISION) { throw new ArgumentException(string.Format("Invalid ACL revision: {}", aclRevision)); } int aclSize = (int)(ushort)Marshal.ReadInt16(pAcl, 2); int aclCount = count; this.pAcl = pAcl; this.pEnd = pAcl + 8 + aclSize; this.count = aclCount; Reset(); } } public class ACLView: IACL { IntPtr pAcl; public IntPtr Ptr { get { return pAcl; } } public IEnumerator<IACE> GetEnumerator() { return new ACEEnumerator(pAcl, Count); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return (int)(ushort)Marshal.ReadInt16(pAcl, 4); } } public int Length { get { return (ushort)Marshal.ReadInt16(pAcl, 2); } } public ACLView(IntPtr pAcl) { this.pAcl = pAcl; } public IntPtr Render() { uint aclSize = (uint)Length; IntPtr buf = Marshal.AllocHGlobal((int)aclSize); Kernel32.MoveMemory(buf, pAcl, aclSize); return buf; } } public class ACL: List<IACE>, IACL { public int Length { get { int aclSize = 8; foreach (IACE ace in this) { aclSize += ace.Length; } return aclSize; } } public IntPtr Render() { int aclSize = Length; IntPtr buf = Marshal.AllocHGlobal(aclSize); Marshal.WriteByte(buf, 2); Marshal.WriteInt16(buf + 2, (short)aclSize); Marshal.WriteInt16(buf + 4, (short)Count); IntPtr p = buf + 8; foreach (IACE ace in this) { p += ace.Render(p); } return buf; } public ACL(): base() {} public ACL(IEnumerable<IACE> enumerable): base(enumerable) {} } [Flags] public enum SECURITY_DESCRIPTOR_CONTROL: ushort { SE_OWNER_DEFAULTED = 0x0001, SE_GROUP_DEFAULTED = 0x0002, SE_DACL_PRESENT = 0x0004, SE_DACL_DEFAULTED = 0x0008, SE_SACL_PRESENT = 0x0010, SE_SACL_DEFAULTED = 0x0020, SE_DACL_AUTO_INHERIT_REQ = 0x0100, SE_SACL_AUTO_INHERIT_REQ = 0x0200, SE_SACL_AUTO_INHERITED = 0x0800, SE_DACL_PROTECTED = 0x1000, SE_SACL_PROTECTED = 0x2000, SE_RM_CONTROL_VALID = 0x4000, SE_SELF_RELATIVE = 0x8000 } public const int SECURITY_DESCRIPTOR_REVISION = 1; [StructLayout(LayoutKind.Sequential)] public struct _SECURITY_DESCRIPTOR { byte Revision; byte Sbz1; SECURITY_DESCRIPTOR_CONTROL Control; IntPtr Owner; IntPtr Group; IntPtr Sacl; IntPtr Dacl; }; [DllImport("advapi32.dll", EntryPoint="GetSecurityDescriptorOwner", SetLastError=true)] public static extern bool _GetSecurityDescriptorOwner( IntPtr pSecurityDescriptor, out IntPtr owner, out bool lpbOwnerDefaulted ); public static IntPtr GetSecurityDescriptorOwner(IntPtr pSecurityDescriptor, out bool defaulted) { IntPtr retval; if (!_GetSecurityDescriptorOwner(pSecurityDescriptor, out retval, out defaulted)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } public static IntPtr GetSecurityDescriptorOwner(IntPtr pSecurityDescriptor) { bool _; return GetSecurityDescriptorOwner(pSecurityDescriptor, out _); } [DllImport("advapi32.dll", EntryPoint="GetSecurityDescriptorGroup", SetLastError=true)] public static extern bool _GetSecurityDescriptorGroup( IntPtr pSecurityDescriptor, out IntPtr owner, out bool lpbGroupDefaulted ); public static IntPtr GetSecurityDescriptorGroup(IntPtr pSecurityDescriptor, out bool defaulted) { IntPtr retval; if (!_GetSecurityDescriptorGroup(pSecurityDescriptor, out retval, out defaulted)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } public static IntPtr GetSecurityDescriptorGroup(IntPtr pSecurityDescriptor) { bool _; return GetSecurityDescriptorGroup(pSecurityDescriptor, out _); } [DllImport("advapi32.dll", EntryPoint="GetSecurityDescriptorDacl", SetLastError=true)] public static extern bool _GetSecurityDescriptorDacl( IntPtr pSecurityDescriptor, out bool lpbDaclPresent, out IntPtr pDacl, out bool lpbDaclDefaulted ); public static IntPtr GetSecurityDescriptorDacl(IntPtr pSecurityDescriptor, out bool defaulted) { IntPtr retval = IntPtr.Zero; bool present; if (!_GetSecurityDescriptorDacl(pSecurityDescriptor, out present, out retval, out defaulted)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } public static IntPtr GetSecurityDescriptorDacl(IntPtr pSecurityDescriptor) { bool _; return GetSecurityDescriptorDacl(pSecurityDescriptor, out _); } [DllImport("advapi32.dll", EntryPoint="GetSecurityDescriptorSacl", SetLastError=true)] public static extern bool _GetSecurityDescriptorSacl( IntPtr pSecurityDescriptor, out bool lpbSaclPresent, out IntPtr pSacl, out bool lpbSaclDefaulted ); public static IntPtr GetSecurityDescriptorSacl(IntPtr pSecurityDescriptor, out bool defaulted) { IntPtr retval = IntPtr.Zero; bool present; if (!_GetSecurityDescriptorSacl(pSecurityDescriptor, out present, out retval, out defaulted)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } public static IntPtr GetSecurityDescriptorSacl(IntPtr pSecurityDescriptor) { bool _; return GetSecurityDescriptorSacl(pSecurityDescriptor, out _); } [DllImport("advapi32.dll", EntryPoint="InitializeSecurityDescriptor", SetLastError=true)] public static extern bool _InitializeSecurityDescriptor(IntPtr pSecurityDescriptor, uint dwRevision); public static void InitializeSecurityDescriptor(IntPtr pSecurityDescriptor, uint dwRevision) { if (!_InitializeSecurityDescriptor(pSecurityDescriptor, dwRevision)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } } public class SecurityDescriptor: IDisposable { class DummyACL: IACL { public IEnumerator<IACE> GetEnumerator() { return null; } IEnumerator IEnumerable.GetEnumerator() { return null; } public int Count { get { return -1; } } public int Length { get { return 0; } } internal DummyACL() {} public IntPtr Render() { return IntPtr.Zero; } } public static readonly string DEFAULTED_SID = "DEFAULTED"; public static readonly IACL DEFAULTED_ACL = new DummyACL(); bool disposed; static readonly int descriptorSize = Marshal.SizeOf(typeof(_SECURITY_DESCRIPTOR)); IntPtr pSecurityDescriptor; bool shouldBeFreed; bool ownerDefaulted; IntPtr? pSidOwner; bool ownerSet; string owner; bool groupDefaulted; IntPtr? pSidGroup; bool groupSet; string group; bool saclDefaulted; IntPtr? pSacl; bool saclSet; IACL sacl; bool daclDefaulted; IntPtr? pDacl; bool daclSet; IACL dacl; void RenderOwner() { if (!ownerSet) { if (pSidOwner == null) { pSidOwner = GetSecurityDescriptorOwner(pSecurityDescriptor); } owner = pSidOwner != IntPtr.Zero ? ConvertSidToStringSid((IntPtr)pSidOwner): null; ownerSet = true; } } public string Owner { get { RenderOwner(); return owner; } set { if (value == DEFAULTED_SID) { OwnerDefaulted = true; return; } owner = value; pSidOwner = null; ownerSet = true; ownerDefaulted = false; ResetSecurityDescriptor(); } } public bool OwnerDefaulted { get { return ownerDefaulted; } set { if (ownerDefaulted != value) { ownerDefaulted = value; if (value) { owner = null; pSidOwner = null; ownerSet = false; ResetSecurityDescriptor(); } } } } public IntPtr? PSidOwner { get { PopulateSecurityDescriptor(); return pSidOwner; } } void RenderGroup() { if (!groupSet) { if (pSidGroup == null) { pSidGroup = GetSecurityDescriptorGroup(pSecurityDescriptor); } group = pSidGroup != IntPtr.Zero ? ConvertSidToStringSid((IntPtr)pSidGroup): null; groupSet = true; } } public string Group { get { RenderGroup(); return group; } set { if (value == DEFAULTED_SID) { GroupDefaulted = true; return; } group = value; pSidGroup = null; groupSet = true; ResetSecurityDescriptor(); } } public bool GroupDefaulted { get { return groupDefaulted; } set { if (groupDefaulted != value) { groupDefaulted = value; if (value) { group = null; pSidGroup = null; groupSet = false; ResetSecurityDescriptor(); } } } } public IntPtr? PSidGroup { get { PopulateSecurityDescriptor(); return pSidGroup; } } void RenderSacl() { if (!saclSet) { if (pSacl == null) { pSacl = GetSecurityDescriptorSacl(pSecurityDescriptor); } sacl = pSacl != IntPtr.Zero ? new ACLView((IntPtr)pSacl): null; saclSet = true; } } public IACL Sacl { get { RenderSacl(); return sacl; } set { if (value == DEFAULTED_ACL) { SaclDefaulted = true; return; } sacl = value; pSacl = null; saclSet = true; ResetSecurityDescriptor(); } } public bool SaclDefaulted { get { return saclDefaulted; } set { if (saclDefaulted != value) { saclDefaulted = value; if (value) { sacl = null; pSacl = null; saclSet = false; ResetSecurityDescriptor(); } } } } public IntPtr? PSacl { get { PopulateSecurityDescriptor(); return pSacl; } } void RenderDacl() { if (!daclSet) { if (pDacl == null) { pDacl = GetSecurityDescriptorSacl(pSecurityDescriptor); } dacl = pDacl != IntPtr.Zero ? new ACLView((IntPtr)pDacl): null; daclSet = true; } } public IACL Dacl { get { RenderDacl(); return dacl; } set { if (value == DEFAULTED_ACL) { DaclDefaulted = true; return; } dacl = value; pDacl = null; daclSet = true; ResetSecurityDescriptor(); } } public bool DaclDefaulted { get { return daclDefaulted; } set { if (daclDefaulted != value) { daclDefaulted = value; if (value) { dacl = null; pDacl = null; daclSet = false; ResetSecurityDescriptor(); } } } } public IntPtr? PDacl { get { PopulateSecurityDescriptor(); return pDacl; } } void PopulateSecurityDescriptor() { if (pSecurityDescriptor == IntPtr.Zero) { pSecurityDescriptor = Render(ref pSidOwner, ref pSidGroup, ref pSacl, ref pDacl); shouldBeFreed = true; } } public IntPtr Ptr { get { PopulateSecurityDescriptor(); return pSecurityDescriptor; } } private void FreeSecurityDescriptor() { SECURITY_DESCRIPTOR_CONTROL control = (SECURITY_DESCRIPTOR_CONTROL)(ushort)Marshal.ReadInt16(pSecurityDescriptor, 2); if ((control & SECURITY_DESCRIPTOR_CONTROL.SE_SELF_RELATIVE) == 0) { if (pSidOwner != null && pSidOwner != IntPtr.Zero) { Marshal.FreeHGlobal((IntPtr)pSidOwner); pSidOwner = null; } if (pSidGroup != null && pSidGroup != IntPtr.Zero) { Marshal.FreeHGlobal((IntPtr)pSidGroup); pSidGroup = null; } if (pSacl != null && pSacl != IntPtr.Zero) { Marshal.FreeHGlobal((IntPtr)pSacl); pSacl = null; } if (pDacl != null && pDacl != IntPtr.Zero) { Marshal.FreeHGlobal((IntPtr)pDacl); pDacl = null; } } if (shouldBeFreed && pSecurityDescriptor != IntPtr.Zero) { Marshal.FreeHGlobal(pSecurityDescriptor); pSecurityDescriptor = IntPtr.Zero; } } private void ResetSecurityDescriptor() { RenderOwner(); RenderGroup(); RenderSacl(); RenderDacl(); FreeSecurityDescriptor(); } public IntPtr Render(ref IntPtr? pSidOwner, ref IntPtr? pSidGroup, ref IntPtr? pSacl, ref IntPtr? pDacl) { IntPtr ptr = Marshal.AllocHGlobal(descriptorSize); InitializeSecurityDescriptor(ptr, SECURITY_DESCRIPTOR_REVISION); SECURITY_DESCRIPTOR_CONTROL flags = 0; try { if (Owner != null) { pSidOwner = ConvertStringSidToSid(Owner); } if (ownerDefaulted) { flags |= SECURITY_DESCRIPTOR_CONTROL.SE_OWNER_DEFAULTED; } Marshal.WriteIntPtr(ptr + 4 + IntPtr.Size * 0, pSidOwner.GetValueOrDefault(IntPtr.Zero)); if (Group != null) { pSidGroup = ConvertStringSidToSid(Group); } if (groupDefaulted) { flags |= SECURITY_DESCRIPTOR_CONTROL.SE_GROUP_DEFAULTED; } Marshal.WriteIntPtr(ptr + 4 + IntPtr.Size * 1, pSidGroup.GetValueOrDefault(IntPtr.Zero)); if (saclDefaulted) { flags |= SECURITY_DESCRIPTOR_CONTROL.SE_SACL_DEFAULTED; } if (sacl != null) { pSacl = sacl.Render(); flags |= SECURITY_DESCRIPTOR_CONTROL.SE_SACL_PRESENT; } else { flags |= SECURITY_DESCRIPTOR_CONTROL.SE_SACL_PROTECTED; } Marshal.WriteIntPtr(ptr + 4 + IntPtr.Size * 2, pSacl.GetValueOrDefault(IntPtr.Zero)); if (dacl != null) { pDacl = dacl.Render(); flags |= SECURITY_DESCRIPTOR_CONTROL.SE_DACL_PRESENT; } else { flags |= SECURITY_DESCRIPTOR_CONTROL.SE_DACL_PROTECTED; } Marshal.WriteIntPtr(ptr + 4 + IntPtr.Size * 3, pDacl.GetValueOrDefault(IntPtr.Zero)); } catch { if (pSidOwner != null && pSidOwner != IntPtr.Zero) { Marshal.FreeHGlobal((IntPtr)pSidOwner); } if (pSidGroup != null && pSidGroup != IntPtr.Zero) { Marshal.FreeHGlobal((IntPtr)pSidGroup); } if (pSacl != null && pSacl != IntPtr.Zero) { Marshal.FreeHGlobal((IntPtr)pSacl); } if (pDacl != null && pDacl != IntPtr.Zero) { Marshal.FreeHGlobal((IntPtr)pDacl); } throw; } return ptr; } public void Dispose() { if (disposed) { return; } disposed = true; FreeSecurityDescriptor(); } public SecurityDescriptor( IntPtr pSecurityDescriptor, bool shouldBeFreed = false, IntPtr? pSidOwner = null, IntPtr? pSidGroup = null, IntPtr? pSacl = null, IntPtr? pDacl = null ) { this.pSecurityDescriptor = pSecurityDescriptor; SECURITY_DESCRIPTOR_CONTROL control = (SECURITY_DESCRIPTOR_CONTROL)(ushort)Marshal.ReadInt16(pSecurityDescriptor, 2); this.shouldBeFreed = shouldBeFreed; this.pSidOwner = pSidOwner; this.pSidGroup = pSidGroup; this.pSacl = pSacl; this.pDacl = pDacl; ownerDefaulted = (control & SECURITY_DESCRIPTOR_CONTROL.SE_OWNER_DEFAULTED) != 0; groupDefaulted = (control & SECURITY_DESCRIPTOR_CONTROL.SE_GROUP_DEFAULTED) != 0; saclDefaulted = (control & SECURITY_DESCRIPTOR_CONTROL.SE_SACL_DEFAULTED) != 0; daclDefaulted = (control & SECURITY_DESCRIPTOR_CONTROL.SE_DACL_DEFAULTED) != 0; } public SecurityDescriptor( string owner, string group, IACL sacl, IACL dacl ) { Owner = owner; Group = group; Sacl = sacl; Dacl = dacl; } } [DllImport("advapi32.dll", EntryPoint="GetSecurityInfo", SetLastError=true)] public static extern uint _GetSecurityInfo( IntPtr handle, SE_OBJECT_TYPE objectType, SECURITY_INFORMATION securityInfo, out IntPtr pSidOwner, out IntPtr pSidGroup, out IntPtr pDacl, // beware the order! this is opposite of SECURITY_DESCRIPTOR out IntPtr pSacl, // beware the order! this is opposite of SECURITY_DESCRIPTOR out IntPtr pSecurityDescriptor ); public static SecurityDescriptor GetSecurityInfo(IntPtr handle, SE_OBJECT_TYPE objectType, SECURITY_INFORMATION securityInfo) { IntPtr sidOwner, sidGroup, dacl, sacl, securityDescriptor; uint err = _GetSecurityInfo( handle, objectType, securityInfo, out sidOwner, out sidGroup, out dacl, out sacl, out securityDescriptor ); if (0 != err) { throw new Win32APIException((int)err); } return new SecurityDescriptor( securityDescriptor, true, (securityInfo & SECURITY_INFORMATION.OWNER) != 0 ? (IntPtr?)sidOwner: (IntPtr?)null, (securityInfo & SECURITY_INFORMATION.GROUP) != 0 ? (IntPtr?)sidGroup: (IntPtr?)null, (securityInfo & SECURITY_INFORMATION.SACL) != 0 ? (IntPtr?)sacl: (IntPtr?)null, (securityInfo & SECURITY_INFORMATION.DACL) != 0 ? (IntPtr?)dacl: (IntPtr?)null ); } [DllImport("advapi32.dll", EntryPoint="SetSecurityInfo", SetLastError=true)] public static extern uint _SetSecurityInfo( IntPtr handle, SE_OBJECT_TYPE objectType, SECURITY_INFORMATION securityInfo, IntPtr pSidOwner, IntPtr pSidGroup, IntPtr pDacl, // beware the order! this is opposite of SECURITY_DESCRIPTOR IntPtr pSacl // beware the order! this is opposite of SECURITY_DESCRIPTOR ); public static void SetSecurityInfo(IntPtr handle, SE_OBJECT_TYPE objectType, SECURITY_INFORMATION securityInfo, SecurityDescriptor desc) { uint err = _SetSecurityInfo( handle, objectType, securityInfo, desc.PSidOwner.GetValueOrDefault(IntPtr.Zero), desc.PSidGroup.GetValueOrDefault(IntPtr.Zero), desc.PDacl.GetValueOrDefault(IntPtr.Zero), desc.PSacl.GetValueOrDefault(IntPtr.Zero) ); if (0 != err) { throw new Win32APIException((int)err); } } public enum TOKEN_INFORMATION_CLASS { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, TokenIsAppContainer, TokenCapabilities, TokenAppContainerSid, TokenAppContainerNumber, TokenUserClaimAttributes, TokenDeviceClaimAttributes, TokenRestrictedUserClaimAttributes, TokenRestrictedDeviceClaimAttributes, TokenDeviceGroups, TokenRestrictedDeviceGroups, TokenSecurityAttributes, TokenIsRestricted, MaxTokenInfoClass } [DllImport("advapi32.dll", EntryPoint="GetTokenInformation", SetLastError=true)] public static extern bool _GetTokenInformation( IntPtr tokenHandle, TOKEN_INFORMATION_CLASS tokenInformationClass, IntPtr tokenInformation, uint tokenInformationLength, out uint returnLength ); public static void GetTokenInformation( IntPtr tokenHandle, TOKEN_INFORMATION_CLASS tokenInformationClass, IntPtr tokenInformation, uint tokenInformationLength, out uint returnLength ) { if (!_GetTokenInformation( tokenHandle, tokenInformationClass, tokenInformation, tokenInformationLength, out returnLength)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } } public static IntPtr GetTokenInformation( IntPtr tokenHandle, TOKEN_INFORMATION_CLASS tokenInformationClass ) { uint returnLength = 0; _GetTokenInformation(tokenHandle, tokenInformationClass, IntPtr.Zero, 0, out returnLength); IntPtr buf = Marshal.AllocHGlobal((int)returnLength); try { GetTokenInformation(tokenHandle, tokenInformationClass, buf, returnLength, out returnLength); } catch { Marshal.FreeHGlobal(buf); throw; } return buf; } public struct _SID_AND_ATTRIBUTES { IntPtr Sid; uint Attributes; } public static string GetTokenUser(IntPtr tokenHandle, out uint attributes) { IntPtr buf = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenUser); try { IntPtr pSid = Marshal.ReadIntPtr(buf, 0); attributes = (uint)Marshal.ReadInt32(buf, IntPtr.Size); return ConvertSidToStringSid(pSid); } finally { Marshal.FreeHGlobal(buf); } } [DllImport("advapi32.dll", EntryPoint="OpenProcessToken", SetLastError=true)] public static extern bool _OpenProcessToken( IntPtr processHandle, ACCESS_MASK desiredAccess, out IntPtr tokenHandle ); public static IntPtr OpenProcessToken(IntPtr processHandle, ACCESS_MASK desiredAccess) { IntPtr retval; if (!_OpenProcessToken(processHandle, desiredAccess, out retval)) { throw new Win32APIException(Marshal.GetLastWin32Error()); } return retval; } } public sealed class PSAPI { [DllImport("psapi.dll", EntryPoint="GetProcessImageFileNameW", SetLastError=true)] public static extern uint _GetProcessImageFileName(IntPtr hProcess, IntPtr lpImageFileName, uint nSize); public static string GetProcessImageFileName(IntPtr hProcess) { IntPtr buf = Marshal.AllocHGlobal(260); try { uint len = _GetProcessImageFileName(hProcess, buf, 260); return Marshal.PtrToStringUni(buf, (int)len); } finally { Marshal.FreeHGlobal(buf); } } } } // vim: sts=4 ts=4 sw=4 et
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MGTK.Services; using MGTK.Messaging; using MGTK.Interfaces.Services; namespace MGTK.Controls { public class Form : Control { public FormWindowState WindowState = FormWindowState.Normal; protected TitleBar titleBar; protected WindowSizeBar windowSizeBar; private bool resizable = true; private bool useTitleBar = true; public bool UseTitleBar { get { return useTitleBar; } set { if (value != useTitleBar) { useTitleBar = value; SetTitleBar(); } } } public bool Resizable { get { return resizable; } set { if (resizable != value) { resizable = value; SetWindowSizeBar(); } } } public int EdgeHeight { get { return windowSizeBar.EdgeHeight; } } public bool MaximizeWindowButtonVisible { get { return titleBar.MaximizeWindowButtonVisible; } set { titleBar.MaximizeWindowButtonVisible = value; } } public bool MinimizeWindowButtonVisible { get { return titleBar.MinimizeWindowButtonVisible; } set { titleBar.MinimizeWindowButtonVisible = value; } } public bool CloseWindowButtonVisible { get { return titleBar.CloseWindowButtonVisible; } set { titleBar.CloseWindowButtonVisible = value; } } public bool WindowOptionsButtonVisible { get { return titleBar.WindowOptionsButtonVisible; } set { titleBar.WindowOptionsButtonVisible = value; } } public event EventHandler OnClose; public Form(IWindowManager windowmanager) { titleBar = new TitleBar(this); titleBar.ForeColor = Color.White; windowSizeBar = new WindowSizeBar(this); WindowManager = windowmanager; this.TextChanged += new EventHandler(Form_TextChanged); } void Form_TextChanged(object sender, EventArgs e) { titleBar.Text = Text; } public override bool ReceiveMessage(MessageEnum message, object msgTag) { if (message == MessageEnum.Focus) if (WindowManager != null) WindowManager.BringToFront(this); return base.ReceiveMessage(message, msgTag); } void RaiseOnClose() { if (OnClose != null) OnClose(this, new EventArgs()); } protected void SetTitleBar() { if (UseTitleBar) { if (!Controls.Contains(titleBar)) { TransposeY(titleBar.TitleBarHeight); titleBar.OnCloseButtonClick += (sender, e) => RaiseOnClose(); Controls.Add(titleBar); } } else { if (Controls.Contains(titleBar)) { TransposeY(-titleBar.TitleBarHeight); Controls.Remove(titleBar); } } } protected void SetWindowSizeBar() { if (Resizable) { if (!Controls.Contains(windowSizeBar)) { Height += windowSizeBar.EdgeHeight; MinimumHeight += windowSizeBar.EdgeHeight; Controls.Add(windowSizeBar); } } else { if (Controls.Contains(windowSizeBar)) { Height -= windowSizeBar.EdgeHeight; MinimumHeight -= windowSizeBar.EdgeHeight; Controls.Remove(windowSizeBar); } } } public override void InitControl() { SetTitleBar(); SetWindowSizeBar(); if (Controls != null) foreach (Control ctrl in Controls) ctrl.InitControl(); base.InitControl(); } private void TransposeY(int addedY) { foreach (Control control in Controls) control.Y += addedY; Height += addedY; MinimumHeight += addedY; } public override void Draw() { DrawingService.DrawRectangle(SpriteBatchProvider, Theme.Dot, Color.Black, X, Y, Width, 1, Z - 0.002f); DrawingService.DrawRectangle(SpriteBatchProvider, Theme.Dot, Color.Black, X, Y + Height - 1, Width, 1, Z - 0.002f); DrawingService.DrawRectangle(SpriteBatchProvider, Theme.Dot, Color.Black, X, Y, 1, Height, Z - 0.002f); DrawingService.DrawRectangle(SpriteBatchProvider, Theme.Dot, Color.Black, X + Width - 1, Y, 1, Height, Z - 0.002f); base.Draw(); } public void Close() { RaiseOnClose(); } } public enum FormBorderStyle { None = 0, FixedSingle = 1 } public enum FormWindowState { Normal = 0, Maximized = 1, Minimized = 2 } }
// // Copyright 2011-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.IO; using System.Threading.Tasks; #if __UNIFIED__ using CoreGraphics; using Foundation; using UIKit; using NSAction = System.Action; #else using MonoTouch.AssetsLibrary; using MonoTouch.Foundation; using MonoTouch.UIKit; using CGRect = global::System.Drawing.RectangleF; using nfloat = global::System.Single; #endif namespace Xamarin.Media { internal class MediaPickerDelegate : UIImagePickerControllerDelegate { private readonly NSObject observer; private readonly StoreCameraMediaOptions options; private readonly UIImagePickerControllerSourceType source; private readonly TaskCompletionSource<MediaFile> tcs = new TaskCompletionSource<MediaFile>(); private readonly UIViewController viewController; private UIDeviceOrientation? orientation; internal MediaPickerDelegate( UIViewController viewController, UIImagePickerControllerSourceType sourceType, StoreCameraMediaOptions options ) { this.viewController = viewController; source = sourceType; this.options = options ?? new StoreCameraMediaOptions(); if(viewController != null) { UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications(); observer = NSNotificationCenter.DefaultCenter.AddObserver( UIDevice.OrientationDidChangeNotification, DidRotate ); } } public UIPopoverController Popover { get; set; } public Task<MediaFile> Task { get { return tcs.Task; } } public UIView View { get { return viewController.View; } } private Boolean IsCaptured { get { return source == UIImagePickerControllerSourceType.Camera; } } public override void Canceled( UIImagePickerController picker ) { Dismiss( picker, () => tcs.TrySetCanceled() ); } public void DisplayPopover( Boolean hideFirst = false ) { if(Popover == null) { return; } var swidth = UIScreen.MainScreen.Bounds.Width; var sheight = UIScreen.MainScreen.Bounds.Height; nfloat width = 400; nfloat height = 300; if(orientation == null) { if(IsValidInterfaceOrientation( UIDevice.CurrentDevice.Orientation )) { orientation = UIDevice.CurrentDevice.Orientation; } else { orientation = GetDeviceOrientation( viewController.InterfaceOrientation ); } } nfloat x, y; if(orientation == UIDeviceOrientation.LandscapeLeft || orientation == UIDeviceOrientation.LandscapeRight) { y = (swidth / 2) - (height / 2); x = (sheight / 2) - (width / 2); } else { x = (swidth / 2) - (width / 2); y = (sheight / 2) - (height / 2); } if(hideFirst && Popover.PopoverVisible) { Popover.Dismiss( animated: false ); } Popover.PresentFromRect( new CGRect( x, y, width, height ), View, 0, animated: true ); } public override void FinishedPickingMedia( UIImagePickerController picker, NSDictionary info ) { MediaFile mediaFile; switch((NSString)info[UIImagePickerController.MediaType]) { case MediaPicker.TypeImage: mediaFile = GetPictureMediaFile( info ); break; case MediaPicker.TypeMovie: mediaFile = GetMovieMediaFile( info ); break; default: throw new NotSupportedException(); } Dismiss( picker, () => tcs.TrySetResult( mediaFile ) ); } private void DidRotate( NSNotification notice ) { UIDevice device = (UIDevice)notice.Object; if(!IsValidInterfaceOrientation( device.Orientation ) || Popover == null) { return; } if(orientation.HasValue && IsSameOrientationKind( orientation.Value, device.Orientation )) { return; } if(UIDevice.CurrentDevice.CheckSystemVersion( 6, 0 )) { if(!GetShouldRotate6( device.Orientation )) { return; } } else if(!GetShouldRotate( device.Orientation )) { return; } UIDeviceOrientation? co = orientation; orientation = device.Orientation; if(co == null) { return; } DisplayPopover( hideFirst: true ); } private void Dismiss( UIImagePickerController picker, NSAction onDismiss ) { if(viewController == null) { onDismiss(); } else { NSNotificationCenter.DefaultCenter.RemoveObserver( observer ); UIDevice.CurrentDevice.EndGeneratingDeviceOrientationNotifications(); observer.Dispose(); if(Popover != null) { Popover.Dismiss( animated: true ); Popover.Dispose(); Popover = null; onDismiss(); } else { picker.DismissViewController( true, onDismiss ); picker.Dispose(); } } } private MediaFile GetMovieMediaFile( NSDictionary info ) { NSUrl url = (NSUrl)info[UIImagePickerController.MediaURL]; String path = GetOutputPath( MediaPicker.TypeMovie, options.Directory ?? ((IsCaptured) ? String.Empty : "temp"), options.Name ?? Path.GetFileName( url.Path ) ); File.Move( url.Path, path ); Action<Boolean> dispose = null; if(source != UIImagePickerControllerSourceType.Camera) { dispose = d => File.Delete( path ); } return new MediaFile( path, () => File.OpenRead( path ), dispose ); } private MediaFile GetPictureMediaFile( NSDictionary info ) { var image = (UIImage)info[UIImagePickerController.EditedImage]; if(image == null) { image = (UIImage)info[UIImagePickerController.OriginalImage]; } String path = GetOutputPath( MediaPicker.TypeImage, options.Directory ?? ((IsCaptured) ? String.Empty : "temp"), options.Name ); using(FileStream fs = File.OpenWrite( path )) using(Stream s = new NSDataStream( image.AsJPEG() )) { s.CopyTo( fs ); fs.Flush(); } Action<Boolean> dispose = null; if(source != UIImagePickerControllerSourceType.Camera) { dispose = d => File.Delete( path ); } return new MediaFile( path, () => File.OpenRead( path ), dispose ); } private Boolean GetShouldRotate( UIDeviceOrientation orientation ) { UIInterfaceOrientation iorientation = UIInterfaceOrientation.Portrait; switch(orientation) { case UIDeviceOrientation.LandscapeLeft: iorientation = UIInterfaceOrientation.LandscapeLeft; break; case UIDeviceOrientation.LandscapeRight: iorientation = UIInterfaceOrientation.LandscapeRight; break; case UIDeviceOrientation.Portrait: iorientation = UIInterfaceOrientation.Portrait; break; case UIDeviceOrientation.PortraitUpsideDown: iorientation = UIInterfaceOrientation.PortraitUpsideDown; break; default: return false; } return viewController.ShouldAutorotateToInterfaceOrientation( iorientation ); } private Boolean GetShouldRotate6( UIDeviceOrientation orientation ) { if(!viewController.ShouldAutorotate()) { return false; } UIInterfaceOrientationMask mask = UIInterfaceOrientationMask.Portrait; switch(orientation) { case UIDeviceOrientation.LandscapeLeft: mask = UIInterfaceOrientationMask.LandscapeLeft; break; case UIDeviceOrientation.LandscapeRight: mask = UIInterfaceOrientationMask.LandscapeRight; break; case UIDeviceOrientation.Portrait: mask = UIInterfaceOrientationMask.Portrait; break; case UIDeviceOrientation.PortraitUpsideDown: mask = UIInterfaceOrientationMask.PortraitUpsideDown; break; default: return false; } return viewController.GetSupportedInterfaceOrientations().HasFlag( mask ); } private static UIDeviceOrientation GetDeviceOrientation( UIInterfaceOrientation self ) { switch(self) { case UIInterfaceOrientation.LandscapeLeft: return UIDeviceOrientation.LandscapeLeft; case UIInterfaceOrientation.LandscapeRight: return UIDeviceOrientation.LandscapeRight; case UIInterfaceOrientation.Portrait: return UIDeviceOrientation.Portrait; case UIInterfaceOrientation.PortraitUpsideDown: return UIDeviceOrientation.PortraitUpsideDown; default: throw new InvalidOperationException(); } } private static String GetOutputPath( String type, String path, String name ) { path = Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.Personal ), path ); Directory.CreateDirectory( path ); if(String.IsNullOrWhiteSpace( name )) { String timestamp = DateTime.Now.ToString( "yyyMMdd_HHmmss" ); if(type == MediaPicker.TypeImage) { name = "IMG_" + timestamp + ".jpg"; } else { name = "VID_" + timestamp + ".mp4"; } } return Path.Combine( path, GetUniquePath( type, path, name ) ); } private static String GetUniquePath( String type, String path, String name ) { Boolean isPhoto = (type == MediaPicker.TypeImage); String ext = Path.GetExtension( name ); if(ext == String.Empty) { ext = ((isPhoto) ? ".jpg" : ".mp4"); } name = Path.GetFileNameWithoutExtension( name ); String nname = name + ext; Int32 i = 1; while(File.Exists( Path.Combine( path, nname ) )) { nname = name + "_" + (i++) + ext; } return Path.Combine( path, nname ); } private static Boolean IsSameOrientationKind( UIDeviceOrientation o1, UIDeviceOrientation o2 ) { if(o1 == UIDeviceOrientation.FaceDown || o1 == UIDeviceOrientation.FaceUp) { return (o2 == UIDeviceOrientation.FaceDown || o2 == UIDeviceOrientation.FaceUp); } if(o1 == UIDeviceOrientation.LandscapeLeft || o1 == UIDeviceOrientation.LandscapeRight) { return (o2 == UIDeviceOrientation.LandscapeLeft || o2 == UIDeviceOrientation.LandscapeRight); } if(o1 == UIDeviceOrientation.Portrait || o1 == UIDeviceOrientation.PortraitUpsideDown) { return (o2 == UIDeviceOrientation.Portrait || o2 == UIDeviceOrientation.PortraitUpsideDown); } return false; } private static Boolean IsValidInterfaceOrientation( UIDeviceOrientation self ) { return (self != UIDeviceOrientation.FaceUp && self != UIDeviceOrientation.FaceDown && self != UIDeviceOrientation.Unknown); } } }
using UnityEngine; using System.Collections; using System; public class Libonati : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } //Math static public bool pointInsideRect(Rect rect, Vector3 point){ return point.x >= rect.xMin && point.x <= rect.xMax && point.y <= rect.yMin && point.y >= rect.yMax; } //Level managment static public void reloadLevel (){ Application.LoadLevel (Application.loadedLevel); } static public void loadNextLevel(){ int levelId = Application.loadedLevel; levelId ++; if(levelId >= Application.levelCount){ levelId = 0; } Application.LoadLevel(levelId); } static public void loadPrevLevel(){ int levelId = Application.loadedLevel; levelId --; if(levelId < 0){ levelId = Application.levelCount-1; } Application.LoadLevel(levelId); } public static float ConvertRange(float originalStart, float originalEnd, float newStart, float newEnd, float value){ float scale = (float)(newEnd - newStart) / (originalEnd - originalStart); return (newStart + ((value - originalStart) * scale)); } //Text Modification static public string padInt(int value, int numberOfDigits){ return value.ToString ("D" + numberOfDigits.ToString ()); } static public string clockString(int totalSeconds){ int minutes = (int)Mathf.Floor(totalSeconds/60); int seconds = (int)Mathf.Round(totalSeconds - minutes*60); string clock = minutes+":"+Libonati.padInt(seconds,2); return clock; } static public char[] generateTextCode(int codeLength){ return generateCode(codeLength,"ABCDEFGHIJKLMNOPQRSTUVWXYZ"); } static public char[] generateNumberCode(int codeLength){ return generateCode(codeLength,"1234567890"); } static public char[] generateCode(int codeLength, string possibleCharacters){ char[] codeChar = new char[codeLength]; for(int i=0; i<codeLength; i++){ codeChar[i] = possibleCharacters[(int)UnityEngine.Random.Range(0,possibleCharacters.Length)]; } return codeChar; } //Game Object Modification static public void destroyAllChildren(GameObject parent){ foreach (Transform child in parent.transform) Destroy(child.gameObject); } public static Vector2 getPositionFromLinearArray(int i, int width){ return new Vector2(i%width, Mathf.Floor(i/width)); } static public void showAllSprites(GameObject obj){ toggleAllSpriteVisibility (obj, true); } static public void hideAllSprites(GameObject obj){ toggleAllSpriteVisibility (obj, false); } static public void toggleAllSpriteVisibility(GameObject obj, bool show){ foreach(SpriteRenderer ren in obj.GetComponentsInChildren<SpriteRenderer>()){ ren.enabled = show; } } static public void showAllMesh(GameObject obj){ toggleAllMeshVisibility (obj, true); } static public void hideAllMesh(GameObject obj){ toggleAllMeshVisibility (obj, false); } static public void toggleAllMeshVisibility(GameObject obj, bool show){ foreach(MeshRenderer ren in obj.GetComponentsInChildren<MeshRenderer>()){ ren.enabled = show; } } static public void hideAll(GameObject obj){ if (obj != null) { hideAllMesh (obj); hideAllSprites (obj); } } static public void showAll(GameObject obj){ if (obj != null) { showAllMesh (obj); showAllSprites (obj); } } static public object getRandomEnumValue(Type enumType){ Array values = Enum.GetValues(enumType); return values.GetValue((int)UnityEngine.Random.Range(0,values.Length)); } static public void disable2DColliders(GameObject obj){ foreach(Collider2D col in obj.GetComponentsInChildren<Collider2D>()){ col.enabled = false; } } static public void enable2DColliders(GameObject obj){ foreach(Collider2D col in obj.GetComponentsInChildren<Collider2D>()){ col.enabled = true; } } static public void disable3DColliders(GameObject obj){ foreach(Collider col in obj.GetComponentsInChildren<Collider>()){ col.enabled = false; } } static public void enable3DColliders(GameObject obj){ foreach(Collider col in obj.GetComponentsInChildren<Collider>()){ col.enabled = true; } } static public void disableColliders(GameObject obj){ disable2DColliders (obj); disable3DColliders (obj); } static public void enableColliders(GameObject obj){ enable2DColliders(obj); enable3DColliders(obj); } //Grid Based public static int tileToLinear(int x, int y, int stride){ return y * stride + x; } public static Vector2 linearToTile(int i, int stride){ return new Vector2 (i % stride, Mathf.Floor(i/stride)); } public static float round(float value, int digits) { float mult = Mathf.Pow(10.0f, (float)digits); return Mathf.Round(value * mult) / mult; } //Color Manipulation public static string colorToString(Color color){ return color.r + "," + color.g + "," + color.b + "," + color.a; } public static Color stringToColor(string colorString){ try{ string[] colors = colorString.Split (','); return new Color (float.Parse(colors [0]), float.Parse(colors [1]), float.Parse(colors [2]), float.Parse(colors [3])); }catch{ return Color.white; } } // Note that Color32 and Color implictly convert to each other. You may pass a Color object to this method without first casting it. public static string colorToHex(Color32 color) { string hex = color.r.ToString("X2") + color.g.ToString("X2") + color.b.ToString("X2"); return hex; } public static Color hexToColor(string hex) { hex = hex.Replace ("0x", "");//in case the string is formatted 0xFFFFFF hex = hex.Replace ("#", "");//in case the string is formatted #FFFFFF byte a = 255;//assume fully visible unless specified in hex byte r = byte.Parse(hex.Substring(0,2), System.Globalization.NumberStyles.HexNumber); byte g = byte.Parse(hex.Substring(2,2), System.Globalization.NumberStyles.HexNumber); byte b = byte.Parse(hex.Substring(4,2), System.Globalization.NumberStyles.HexNumber); //Only use alpha if the string has enough characters if(hex.Length == 8){ a = byte.Parse(hex.Substring(4,2), System.Globalization.NumberStyles.HexNumber); } return new Color32(r,g,b,a); } public static float clampAngle (float angle, float min, float max) { angle = angle % 360; if ((angle >= -360F) && (angle <= 360F)) { if (angle < -360F) { angle += 360F; } if (angle > 360F) { angle -= 360F; } } return Mathf.Clamp (angle, min, max); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Buffers; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading; namespace System.Net.Sockets { internal static class SocketPal { public const bool SupportsMultipleConnectAttempts = true; private static void MicrosecondsToTimeValue(long microseconds, ref Interop.Winsock.TimeValue socketTime) { const int microcnv = 1000000; socketTime.Seconds = (int)(microseconds / microcnv); socketTime.Microseconds = (int)(microseconds % microcnv); } public static void Initialize() { // Ensure that WSAStartup has been called once per process. // The System.Net.NameResolution contract is responsible for the initialization. Dns.GetHostName(); } public static SocketError GetLastSocketError() { int win32Error = Marshal.GetLastWin32Error(); Debug.Assert(win32Error != 0, "Expected non-0 error"); return (SocketError)win32Error; } public static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeSocketHandle socket) { socket = SafeSocketHandle.CreateWSASocket(addressFamily, socketType, protocolType); return socket.IsInvalid ? GetLastSocketError() : SocketError.Success; } public static SocketError SetBlocking(SafeSocketHandle handle, bool shouldBlock, out bool willBlock) { int intBlocking = shouldBlock ? 0 : -1; SocketError errorCode; errorCode = Interop.Winsock.ioctlsocket( handle, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref intBlocking); if (errorCode == SocketError.SocketError) { errorCode = GetLastSocketError(); } willBlock = intBlocking == 0; return errorCode; } public static SocketError GetSockName(SafeSocketHandle handle, byte[] buffer, ref int nameLen) { SocketError errorCode = Interop.Winsock.getsockname(handle, buffer, ref nameLen); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError GetAvailable(SafeSocketHandle handle, out int available) { int value = 0; SocketError errorCode = Interop.Winsock.ioctlsocket( handle, Interop.Winsock.IoctlSocketConstants.FIONREAD, ref value); available = value; return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError GetPeerName(SafeSocketHandle handle, byte[] buffer, ref int nameLen) { SocketError errorCode = Interop.Winsock.getpeername(handle, buffer, ref nameLen); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError Bind(SafeSocketHandle handle, ProtocolType socketProtocolType, byte[] buffer, int nameLen) { SocketError errorCode = Interop.Winsock.bind(handle, buffer, nameLen); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError Listen(SafeSocketHandle handle, int backlog) { SocketError errorCode = Interop.Winsock.listen(handle, backlog); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError Accept(SafeSocketHandle handle, byte[] buffer, ref int nameLen, out SafeSocketHandle socket) { socket = SafeSocketHandle.Accept(handle, buffer, ref nameLen); return socket.IsInvalid ? GetLastSocketError() : SocketError.Success; } public static SocketError Connect(SafeSocketHandle handle, byte[] peerAddress, int peerAddressLen) { SocketError errorCode = Interop.Winsock.WSAConnect( handle, peerAddress, peerAddressLen, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError Send(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred) { const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately) int count = buffers.Count; bool useStack = count <= StackThreshold; WSABuffer[] leasedWSA = null; GCHandle[] leasedGC = null; Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0]; Span<GCHandle> objectsToPin = stackalloc GCHandle[0]; if (useStack) { WSABuffers = stackalloc WSABuffer[StackThreshold]; objectsToPin = stackalloc GCHandle[StackThreshold]; } else { WSABuffers = leasedWSA = ArrayPool<WSABuffer>.Shared.Rent(count); objectsToPin = leasedGC = ArrayPool<GCHandle>.Shared.Rent(count); } objectsToPin = objectsToPin.Slice(0, count); objectsToPin.Clear(); // note: touched in finally try { for (int i = 0; i < count; ++i) { ArraySegment<byte> buffer = buffers[i]; RangeValidationHelpers.ValidateSegment(buffer); objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned); WSABuffers[i].Length = buffer.Count; WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset); } unsafe { SocketError errorCode = Interop.Winsock.WSASend( handle, WSABuffers, count, out bytesTransferred, socketFlags, null, IntPtr.Zero); if (errorCode == SocketError.SocketError) { errorCode = GetLastSocketError(); } return errorCode; } } finally { for (int i = 0; i < count; ++i) { if (objectsToPin[i].IsAllocated) { objectsToPin[i].Free(); } } if (!useStack) { ArrayPool<WSABuffer>.Shared.Return(leasedWSA); ArrayPool<GCHandle>.Shared.Return(leasedGC); } } } public static unsafe SocketError Send(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) => Send(handle, new ReadOnlySpan<byte>(buffer, offset, size), socketFlags, out bytesTransferred); public static unsafe SocketError Send(SafeSocketHandle handle, ReadOnlySpan<byte> buffer, SocketFlags socketFlags, out int bytesTransferred) { int bytesSent; fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer)) { bytesSent = Interop.Winsock.send(handle, bufferPtr, buffer.Length, socketFlags); } if (bytesSent == (int)SocketError.SocketError) { bytesTransferred = 0; return GetLastSocketError(); } bytesTransferred = bytesSent; return SocketError.Success; } public static unsafe SocketError SendFile(SafeSocketHandle handle, SafeFileHandle fileHandle, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags) { fixed (byte* prePinnedBuffer = preBuffer) fixed (byte* postPinnedBuffer = postBuffer) { bool success = TransmitFileHelper(handle, fileHandle, null, preBuffer, postBuffer, flags); return (success ? SocketError.Success : SocketPal.GetLastSocketError()); } } public static unsafe SocketError SendTo(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] peerAddress, int peerAddressSize, out int bytesTransferred) { int bytesSent; if (buffer.Length == 0) { bytesSent = Interop.Winsock.sendto( handle, null, 0, socketFlags, peerAddress, peerAddressSize); } else { fixed (byte* pinnedBuffer = &buffer[0]) { bytesSent = Interop.Winsock.sendto( handle, pinnedBuffer + offset, size, socketFlags, peerAddress, peerAddressSize); } } if (bytesSent == (int)SocketError.SocketError) { bytesTransferred = 0; return GetLastSocketError(); } bytesTransferred = bytesSent; return SocketError.Success; } public static SocketError Receive(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, ref SocketFlags socketFlags, out int bytesTransferred) { const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately) int count = buffers.Count; bool useStack = count <= StackThreshold; WSABuffer[] leasedWSA = null; GCHandle[] leasedGC = null; Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0]; Span<GCHandle> objectsToPin = stackalloc GCHandle[0]; if (useStack) { WSABuffers = stackalloc WSABuffer[StackThreshold]; objectsToPin = stackalloc GCHandle[StackThreshold]; } else { WSABuffers = leasedWSA = ArrayPool<WSABuffer>.Shared.Rent(count); objectsToPin = leasedGC = ArrayPool<GCHandle>.Shared.Rent(count); } objectsToPin = objectsToPin.Slice(0, count); objectsToPin.Clear(); // note: touched in finally try { for (int i = 0; i < count; ++i) { ArraySegment<byte> buffer = buffers[i]; RangeValidationHelpers.ValidateSegment(buffer); objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned); WSABuffers[i].Length = buffer.Count; WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset); } unsafe { SocketError errorCode = Interop.Winsock.WSARecv( handle, WSABuffers, count, out bytesTransferred, ref socketFlags, null, IntPtr.Zero); if (errorCode == SocketError.SocketError) { errorCode = GetLastSocketError(); } return errorCode; } } finally { for (int i = 0; i < count; ++i) { if (objectsToPin[i].IsAllocated) { objectsToPin[i].Free(); } } if (!useStack) { ArrayPool<WSABuffer>.Shared.Return(leasedWSA); ArrayPool<GCHandle>.Shared.Return(leasedGC); } } } public static unsafe SocketError Receive(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) => Receive(handle, new Span<byte>(buffer, offset, size), socketFlags, out bytesTransferred); public static unsafe SocketError Receive(SafeSocketHandle handle, Span<byte> buffer, SocketFlags socketFlags, out int bytesTransferred) { int bytesReceived; fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer)) { bytesReceived = Interop.Winsock.recv(handle, bufferPtr, buffer.Length, socketFlags); } if (bytesReceived == (int)SocketError.SocketError) { bytesTransferred = 0; return GetLastSocketError(); } bytesTransferred = bytesReceived; return SocketError.Success; } public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlData* controlBuffer) { IPAddress address = controlBuffer->length == UIntPtr.Zero ? IPAddress.None : new IPAddress((long)controlBuffer->address); return new IPPacketInformation(address, (int)controlBuffer->index); } public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlDataIPv6* controlBuffer) { IPAddress address = controlBuffer->length != UIntPtr.Zero ? new IPAddress(new ReadOnlySpan<byte>(controlBuffer->address, Interop.Winsock.IPv6AddressLength)) : IPAddress.IPv6None; return new IPPacketInformation(address, (int)controlBuffer->index); } public static unsafe SocketError ReceiveMessageFrom(Socket socket, SafeSocketHandle handle, byte[] buffer, int offset, int size, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred) { bool ipv4, ipv6; Socket.GetIPProtocolInformation(socket.AddressFamily, socketAddress, out ipv4, out ipv6); bytesTransferred = 0; receiveAddress = socketAddress; ipPacketInformation = default(IPPacketInformation); fixed (byte* ptrBuffer = buffer) fixed (byte* ptrSocketAddress = socketAddress.Buffer) { Interop.Winsock.WSAMsg wsaMsg; wsaMsg.socketAddress = (IntPtr)ptrSocketAddress; wsaMsg.addressLength = (uint)socketAddress.Size; wsaMsg.flags = socketFlags; WSABuffer wsaBuffer; wsaBuffer.Length = size; wsaBuffer.Pointer = (IntPtr)(ptrBuffer + offset); wsaMsg.buffers = (IntPtr)(&wsaBuffer); wsaMsg.count = 1; if (ipv4) { Interop.Winsock.ControlData controlBuffer; wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer); wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlData); if (socket.WSARecvMsgBlocking( handle, (IntPtr)(&wsaMsg), out bytesTransferred, IntPtr.Zero, IntPtr.Zero) == SocketError.SocketError) { return GetLastSocketError(); } ipPacketInformation = GetIPPacketInformation(&controlBuffer); } else if (ipv6) { Interop.Winsock.ControlDataIPv6 controlBuffer; wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer); wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlDataIPv6); if (socket.WSARecvMsgBlocking( handle, (IntPtr)(&wsaMsg), out bytesTransferred, IntPtr.Zero, IntPtr.Zero) == SocketError.SocketError) { return GetLastSocketError(); } ipPacketInformation = GetIPPacketInformation(&controlBuffer); } else { wsaMsg.controlBuffer.Pointer = IntPtr.Zero; wsaMsg.controlBuffer.Length = 0; if (socket.WSARecvMsgBlocking( handle, (IntPtr)(&wsaMsg), out bytesTransferred, IntPtr.Zero, IntPtr.Zero) == SocketError.SocketError) { return GetLastSocketError(); } } socketFlags = wsaMsg.flags; } return SocketError.Success; } public static unsafe SocketError ReceiveFrom(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred) { int bytesReceived; if (buffer.Length == 0) { bytesReceived = Interop.Winsock.recvfrom(handle, null, 0, socketFlags, socketAddress, ref addressLength); } else { fixed (byte* pinnedBuffer = &buffer[0]) { bytesReceived = Interop.Winsock.recvfrom(handle, pinnedBuffer + offset, size, socketFlags, socketAddress, ref addressLength); } } if (bytesReceived == (int)SocketError.SocketError) { bytesTransferred = 0; return GetLastSocketError(); } bytesTransferred = bytesReceived; return SocketError.Success; } public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength) { if (ioControlCode == Interop.Winsock.IoctlSocketConstants.FIONBIO) { throw new InvalidOperationException(SR.net_sockets_useblocking); } SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking( handle, ioControlCode, optionInValue, optionInValue != null ? optionInValue.Length : 0, optionOutValue, optionOutValue != null ? optionOutValue.Length : 0, out optionLength, IntPtr.Zero, IntPtr.Zero); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static unsafe SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue) { SocketError errorCode; if (optionLevel == SocketOptionLevel.Tcp && (optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) && IOControlKeepAlive.IsNeeded) { errorCode = IOControlKeepAlive.Set(handle, optionName, optionValue); } else { errorCode = Interop.Winsock.setsockopt( handle, optionLevel, optionName, ref optionValue, sizeof(int)); } return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue) { SocketError errorCode; if (optionLevel == SocketOptionLevel.Tcp && (optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) && IOControlKeepAlive.IsNeeded) { return IOControlKeepAlive.Set(handle, optionName, optionValue); } else { errorCode = Interop.Winsock.setsockopt( handle, optionLevel, optionName, optionValue, optionValue != null ? optionValue.Length : 0); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } } public static void SetReceivingDualModeIPv4PacketInformation(Socket socket) { socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); } public static SocketError SetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, MulticastOption optionValue) { Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest(); #pragma warning disable CS0618 // Address is marked obsolete ipmr.MulticastAddress = unchecked((int)optionValue.Group.Address); #pragma warning restore CS0618 if (optionValue.LocalAddress != null) { #pragma warning disable CS0618 // Address is marked obsolete ipmr.InterfaceAddress = unchecked((int)optionValue.LocalAddress.Address); #pragma warning restore CS0618 } else { //this structure works w/ interfaces as well int ifIndex = IPAddress.HostToNetworkOrder(optionValue.InterfaceIndex); ipmr.InterfaceAddress = unchecked((int)ifIndex); } #if BIGENDIAN ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) | (((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) | (((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) | ((uint) ipmr.MulticastAddress >> 24)); if (optionValue.LocalAddress != null) { ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) | (((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) | (((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) | ((uint) ipmr.InterfaceAddress >> 24)); } #endif // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.setsockopt( handle, SocketOptionLevel.IP, optionName, ref ipmr, Interop.Winsock.IPMulticastRequest.Size); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError SetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, IPv6MulticastOption optionValue) { Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest(); ipmr.MulticastAddress = optionValue.Group.GetAddressBytes(); ipmr.InterfaceIndex = unchecked((int)optionValue.InterfaceIndex); // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.setsockopt( handle, SocketOptionLevel.IPv6, optionName, ref ipmr, Interop.Winsock.IPv6MulticastRequest.Size); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError SetLingerOption(SafeSocketHandle handle, LingerOption optionValue) { Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger(); lngopt.OnOff = optionValue.Enabled ? (ushort)1 : (ushort)0; lngopt.Time = (ushort)optionValue.LingerTime; // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.setsockopt( handle, SocketOptionLevel.Socket, SocketOptionName.Linger, ref lngopt, 4); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static void SetIPProtectionLevel(Socket socket, SocketOptionLevel optionLevel, int protectionLevel) { socket.SetSocketOption(optionLevel, SocketOptionName.IPProtectionLevel, protectionLevel); } public static SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue) { if (optionLevel == SocketOptionLevel.Tcp && (optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) && IOControlKeepAlive.IsNeeded) { optionValue = IOControlKeepAlive.Get(handle, optionName); return SocketError.Success; } int optionLength = 4; // sizeof(int) SocketError errorCode = Interop.Winsock.getsockopt( handle, optionLevel, optionName, out optionValue, ref optionLength); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength) { if (optionLevel == SocketOptionLevel.Tcp && (optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) && IOControlKeepAlive.IsNeeded) { return IOControlKeepAlive.Get(handle, optionName, optionValue, ref optionLength); } SocketError errorCode = Interop.Winsock.getsockopt( handle, optionLevel, optionName, optionValue, ref optionLength); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; } public static SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption optionValue) { Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest(); int optlen = Interop.Winsock.IPMulticastRequest.Size; // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.getsockopt( handle, SocketOptionLevel.IP, optionName, out ipmr, ref optlen); if (errorCode == SocketError.SocketError) { optionValue = default(MulticastOption); return GetLastSocketError(); } #if BIGENDIAN ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) | (((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) | (((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) | ((uint) ipmr.MulticastAddress >> 24)); ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) | (((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) | (((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) | ((uint) ipmr.InterfaceAddress >> 24)); #endif // BIGENDIAN IPAddress multicastAddr = new IPAddress(ipmr.MulticastAddress); IPAddress multicastIntr = new IPAddress(ipmr.InterfaceAddress); optionValue = new MulticastOption(multicastAddr, multicastIntr); return SocketError.Success; } public static SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption optionValue) { Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest(); int optlen = Interop.Winsock.IPv6MulticastRequest.Size; // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.getsockopt( handle, SocketOptionLevel.IP, optionName, out ipmr, ref optlen); if (errorCode == SocketError.SocketError) { optionValue = default(IPv6MulticastOption); return GetLastSocketError(); } optionValue = new IPv6MulticastOption(new IPAddress(ipmr.MulticastAddress), ipmr.InterfaceIndex); return SocketError.Success; } public static SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption optionValue) { Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger(); int optlen = 4; // This can throw ObjectDisposedException. SocketError errorCode = Interop.Winsock.getsockopt( handle, SocketOptionLevel.Socket, SocketOptionName.Linger, out lngopt, ref optlen); if (errorCode == SocketError.SocketError) { optionValue = default(LingerOption); return GetLastSocketError(); } optionValue = new LingerOption(lngopt.OnOff != 0, (int)lngopt.Time); return SocketError.Success; } public static unsafe SocketError Poll(SafeSocketHandle handle, int microseconds, SelectMode mode, out bool status) { bool refAdded = false; try { handle.DangerousAddRef(ref refAdded); IntPtr rawHandle = handle.DangerousGetHandle(); IntPtr* fileDescriptorSet = stackalloc IntPtr[2] { (IntPtr)1, rawHandle }; Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue(); // A negative timeout value implies an indefinite wait. int socketCount; if (microseconds != -1) { MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait); socketCount = Interop.Winsock.select( 0, mode == SelectMode.SelectRead ? fileDescriptorSet : null, mode == SelectMode.SelectWrite ? fileDescriptorSet : null, mode == SelectMode.SelectError ? fileDescriptorSet : null, ref IOwait); } else { socketCount = Interop.Winsock.select( 0, mode == SelectMode.SelectRead ? fileDescriptorSet : null, mode == SelectMode.SelectWrite ? fileDescriptorSet : null, mode == SelectMode.SelectError ? fileDescriptorSet : null, IntPtr.Zero); } if ((SocketError)socketCount == SocketError.SocketError) { status = false; return GetLastSocketError(); } status = (int)fileDescriptorSet[0] != 0 && fileDescriptorSet[1] == rawHandle; return SocketError.Success; } finally { if (refAdded) { handle.DangerousRelease(); } } } public static unsafe SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds) { const int StackThreshold = 64; // arbitrary limit to avoid too much space on stack bool ShouldStackAlloc(IList list, ref IntPtr[] lease, out Span<IntPtr> span) { int count; if (list == null || (count = list.Count) == 0) { span = default; return false; } if (count >= StackThreshold) // note on >= : the first element is reserved for internal length { span = lease = ArrayPool<IntPtr>.Shared.Rent(count + 1); return false; } span = default; return true; } IntPtr[] leaseRead = null, leaseWrite = null, leaseError = null; try { Span<IntPtr> readfileDescriptorSet = ShouldStackAlloc(checkRead, ref leaseRead, out var tmp) ? stackalloc IntPtr[StackThreshold] : tmp; Socket.SocketListToFileDescriptorSet(checkRead, readfileDescriptorSet); Span<IntPtr> writefileDescriptorSet = ShouldStackAlloc(checkWrite, ref leaseWrite, out tmp) ? stackalloc IntPtr[StackThreshold] : tmp; Socket.SocketListToFileDescriptorSet(checkWrite, writefileDescriptorSet); Span<IntPtr> errfileDescriptorSet = ShouldStackAlloc(checkError, ref leaseError, out tmp) ? stackalloc IntPtr[StackThreshold] : tmp; Socket.SocketListToFileDescriptorSet(checkError, errfileDescriptorSet); // This code used to erroneously pass a non-null timeval structure containing zeroes // to select() when the caller specified (-1) for the microseconds parameter. That // caused select to actually have a *zero* timeout instead of an infinite timeout // turning the operation into a non-blocking poll. // // Now we pass a null timeval struct when microseconds is (-1). // // Negative microsecond values that weren't exactly (-1) were originally successfully // converted to a timeval struct containing unsigned non-zero integers. This code // retains that behavior so that any app working around the original bug with, // for example, (-2) specified for microseconds, will continue to get the same behavior. int socketCount; fixed (IntPtr* readPtr = &MemoryMarshal.GetReference(readfileDescriptorSet)) fixed (IntPtr* writePtr = &MemoryMarshal.GetReference(writefileDescriptorSet)) fixed (IntPtr* errPtr = &MemoryMarshal.GetReference(errfileDescriptorSet)) { if (microseconds != -1) { Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue(); MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait); socketCount = Interop.Winsock.select( 0, // ignored value readPtr, writePtr, errPtr, ref IOwait); } else { socketCount = Interop.Winsock.select( 0, // ignored value readPtr, writePtr, errPtr, IntPtr.Zero); } } if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Interop.Winsock.select returns socketCount:{socketCount}"); if ((SocketError)socketCount == SocketError.SocketError) { return GetLastSocketError(); } Socket.SelectFileDescriptor(checkRead, readfileDescriptorSet); Socket.SelectFileDescriptor(checkWrite, writefileDescriptorSet); Socket.SelectFileDescriptor(checkError, errfileDescriptorSet); return SocketError.Success; } finally { if (leaseRead != null) ArrayPool<IntPtr>.Shared.Return(leaseRead); if (leaseWrite != null) ArrayPool<IntPtr>.Shared.Return(leaseWrite); if (leaseError != null) ArrayPool<IntPtr>.Shared.Return(leaseError); } } public static SocketError Shutdown(SafeSocketHandle handle, bool isConnected, bool isDisconnected, SocketShutdown how) { SocketError err = Interop.Winsock.shutdown(handle, (int)how); if (err != SocketError.SocketError) { handle.TrackShutdown(how); return SocketError.Success; } err = GetLastSocketError(); Debug.Assert(err != SocketError.NotConnected || (!isConnected && !isDisconnected)); return err; } public static unsafe SocketError ConnectAsync(Socket socket, SafeSocketHandle handle, byte[] socketAddress, int socketAddressLen, ConnectOverlappedAsyncResult asyncResult) { // This will pin the socketAddress buffer. asyncResult.SetUnmanagedStructures(socketAddress); try { int ignoreBytesSent; bool success = socket.ConnectEx( handle, Marshal.UnsafeAddrOfPinnedArrayElement(socketAddress, 0), socketAddressLen, IntPtr.Zero, 0, out ignoreBytesSent, asyncResult.DangerousOverlappedPointer); // SafeHandle was just created in SetUnmanagedStructures return asyncResult.ProcessOverlappedResult(success, 0); } catch { asyncResult.ReleaseUnmanagedStructures(); throw; } } public static unsafe SocketError SendAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult) { // Set up unmanaged structures for overlapped WSASend. asyncResult.SetUnmanagedStructures(buffer, offset, count, null); try { int bytesTransferred; SocketError errorCode = Interop.Winsock.WSASend( handle, ref asyncResult._singleBuffer, 1, // There is only ever 1 buffer being sent. out bytesTransferred, socketFlags, asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures IntPtr.Zero); return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred); } catch { asyncResult.ReleaseUnmanagedStructures(); throw; } } public static unsafe SocketError SendAsync(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult) { // Set up asyncResult for overlapped WSASend. asyncResult.SetUnmanagedStructures(buffers); try { int bytesTransferred; SocketError errorCode = Interop.Winsock.WSASend( handle, asyncResult._wsaBuffers, asyncResult._wsaBuffers.Length, out bytesTransferred, socketFlags, asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures IntPtr.Zero); return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred); } catch { asyncResult.ReleaseUnmanagedStructures(); throw; } } // This assumes preBuffer/postBuffer are pinned already private static unsafe bool TransmitFileHelper( SafeHandle socket, SafeHandle fileHandle, NativeOverlapped* overlapped, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags) { bool needTransmitFileBuffers = false; Interop.Mswsock.TransmitFileBuffers transmitFileBuffers = default(Interop.Mswsock.TransmitFileBuffers); if (preBuffer != null && preBuffer.Length > 0) { needTransmitFileBuffers = true; transmitFileBuffers.Head = Marshal.UnsafeAddrOfPinnedArrayElement(preBuffer, 0); transmitFileBuffers.HeadLength = preBuffer.Length; } if (postBuffer != null && postBuffer.Length > 0) { needTransmitFileBuffers = true; transmitFileBuffers.Tail = Marshal.UnsafeAddrOfPinnedArrayElement(postBuffer, 0); transmitFileBuffers.TailLength = postBuffer.Length; } bool success = Interop.Mswsock.TransmitFile(socket, fileHandle, 0, 0, overlapped, needTransmitFileBuffers ? &transmitFileBuffers : null, flags); return success; } public static unsafe SocketError SendFileAsync(SafeSocketHandle handle, FileStream fileStream, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult) { asyncResult.SetUnmanagedStructures(fileStream, preBuffer, postBuffer, (flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0); try { bool success = TransmitFileHelper( handle, fileStream?.SafeFileHandle, asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures preBuffer, postBuffer, flags); return asyncResult.ProcessOverlappedResult(success, 0); } catch { asyncResult.ReleaseUnmanagedStructures(); throw; } } public static unsafe SocketError SendToAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult) { // Set up asyncResult for overlapped WSASendTo. asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress); try { int bytesTransferred; SocketError errorCode = Interop.Winsock.WSASendTo( handle, ref asyncResult._singleBuffer, 1, // There is only ever 1 buffer being sent. out bytesTransferred, socketFlags, asyncResult.GetSocketAddressPtr(), asyncResult.SocketAddress.Size, asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures IntPtr.Zero); return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred); } catch { asyncResult.ReleaseUnmanagedStructures(); throw; } } public static unsafe SocketError ReceiveAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult) { // Set up asyncResult for overlapped WSARecv. asyncResult.SetUnmanagedStructures(buffer, offset, count, null); try { int bytesTransferred; SocketError errorCode = Interop.Winsock.WSARecv( handle, ref asyncResult._singleBuffer, 1, out bytesTransferred, ref socketFlags, asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures IntPtr.Zero); return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred); } catch { asyncResult.ReleaseUnmanagedStructures(); throw; } } public static unsafe SocketError ReceiveAsync(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult) { // Set up asyncResult for overlapped WSASend. asyncResult.SetUnmanagedStructures(buffers); try { int bytesTransferred; SocketError errorCode = Interop.Winsock.WSARecv( handle, asyncResult._wsaBuffers, asyncResult._wsaBuffers.Length, out bytesTransferred, ref socketFlags, asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures IntPtr.Zero); return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred); } catch { asyncResult.ReleaseUnmanagedStructures(); throw; } } public static unsafe SocketError ReceiveFromAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult) { // Set up asyncResult for overlapped WSARecvFrom. asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress); try { int bytesTransferred; SocketError errorCode = Interop.Winsock.WSARecvFrom( handle, ref asyncResult._singleBuffer, 1, out bytesTransferred, ref socketFlags, asyncResult.GetSocketAddressPtr(), asyncResult.GetSocketAddressSizePtr(), asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures IntPtr.Zero); return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred); } catch { asyncResult.ReleaseUnmanagedStructures(); throw; } } public static unsafe SocketError ReceiveMessageFromAsync(Socket socket, SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult) { asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, socketFlags); try { int bytesTransfered; SocketError errorCode = (SocketError)socket.WSARecvMsg( handle, Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0), out bytesTransfered, asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures IntPtr.Zero); return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransfered); } catch { asyncResult.ReleaseUnmanagedStructures(); throw; } } public static unsafe SocketError AcceptAsync(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult) { // The buffer needs to contain the requested data plus room for two sockaddrs and 16 bytes // of associated data for each. int addressBufferSize = socketAddressSize + 16; byte[] buffer = new byte[receiveSize + ((addressBufferSize) * 2)]; // Set up asyncResult for overlapped AcceptEx. // This call will use completion ports on WinNT. asyncResult.SetUnmanagedStructures(buffer, addressBufferSize); try { // This can throw ObjectDisposedException. int bytesTransferred; bool success = socket.AcceptEx( handle, acceptHandle, Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.Buffer, 0), receiveSize, addressBufferSize, addressBufferSize, out bytesTransferred, asyncResult.DangerousOverlappedPointer); // SafeHandle was just created in SetUnmanagedStructures return asyncResult.ProcessOverlappedResult(success, 0); } catch { asyncResult.ReleaseUnmanagedStructures(); throw; } } public static void CheckDualModeReceiveSupport(Socket socket) { // Dual-mode sockets support received packet info on Windows. } internal static unsafe SocketError DisconnectAsync(Socket socket, SafeSocketHandle handle, bool reuseSocket, DisconnectOverlappedAsyncResult asyncResult) { asyncResult.SetUnmanagedStructures(null); try { // This can throw ObjectDisposedException bool success = socket.DisconnectEx( handle, asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures (int)(reuseSocket ? TransmitFileOptions.ReuseSocket : 0), 0); return asyncResult.ProcessOverlappedResult(success, 0); } catch { asyncResult.ReleaseUnmanagedStructures(); throw; } } internal static SocketError Disconnect(Socket socket, SafeSocketHandle handle, bool reuseSocket) { SocketError errorCode = SocketError.Success; // This can throw ObjectDisposedException (handle, and retrieving the delegate). if (!socket.DisconnectExBlocking(handle, IntPtr.Zero, (int)(reuseSocket ? TransmitFileOptions.ReuseSocket : 0), 0)) { errorCode = GetLastSocketError(); } return errorCode; } } }
// This example will show how to play sounds directly from memory using irrKlang. // This is useful for embedding sounds directly in executables as well for // making irrKlang work together with different APIs like advanced decoders or // middleware. using System; using IrrKlang; namespace CSharp._03._MemoryPlayback { class Class1 { // the following huge array simply represents the plain sound data we // want to play back. It is just the content of a .wav file from the // game 'Hell Troopers'. Usually this sound is somewhere provided by // some external software, but to keep it simple we just use this array as memory. // test.wav, converted to this array by bin2h tool, available at bin2h.irrlicht3d.org private static byte[] SoundDataArray = { 0x52,0x49,0x46,0x46,0x54,0xf,0x0,0x0,0x57,0x41,0x56,0x45,0x66,0x6d,0x74,0x20,0x12, 0x0,0x0,0x0,0x1,0x0,0x1,0x0,0x40,0x1f,0x0,0x0,0x40,0x1f,0x0,0x0,0x1,0x0,0x8, 0x0,0x0,0x0,0x66,0x61,0x63,0x74,0x4,0x0,0x0,0x0,0x22,0xf,0x0,0x0,0x64,0x61,0x74, 0x61,0x22,0xf,0x0,0x0,0x7f,0x80,0x7f,0x7f,0x80,0x80,0x80,0x80,0x80,0x7f,0x80,0x80,0x81, 0x80,0x80,0x7e,0x7f,0x7f,0x7f,0x7f,0x80,0x7f,0x81,0x80,0x80,0x80,0x80,0x7e,0x7e,0x7e,0x7e, 0x7e,0x7e,0x80,0x7f,0x7f,0x7f,0x7f,0x7f,0x7f,0x7e,0x7e,0x7e,0x7e,0x7e,0x7f,0x80,0x80,0x7f, 0x80,0x7f,0x80,0x81,0x81,0x80,0x81,0x80,0x80,0x80,0x80,0x80,0x80,0x81,0x81,0x81,0x83,0x84, 0x85,0x86,0x87,0x86,0x87,0x87,0x85,0x83,0x71,0x5a,0x4f,0x6e,0x6d,0x81,0x8a,0x8c,0x8f,0x91, 0x97,0x84,0x76,0x6e,0x5f,0x68,0x77,0x83,0x85,0x89,0x90,0x94,0x95,0x8f,0x7b,0x70,0x6b,0x72, 0x76,0x80,0x83,0x84,0x8c,0x8f,0x90,0x87,0x7f,0x72,0x6f,0x70,0x77,0x7b,0x7d,0x82,0x84,0x85, 0x87,0x86,0x7e,0x79,0x76,0x77,0x79,0x7e,0x80,0x7f,0x85,0x87,0x89,0x85,0x80,0x7c,0x7b,0x7b, 0x7f,0x7f,0x83,0x84,0x88,0x8a,0x88,0x85,0x7d,0x7c,0x7d,0x80,0x83,0x8b,0x94,0x9d,0xa6,0x8d, 0x31,0x50,0x52,0x73,0x92,0x7e,0x8f,0x81,0xbb,0xb8,0x9f,0x87,0x5b,0x45,0x4c,0x5f,0x80,0x7c, 0x8a,0x8f,0x97,0xa7,0xa8,0x95,0x6a,0x5b,0x57,0x63,0x78,0x83,0x84,0x87,0x95,0x9a,0x9a,0x92, 0x81,0x60,0x5f,0x65,0x75,0x7f,0x84,0x83,0x82,0x8e,0x91,0x8c,0x7b,0x73,0x6a,0x70,0x7b,0x86, 0x88,0x87,0x88,0x87,0x89,0x87,0x80,0x75,0x74,0x75,0x7e,0x84,0x86,0x84,0x84,0x84,0x83,0x83, 0x7c,0x78,0x7a,0x7e,0x86,0x90,0x93,0x94,0x93,0x9b,0x87,0x5e,0x3c,0x3b,0x3e,0x49,0x98,0x99, 0x9d,0x9d,0xab,0xa0,0x97,0x8e,0x51,0x3e,0x49,0x58,0x6f,0x99,0xa7,0x9d,0xa0,0xa2,0x95,0x8a, 0x80,0x5a,0x50,0x5d,0x70,0x7e,0x9b,0x9d,0x94,0x8a,0x86,0x84,0x7b,0x71,0x5f,0x5d,0x69,0x88, 0x96,0x99,0x91,0x88,0x7e,0x80,0x81,0x80,0x80,0x82,0x87,0x8f,0x9d,0xa2,0xa7,0xad,0xae,0x31, 0x31,0x47,0x31,0x78,0x87,0xbc,0xab,0xba,0xc1,0xa3,0xb2,0x9d,0x31,0x39,0x31,0x52,0x5f,0x81, 0xb2,0xa4,0xb7,0xab,0x9a,0x9b,0x80,0x6a,0x37,0x3e,0x51,0x6b,0x98,0xb0,0xad,0xaa,0x95,0x8f, 0x7c,0x7e,0x6c,0x53,0x53,0x64,0x77,0x91,0xa4,0xa1,0x97,0x7d,0x70,0x70,0x73,0x71,0x76,0x77, 0x79,0x8b,0x94,0x97,0x90,0x86,0x74,0x6d,0x70,0x79,0x7d,0x86,0x87,0x89,0x92,0x98,0x9c,0x9d, 0xa0,0xa7,0xb3,0xa2,0x31,0x50,0x31,0x57,0x7f,0xb7,0xc0,0xa1,0xc2,0x9f,0xb3,0x65,0x4a,0x66, 0x31,0x33,0x31,0xa0,0xa1,0xc6,0xc0,0xb9,0xa0,0xa5,0x7c,0x71,0x52,0x46,0x31,0x42,0x83,0x8e, 0xc6,0xb7,0xa9,0x78,0x70,0x6d,0x61,0x70,0x6e,0x6d,0x7b,0x82,0x8e,0x96,0x9f,0x93,0x7c,0x7e, 0x79,0x90,0xa2,0xaa,0xb8,0xbd,0x97,0x36,0x31,0x31,0x31,0x47,0x6b,0xa0,0xaa,0xc6,0xbf,0xad, 0xc1,0xb0,0x6d,0x6b,0x31,0x31,0x31,0x6e,0x7e,0xc0,0xc5,0xbc,0xbd,0xaf,0x91,0x7e,0x6e,0x45, 0x36,0x3c,0x54,0x65,0x8f,0xb5,0xbe,0xae,0x97,0x78,0x5a,0x5b,0x5a,0x6e,0x79,0x7e,0x88,0x93, 0x9f,0xa0,0xa0,0x89,0x79,0x77,0x7b,0x84,0xb0,0xbe,0xc2,0xa0,0x43,0x45,0x31,0x31,0x44,0x69, 0xa5,0xaf,0xbd,0x9f,0xa5,0xc6,0x89,0x9d,0x42,0x31,0x31,0x31,0x47,0x64,0xba,0xc7,0xbe,0xc1, 0xa4,0x96,0x8a,0x84,0x63,0x55,0x42,0x36,0x40,0x6b,0x7d,0xae,0xb2,0xb2,0xa7,0x9d,0x95,0x7d, 0x7b,0x60,0x5f,0x62,0x6b,0x80,0x99,0xc4,0xc3,0xc3,0xb5,0x7b,0x41,0x31,0x31,0x31,0x39,0x84, 0xa4,0xbb,0xbd,0xbd,0xc6,0xb0,0xaa,0x6f,0x45,0x31,0x31,0x31,0x31,0x86,0xaa,0xc4,0xc6,0xc3, 0xb6,0xa8,0x85,0x76,0x64,0x3e,0x31,0x31,0x37,0x52,0xa3,0xc3,0xc6,0xc5,0xc1,0xb5,0x85,0x76, 0x65,0x62,0x65,0x79,0x8b,0xa3,0xb3,0x89,0x87,0x3a,0x31,0x37,0x45,0x60,0x87,0x99,0x92,0x9d, 0xb0,0x8c,0xa3,0x87,0x7c,0x73,0x4f,0x45,0x41,0x65,0x75,0x9f,0xb2,0xa7,0xaa,0xa0,0x94,0x83, 0x7b,0x67,0x59,0x5a,0x4f,0x57,0x69,0x91,0xa2,0xbc,0xba,0xaf,0x9d,0x93,0x8a,0x92,0x9d,0xb3, 0x7f,0x5a,0x31,0x31,0x31,0x31,0x60,0xb2,0xc2,0xc4,0xb6,0xbc,0x7b,0x89,0x92,0x6b,0x6a,0x58, 0x33,0x31,0x4d,0x6e,0x84,0xc9,0xc4,0xc4,0xb2,0x98,0x73,0x65,0x5b,0x58,0x56,0x62,0x58,0x66, 0x88,0x9a,0xb8,0xc3,0xc5,0xbe,0xad,0xac,0xa6,0x84,0x6a,0x31,0x31,0x31,0x31,0x31,0x83,0xab, 0xc7,0xc3,0xc6,0xb8,0xa9,0x9b,0x69,0x66,0x55,0x38,0x31,0x31,0x3c,0x4f,0xa2,0xb8,0xc5,0xc3, 0xc5,0xa3,0x87,0x74,0x52,0x53,0x58,0x57,0x5f,0x70,0x7b,0x8f,0xb6,0xc2,0xc4,0xc4,0xc3,0x99, 0x83,0x5a,0x31,0x31,0x31,0x31,0x4a,0x9a,0xb9,0xb8,0xc8,0xc1,0xc3,0xc0,0xb1,0x90,0x6a,0x48, 0x31,0x31,0x31,0x33,0x61,0x9a,0xb8,0xc6,0xc6,0xc4,0xb0,0xa1,0x97,0x7c,0x6e,0x63,0x54,0x53, 0x66,0x7b,0x94,0xc5,0xc6,0xc4,0x97,0x4f,0x31,0x31,0x31,0x31,0x5f,0x7a,0x8a,0xa0,0xaa,0x9d, 0xaf,0xb5,0xb6,0xba,0x8f,0x73,0x52,0x31,0x31,0x3f,0x57,0x69,0x9c,0xa9,0xab,0xac,0xa7,0xa6, 0xa4,0xa5,0x94,0x8a,0x83,0x6e,0x71,0x8a,0xa5,0xaf,0xad,0x99,0x72,0x31,0x31,0x31,0x45,0x69, 0xaa,0xbf,0xc6,0xb3,0x9c,0x85,0x7a,0x74,0x8a,0x86,0x80,0x6e,0x58,0x41,0x41,0x4c,0x73,0x8e, 0xad,0xb0,0xaf,0x94,0x89,0x84,0x81,0x89,0x91,0x95,0x94,0x8b,0x8d,0x99,0xa7,0xb0,0x9a,0x88, 0x68,0x31,0x31,0x31,0x38,0x55,0x94,0xaa,0xb7,0xb4,0xa8,0x9a,0x8a,0x8a,0x8c,0x8c,0x87,0x6f, 0x5e,0x3f,0x3c,0x3e,0x5b,0x70,0x88,0xa8,0xb0,0xb1,0xaa,0xa4,0x99,0x97,0x95,0x9b,0xa0,0xac, 0xac,0xac,0x87,0x6e,0x57,0x31,0x31,0x31,0x3a,0x55,0x8a,0xa0,0xab,0xb5,0xb1,0x9f,0x9c,0x95, 0x8d,0x87,0x78,0x6b,0x5f,0x47,0x42,0x44,0x55,0x64,0x87,0x95,0xa2,0xb0,0xb1,0xae,0xa5,0xa1, 0x9a,0x9b,0x9f,0xa8,0xad,0xaf,0x9e,0x85,0x54,0x39,0x31,0x31,0x31,0x40,0x75,0x92,0xaf,0xb3, 0xb3,0x9d,0x96,0x8e,0x87,0x86,0x81,0x7b,0x72,0x5d,0x50,0x47,0x48,0x52,0x6f,0x80,0x92,0xa6, 0xad,0xa9,0xa5,0x9f,0x97,0x97,0x9a,0xa4,0xa8,0xb0,0xaa,0x9f,0x71,0x5c,0x40,0x31,0x31,0x36, 0x4d,0x66,0x8f,0x95,0x9f,0x98,0x8f,0x8f,0x8a,0x8f,0x90,0x94,0x86,0x7b,0x75,0x57,0x54,0x4e, 0x57,0x5b,0x7e,0x8a,0x9a,0xad,0xb1,0xaf,0xa7,0xa3,0x9a,0x9a,0x9b,0x9d,0x9f,0x9f,0x84,0x77, 0x4f,0x41,0x33,0x31,0x31,0x46,0x63,0x7d,0x94,0xa2,0x98,0x9f,0x92,0x8a,0x84,0x84,0x81,0x82, 0x83,0x7e,0x7c,0x6e,0x6a,0x65,0x6e,0x75,0x86,0xa3,0xb0,0xb9,0xb5,0xac,0x91,0x85,0x7b,0x75, 0x77,0x84,0x8c,0x8b,0x83,0x73,0x66,0x4e,0x4a,0x4f,0x5b,0x66,0x83,0x8b,0x92,0x8e,0x88,0x79, 0x76,0x75,0x7e,0x86,0x91,0x93,0x92,0x86,0x7e,0x76,0x6b,0x6b,0x76,0x80,0x89,0x9a,0x9d,0x9b, 0x90,0x86,0x75,0x71,0x6e,0x74,0x78,0x80,0x8c,0x91,0x8f,0x8b,0x84,0x79,0x75,0x72,0x75,0x78, 0x81,0x84,0x87,0x84,0x82,0x7a,0x78,0x76,0x78,0x7b,0x7e,0x84,0x86,0x86,0x83,0x81,0x7a,0x79, 0x78,0x7a,0x7d,0x83,0x86,0x88,0x88,0x86,0x83,0x7e,0x7c,0x7a,0x7c,0x7e,0x82,0x83,0x84,0x84, 0x83,0x80,0x7e,0x7d,0x7d,0x7d,0x7f,0x81,0x80,0x7f,0x7e,0x7c,0x79,0x78,0x79,0x7c,0x7e,0x7f, 0x81,0x80,0x80,0x7e,0x7d,0x7d,0x7e,0x7e,0x81,0x82,0x82,0x82,0x81,0x80,0x7d,0x7d,0x7e,0x7f, 0x81,0x83,0x83,0x84,0x83,0x81,0x7f,0x7e,0x7d,0x7e,0x7e,0x80,0x81,0x81,0x80,0x7e,0x7e,0x7e, 0x7e,0x7e,0x7f,0x80,0x81,0x80,0x80,0x7e,0x7f,0x7e,0x80,0x7f,0x81,0x82,0x82,0x82,0x81,0x80, 0x7e,0x7d,0x7c,0x7d,0x80,0x81,0x82,0x82,0x81,0x81,0x80,0x80,0x80,0x81,0x80,0x80,0x7f,0x7e, 0x7d,0x7d,0x7c,0x7c,0x7e,0x7f,0x80,0x81,0x81,0x81,0x80,0x80,0x80,0x80,0x80,0x81,0x81,0x81, 0x81,0x80,0x7e,0x7e,0x7d,0x7e,0x7e,0x7e,0x7f,0x7f,0x80,0x80,0x80,0x80,0x81,0x80,0x81,0x80, 0x80,0x80,0x80,0x7f,0x7f,0x7e,0x7e,0x7e,0x7e,0x7e,0x7e,0x7e,0x7f,0x7f,0x80,0x7f,0x80,0x80, 0x80,0x80,0x81,0x81,0x81,0x80,0x7e,0x7e,0x7e,0x7c,0x7c,0x7d,0x7e,0x7e,0x80,0x80,0x80,0x80, 0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x7e,0x7e,0x7e,0x7e,0x7e,0x7e,0x7e,0x7e,0x7f,0x7f,0x7f, 0x7f,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x81,0x80,0x80,0x80,0x7e,0x7e,0x7d,0x7e,0x7e, 0x7e,0x7f,0x7f,0x7e,0x7e,0x7f,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x7f,0x80,0x7f, 0x7e,0x7f,0x80,0x7f,0x7f,0x7f,0x7f,0x7f,0x80,0x7f,0x80,0x7f,0x80,0x80,0x81,0x80,0x80,0x7f, 0x80,0x7d,0x7e,0x7e,0x7e,0x7e,0x7f,0x80,0x80,0x80,0x80,0x80,0x81,0x80,0x80,0x80,0x7f,0x7f, 0x7f,0x7f,0x7e,0x7f,0x7f,0x80,0x80,0x80,0x80,0x7f,0x7f,0x7e,0x7f,0x80,0x7f,0x80,0x80,0x80, 0x80,0x80,0x80,0x80,0x7e,0x7e,0x7e,0x7e,0x7e,0x7f,0x80,0x80,0x80,0x80,0x80,0x80,0x7f,0x7f, 0x7f,0x7f,0x7e,0x80,0x7f,0x80,0x80,0x80,0x7f,0x80,0x7f,0x7f,0x80,0x7f,0x80,0x80,0x80,0x80, 0x80,0x7f,0x7f,0x7f,0x7f,0x7f,0x80,0x80,0x80,0x7f,0x7f,0x7f,0x7f,0x7f,0x80,0x7f,0x80,0x80, 0x80,0x80,0x80,0x80,0x80,0x80,0x7f,0x7f,0x7e,0x80,0x7f,0x80,0x80,0x80,0x80,0x7f,0x7e,0x7f, 0x7f,0x80,0x80,0x7f,0x80,0x80,0x80,0x80,0x80,0x80,0x7f,0x80,0x80,0x7f,0x7e,0x7f,0x7f,0x7f, 0x7f,0x7f,0x7f,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x7f,0x7e,0x7e,0x7e,0x7f,0x7e,0x7e, 0x7f,0x80,0x7f,0x7f,0x7e,0x7f,0x7f,0x80,0x80,0x7f,0x7f,0x7f,0x80,0x80,0x80,0x7f,0x80,0x80, 0x7f,0x7f,0x7f,0x7e,0x7e,0x80,0x80,0x80,0x80,0x80,0x81,0x80,0x80,0x7f,0x7f,0x7e,0x7e,0x7e, 0x7e,0x80,0x78,0x5f,0x94,0x8a,0x90,0x7c,0x78,0x5b,0xa7,0xaa,0x89,0x68,0x68,0x7f,0xa1,0x95, 0x7b,0x61,0x43,0x97,0xaa,0xae,0x76,0x4e,0x5b,0xac,0x97,0x76,0x4f,0x6e,0x88,0x99,0x90,0x88, 0x31,0x7a,0xbb,0xac,0x86,0x6e,0x6e,0xa9,0x98,0x7c,0x45,0x52,0x71,0xab,0x9e,0x8a,0x7d,0x86, 0x90,0x97,0x8a,0x5f,0x51,0x57,0x8c,0x80,0x83,0x7c,0x8f,0x94,0x99,0x8e,0x85,0x80,0x87,0x85, 0x81,0x7c,0x87,0x87,0x64,0x6a,0x6d,0x75,0x78,0x74,0x87,0x7c,0x92,0x89,0x96,0x89,0x91,0x86, 0x87,0x71,0x7b,0x80,0x67,0x76,0x66,0x6d,0x75,0x7d,0x79,0x83,0x8f,0x93,0x9c,0x8d,0x82,0x7c, 0x7b,0x7f,0x73,0x73,0x79,0x70,0x80,0x7a,0x8c,0x7a,0x84,0x83,0x83,0x84,0x83,0x8c,0x8b,0x79, 0x80,0x89,0x6b,0x79,0x7c,0x81,0x7d,0x81,0x86,0x8f,0x84,0x87,0x91,0x94,0x89,0x7e,0x88,0x91, 0x86,0x87,0x7e,0x81,0x80,0x86,0x78,0x7b,0x81,0x7a,0x70,0x78,0x75,0x6d,0x66,0x6a,0x77,0x78, 0x79,0x7d,0x86,0x8a,0x8e,0x91,0x97,0x91,0x94,0x9d,0x97,0x96,0x9c,0x99,0xa2,0xa4,0xb0,0x6c, 0x47,0x80,0x5d,0x50,0x38,0x62,0x58,0x56,0x6b,0x7b,0x7c,0x7e,0x88,0x75,0x79,0x6a,0x59,0x52, 0x70,0x6d,0x68,0x7f,0xac,0xaf,0xa4,0xc0,0xc3,0xbd,0xb3,0xbd,0xc3,0xbc,0x73,0x67,0x7b,0x52, 0x31,0x31,0x5a,0x4d,0x60,0x87,0x95,0x9e,0xa1,0x99,0x86,0x81,0x76,0x47,0x3e,0x4b,0x3e,0x4a, 0x6d,0x87,0x9a,0xc8,0xc1,0xbb,0xc3,0xc3,0xbf,0xbe,0xc3,0x7e,0x31,0x89,0x38,0x31,0x31,0x51, 0x70,0x77,0xa7,0xad,0xb7,0xb5,0xb6,0x7c,0x71,0x77,0x5a,0x31,0x42,0x46,0x31,0x4a,0x71,0x99, 0x9f,0xc9,0xc1,0xc7,0xc3,0xc5,0xbe,0xb7,0xc4,0x31,0x31,0x45,0x31,0x31,0x31,0x7e,0x84,0xb3, 0xc8,0xbc,0xc1,0xc0,0x93,0x60,0x59,0x4a,0x31,0x31,0x3a,0x47,0x45,0x71,0x8f,0xb9,0xba,0xc2, 0xc3,0xc5,0xc3,0xc3,0xb7,0xbe,0xbf,0x65,0x31,0x68,0x31,0x31,0x31,0xb3,0x8f,0xb5,0xba,0xc5, 0xbf,0xc1,0x8e,0x34,0x52,0x31,0x31,0x31,0x5f,0x5a,0x6a,0x97,0xad,0xc1,0xc6,0xc3,0xc4,0xc3, 0xc3,0xb0,0xb0,0xc0,0x75,0x31,0x6a,0x49,0x31,0x31,0x73,0x95,0xb5,0xcd,0xbf,0xbb,0xbe,0x8e, 0x3f,0x47,0x3f,0x31,0x31,0x3f,0x60,0x7b,0x8c,0xaa,0xb9,0xbe,0xbe,0xc2,0xc3,0xbf,0xae,0xad, 0xbf,0x73,0x31,0x5b,0x33,0x31,0x31,0x7a,0x9d,0xc0,0xc9,0xba,0xba,0xb6,0x79,0x31,0x3f,0x37, 0x31,0x31,0x52,0x76,0x8c,0xac,0xa7,0xb2,0xbb,0xad,0xb1,0xc2,0xc0,0xbd,0xab,0xc3,0x5f,0x31, 0x31,0x39,0x31,0x31,0x8e,0xb2,0xc0,0xc9,0xba,0xb5,0xc2,0xb3,0x31,0x31,0x31,0x31,0x31,0x60, 0x78,0x82,0xab,0xac,0xba,0xb9,0xab,0xb8,0xc5,0xbe,0xbb,0xad,0xc5,0xa7,0x31,0x41,0x59,0x31, 0x31,0x4b,0xa5,0xa8,0xcc,0xbc,0xb6,0xc1,0x95,0x3c,0x31,0x39,0x31,0x31,0x4c,0x85,0x8c,0xad, 0xa5,0xad,0xaf,0xab,0x9c,0xc3,0xc0,0xbf,0xaf,0xc1,0x5d,0x31,0x31,0x31,0x31,0x31,0x8e,0xaa, 0xc6,0xc6,0xba,0xb3,0xc6,0xab,0x31,0x31,0x31,0x31,0x31,0x65,0x81,0x90,0xba,0xa8,0xb2,0xb4, 0xa1,0x9c,0xb6,0xc3,0xb3,0xbb,0xc1,0xa1,0x31,0x5e,0x54,0x31,0x31,0x53,0x9b,0xaa,0xcc,0xb6, 0xb0,0xc0,0x86,0x35,0x39,0x38,0x31,0x35,0x56,0x80,0x99,0xb2,0x9f,0xa8,0xae,0xa5,0x9d,0xc6, 0xc0,0xc2,0xb1,0xc3,0x9d,0x31,0x52,0x31,0x31,0x31,0xa4,0x9d,0xb3,0xbe,0xbe,0xbf,0xc2,0x85, 0x31,0x3a,0x31,0x31,0x33,0x73,0x87,0x9d,0xaf,0xa4,0xb5,0xa5,0x9f,0xb3,0xc2,0xbf,0xb2,0xbe, 0xa3,0x31,0x31,0x5f,0x31,0x31,0x51,0xa2,0xaa,0xcb,0xbe,0xb3,0xc1,0xc3,0x35,0x31,0x3e,0x31, 0x31,0x4d,0x72,0x9b,0xad,0xa9,0xb8,0xc1,0xac,0xa6,0xbe,0xbd,0xb8,0xbb,0xb8,0x6b,0x31,0x6d, 0x31,0x31,0x31,0x7f,0x9b,0xc0,0xc8,0xc3,0xba,0xb1,0x61,0x31,0x3f,0x31,0x31,0x34,0x63,0x8d, 0xaa,0xb5,0xb0,0xbd,0xa5,0x99,0xa4,0xc5,0xb7,0xb2,0xc3,0xa1,0x31,0x5f,0x64,0x31,0x31,0x54, 0x8f,0xa5,0xbf,0xc2,0xbc,0xc3,0x8f,0x3a,0x44,0x3a,0x31,0x31,0x4f,0x81,0x9b,0xad,0xae,0xbe, 0xb6,0xa9,0x9b,0xb9,0xb1,0xa5,0xc8,0xb5,0x31,0x4c,0x9d,0x31,0x31,0x99,0x94,0x84,0xc5,0xb8, 0xbb,0xc7,0xa5,0x31,0x4d,0x54,0x31,0x31,0x40,0x78,0x8f,0xa4,0xb2,0xc1,0xbd,0xac,0xa5,0xb6, 0xa7,0xaf,0xc5,0xb8,0x31,0x62,0xb1,0x31,0x31,0xb2,0x90,0x76,0xc1,0xb3,0xb9,0xca,0x9d,0x31, 0x5d,0x5f,0x31,0x31,0x70,0x76,0x8c,0xaa,0xac,0xbd,0xbb,0xaa,0xac,0xc3,0xaa,0xab,0xc7,0xad, 0x31,0x83,0x31,0x31,0x31,0xbd,0x79,0x83,0xba,0xb3,0xc0,0xc6,0x87,0x31,0x6c,0x52,0x31,0x31, 0x73,0x77,0x91,0xaf,0xb2,0xc5,0xa7,0xa3,0xb1,0xa9,0x9e,0xba,0x91,0x31,0xa8,0x75,0x31,0x31, 0x81,0xb9,0xa4,0xcd,0xb9,0xb2,0xc6,0x6c,0x31,0x6c,0x38,0x31,0x33,0x62,0x74,0x96,0xa8,0xba, 0xc5,0xc1,0xa4,0xa7,0xb2,0xa1,0x94,0xc7,0x89,0x31,0xab,0x6b,0x31,0x31,0x8f,0x68,0xac,0xcd, 0xb6,0xaf,0xc8,0x66,0x31,0x6d,0x36,0x31,0x3c,0x65,0x72,0x94,0xab,0xb8,0xc5,0xbd,0xa8,0xb0, 0xa8,0x8f,0x8a,0xc5,0x91,0x31,0xa5,0x7f,0x31,0x31,0x86,0x71,0xa8,0xcd,0xad,0xad,0xb7,0x69, 0x31,0x75,0x3f,0x31,0x3d,0x65,0x7a,0x8d,0xa8,0xb6,0xc5,0xbf,0xa5,0xaf,0xaa,0x97,0x90,0xc5, 0x8b,0x31,0xab,0x6d,0x31,0x31,0x93,0x69,0xac,0xb1,0xb3,0xb1,0xb5,0x64,0x31,0x70,0x39,0x31, 0x3f,0x6a,0x7b,0x8c,0xa2,0xbd,0xc4,0xa7,0xa1,0xab,0xa9,0x91,0x8c,0xc3,0xa8,0x31,0x90,0x9e, 0x31,0x31,0xbe,0x77,0x8b,0xb6,0xaf,0xb2,0xc0,0x81,0x42,0x77,0x4d,0x31,0x31,0x5d,0x79,0x87, 0xa8,0xbe,0xc3,0xaa,0x9f,0xad,0xa7,0x97,0x91,0xae,0xc8,0x31,0x31,0xb1,0x31,0x31,0x80,0xc2, 0x62,0xcd,0xac,0xaf,0xc5,0xb8,0x31,0x5c,0x83,0x31,0x31,0x6f,0x70,0x6e,0x8a,0xa4,0xc3,0xb8, 0xa3,0xae,0xb7,0xab,0x8a,0x9c,0xb3,0xa2,0x31,0xa2,0xa3,0x31,0x31,0x65,0xc6,0x81,0xcd,0xaf, 0xb8,0xc1,0x7b,0x36,0x5d,0x4a,0x31,0x31,0x64,0x71,0x80,0x8e,0xb8,0xc5,0xb8,0x8f,0xa4,0xb9, 0x87,0x8a,0xa6,0xb7,0xc7,0x31,0x31,0xa8,0x31,0x31,0x6b,0xc3,0x63,0xc8,0xb6,0xb4,0xc1,0xba, 0x49,0x75,0x95,0x31,0x31,0x37,0x69,0x5b,0x8a,0x93,0xae,0xb0,0x92,0xad,0xb2,0xa6,0x86,0x9d, 0xa7,0xbb,0xc4,0x31,0x31,0xc6,0x31,0x31,0x31,0xb3,0x3f,0xc8,0xb5,0xb8,0xc1,0xb3,0x76,0x8d, 0x94,0x31,0x31,0x51,0x4c,0x55,0x79,0x9c,0xa8,0xad,0x91,0x97,0xa9,0x8a,0x79,0xa2,0xa7,0x99, 0xb8,0xc5,0x31,0x31,0x75,0x31,0x31,0x88,0xa1,0x31,0xcb,0xad,0xba,0xc5,0xba,0x62,0x96,0x9c, 0x31,0x31,0x5e,0x46,0x44,0x8c,0x8c,0xa0,0xa5,0xa2,0xa2,0xaa,0x92,0x8e,0x98,0x94,0x8d,0x96, 0xc6,0xb1,0x3e,0x87,0xbb,0x31,0x31,0x4d,0x63,0x50,0xa2,0xad,0xb8,0xbb,0x9a,0x73,0xa3,0x68, 0x31,0x48,0x5b,0x45,0x51,0x7c,0x94,0xa8,0xa7,0xa4,0xac,0x90,0x7e,0x7a,0x96,0x82,0x85,0x9f, 0xb2,0xc0,0x94,0x31,0xbe,0x8f,0x31,0x31,0x71,0x41,0x5d,0xa5,0xb1,0xc1,0xb2,0x87,0x9d,0x94, 0x31,0x3e,0x57,0x45,0x48,0x7b,0x8b,0xa0,0x9f,0x9c,0x9f,0xa0,0x83,0x7b,0x86,0x83,0x79,0x90, 0xa2,0xaf,0xc5,0xac,0x31,0x31,0xa0,0x31,0x31,0x57,0x8c,0x38,0x9a,0xb5,0xb6,0xc9,0xad,0x9c, 0xab,0x65,0x31,0x41,0x4f,0x36,0x4a,0x6f,0x7d,0xa2,0xaa,0xa0,0xba,0xaa,0x86,0x81,0x81,0x6c, 0x6a,0x75,0x93,0x9b,0xac,0xc1,0xc4,0x5a,0x31,0xc2,0x31,0x31,0x37,0x7e,0x3f,0x7d,0xa6,0xb7, 0xc8,0xc1,0xa5,0xad,0xb8,0x3e,0x41,0x54,0x3c,0x31,0x66,0x78,0x82,0x99,0xb0,0xb3,0xb7,0xa0, 0x7f,0x84,0x7b,0x57,0x67,0x7b,0x88,0x97,0xb1,0xc3,0xc3,0xb9,0x6f,0x93,0xa3,0x31,0x31,0x31, 0x37,0x31,0x69,0xb6,0xbf,0xc8,0xc3,0xc2,0xb7,0x84,0x4f,0x50,0x47,0x31,0x31,0x54,0x7a,0x8e, 0x9f,0xb6,0xc5,0xbe,0x9d,0x95,0x6d,0x5c,0x57,0x5d,0x62,0x7d,0x91,0xa0,0xc2,0xc3,0xc4,0xc1, 0x9f,0x45,0xb6,0x69,0x31,0x31,0x3c,0x31,0x48,0xb5,0xbd,0xc2,0xc3,0xc5,0xc4,0xa8,0x64,0x4e, 0x4f,0x33,0x31,0x38,0x5c,0x80,0x97,0xb9,0xc6,0xc3,0xad,0x9c,0x92,0x65,0x47,0x4f,0x51,0x5a, 0x72,0x8a,0xb3,0xbf,0xc3,0xc4,0xc3,0xc3,0x91,0x31,0xb4,0x53,0x31,0x31,0x4c,0x5e,0x55,0xa5, 0xc4,0xc2,0xc8,0xc5,0xc4,0xbe,0x5b,0x3b,0x4c,0x31,0x31,0x3a,0x5f,0x6f,0x98,0xaf,0xc6,0xc3, 0xc1,0xa6,0xa5,0x62,0x4a,0x3b,0x49,0x3e,0x4d,0x79,0x93,0xb3,0xbd,0xc4,0xc3,0xc4,0xc3,0xc2, 0xa4,0x31,0x9a,0x65,0x31,0x31,0x41,0x31,0x4c,0xc6,0xbe,0xbf,0xc2,0xc5,0xc0,0xab,0x6b,0x47, 0x54,0x37,0x31,0x36,0x70,0x6f,0x8f,0xbb,0xc5,0xc5,0xc1,0xb2,0x92,0x80,0x54,0x3f,0x36,0x41, 0x45,0x62,0x94,0xa7,0xb5,0xc5,0xc5,0xc3,0xc3,0xc4,0xb6,0xa2,0x66,0x44,0xb0,0x31,0x31,0x31, 0x5e,0x34,0x7a,0xc7,0xb6,0xc3,0xbf,0xc5,0xaf,0x89,0x47,0x51,0x4f,0x31,0x31,0x4c,0x71,0x7e, 0x9d,0xc0,0xc5,0xbf,0xb7,0xb2,0x7e,0x65,0x5b,0x44,0x3c,0x41,0x51,0x63,0x8f,0x9a,0xaa,0xc3, 0xc3,0xbb,0xbe,0xb8,0xac,0xaf,0xa1,0x66,0x31,0xb8,0x31,0x31,0x31,0x89,0x3c,0x7f,0xb6,0xa4, 0xbc,0xc7,0xbb,0xa4,0x92,0x4d,0x4c,0x5f,0x3c,0x31,0x53,0x71,0x75,0x91,0x9f,0xbd,0xc0,0xb4, 0xaf,0xa6,0x75,0x50,0x5d,0x47,0x38,0x3a,0x69,0x6c,0x87,0xa5,0xaf,0xc0,0xbb,0xb8,0xb3,0xad, 0x9a,0x9a,0xa7,0x8c,0x65,0x45,0x36,0x31,0x39,0x8b,0x71,0x34,0xaf,0xbc,0xb5,0xc0,0xa0,0xa5, 0xa0,0x9a,0x5d,0x6d,0x4a,0x37,0x4e,0x71,0x6d,0x86,0x94,0x9f,0xb1,0xa8,0xa8,0xa7,0x9b,0x77, 0x6b,0x5a,0x61,0x4b,0x38,0x69,0x71,0x7b,0x92,0xad,0xa5,0xaa,0xb6,0xaa,0x9e,0x9a,0x97,0x94, 0xa0,0xa0,0x87,0x31,0xb8,0x31,0x31,0x3f,0x8c,0x36,0x4d,0xb9,0x92,0xc8,0x9a,0xb0,0x99,0xad, 0x63,0x75,0x7b,0x3c,0x4e,0x55,0x73,0x5b,0x87,0x90,0x9f,0xa5,0xa2,0xad,0xa1,0x9b,0x7b,0x7d, 0x70,0x3f,0x57,0x66,0x49,0x61,0x86,0x86,0x8c,0xb3,0xb0,0xa6,0xaa,0xa0,0x92,0x91,0x8c,0x89, 0x96,0x96,0x89,0x31,0xc1,0x79,0x31,0x44,0x72,0x35,0x49,0x89,0x84,0x87,0xbc,0xab,0xb2,0xb0, 0x80,0x6d,0x89,0x74,0x49,0x5c,0x65,0x58,0x66,0x7d,0x8f,0x96,0x97,0xa5,0xa8,0x9f,0x90,0x84, 0x80,0x71,0x4f,0x49,0x71,0x3e,0x52,0x76,0x89,0x81,0xa7,0xb6,0xa4,0xa6,0xa3,0x9f,0x8a,0x89, 0x86,0x8e,0x95,0x93,0x98,0x55,0xaa,0xa2,0x3b,0x54,0x62,0x45,0x39,0x79,0x86,0x70,0x91,0x9a, 0xaf,0xa8,0x93,0x76,0x91,0x84,0x61,0x68,0x69,0x5b,0x5d,0x79,0x7f,0x87,0x8c,0x9a,0xa2,0x9d, 0x98,0x94,0x91,0x81,0x73,0x70,0x6b,0x4f,0x6a,0x55,0x65,0x72,0x87,0x89,0x91,0xa7,0x9d,0xaa, 0x9c,0x95,0x8d,0x89,0x80,0x81,0x8e,0x8f,0x92,0x83,0x65,0xc9,0x31,0x5b,0x5b,0x75,0x3c,0x55, 0x9a,0x6d,0x97,0x80,0xa2,0x95,0x9d,0x81,0x8f,0x94,0x65,0x73,0x71,0x70,0x5d,0x6b,0x78,0x7b, 0x80,0x83,0x94,0x91,0x94,0x8e,0x96,0x90,0x7e,0x7e,0x7b,0x71,0x65,0x5d,0x6c,0x73,0x60,0x74, 0x84,0x86,0x88,0xa4,0x9f,0x95,0x97,0x93,0x8e,0x82,0x7c,0x7d,0x81,0x86,0x94,0x98,0x8c,0x5d, 0xaf,0x3c,0x54,0x61,0x7a,0x4c,0x4f,0x8c,0x7c,0x8e,0x86,0x91,0x92,0x99,0x8d,0x8e,0x94,0x70, 0x72,0x76,0x77,0x66,0x72,0x77,0x77,0x7a,0x80,0x8b,0x8a,0x8e,0x8e,0x91,0x8f,0x84,0x84,0x81, 0x7c,0x72,0x76,0x76,0x6e,0x67,0x79,0x79,0x6e,0x81,0x88,0x87,0x89,0x99,0x93,0x8f,0x91,0x8b, 0x87,0x83,0x7e,0x7d,0x82,0x80,0x8c,0x97,0x68,0x6a,0xa0,0x5a,0x66,0x74,0x79,0x5b,0x71,0x81, 0x73,0x86,0x7e,0x91,0x8e,0x95,0x85,0x8b,0x91,0x7b,0x79,0x7b,0x7a,0x70,0x74,0x77,0x79,0x79, 0x7b,0x89,0x87,0x8a,0x8a,0x8e,0x8e,0x85,0x84,0x81,0x7f,0x79,0x77,0x77,0x76,0x76,0x7a,0x7c, 0x74,0x78,0x84,0x7d,0x7a,0x8d,0x8a,0x81,0x88,0x8c,0x89,0x80,0x84,0x7e,0x7f,0x80,0x7d,0x80, 0x83,0x83,0x84,0x8e,0x8e,0x91,0x73,0x7f,0x7c,0x69,0x6a,0x78,0x73,0x65,0x73,0x7c,0x75,0x7a, 0x7e,0x89,0x89,0x89,0x89,0x8c,0x86,0x80,0x7f,0x81,0x7c,0x76,0x77,0x79,0x77,0x76,0x79,0x80, 0x81,0x81,0x86,0x89,0x86,0x85,0x86,0x86,0x83,0x7e,0x7e,0x7b,0x78,0x76,0x76,0x79,0x79,0x7b, 0x7f,0x80,0x80,0x80,0x86,0x7b,0x80,0x7b,0x76,0x7f,0x7b,0x7d,0x7c,0x85,0x81,0x82,0x87,0x87, 0x84,0x87,0x87,0x85,0x89,0x8e,0x91,0x87,0x75,0x94,0x65,0x62,0x66,0x74,0x65,0x5f,0x84,0x79, 0x80,0x81,0x8c,0x8f,0x8f,0x8a,0x8b,0x8f,0x7b,0x7a,0x7b,0x7a,0x70,0x6d,0x77,0x77,0x75,0x79, 0x80,0x85,0x85,0x87,0x8f,0x8e,0x88,0x86,0x86,0x80,0x7b,0x79,0x77,0x75,0x73,0x74,0x76,0x7b, 0x7b,0x83,0x85,0x86,0x87,0x88,0x89,0x86,0x84,0x80,0x80,0x7c,0x78,0x79,0x79,0x77,0x78,0x7b, 0x7c,0x7d,0x82,0x83,0x85,0x86,0x86,0x86,0x86,0x83,0x81,0x7e,0x7d,0x7b,0x79,0x78,0x79,0x79, 0x79,0x7b,0x7e,0x80,0x80,0x84,0x84,0x86,0x84,0x84,0x83,0x80,0x7e,0x7c,0x7b,0x7b,0x7b,0x7a, 0x7b,0x7c,0x7d,0x7f,0x80,0x81,0x84,0x83,0x83,0x84,0x83,0x81,0x80,0x7e,0x7c,0x7c,0x7b,0x7b, 0x7b,0x7b,0x7c,0x7f,0x80,0x80,0x81,0x82,0x82,0x82,0x81,0x80,0x80,0x80,0x7e,0x7e,0x7c,0x7c, 0x7c,0x7c,0x7e,0x7e,0x7e,0x7e,0x80,0x81,0x81,0x81,0x81,0x81,0x81,0x81,0x80,0x80,0x7f,0x7e, 0x7e,0x7d,0x7c,0x7d,0x7e,0x7e,0x7e,0x7f,0x80,0x80,0x80,0x80,0x81,0x81,0x80,0x80,0x80,0x7f, 0x7e,0x7e,0x7c,0x7c,0x7d,0x7d,0x7e,0x7e,0x80,0x80,0x81,0x81,0x81,0x80,0x80,0x80,0x7f,0x7e, 0x7e,0x7e,0x7e,0x7d,0x7e,0x7e,0x7e,0x7e,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x80,0x7f, 0x7e,0x7f,0x7f,0x7f,0x80,0x7f,0x7f,0x7f,0x80,0x80,0x80,0x80,0x7f,0x7f,0x7e,0x7f,0x7e,0x7f, 0x7f,0x7e,0x7e,0x7f,0x7e,0x7e,0x7e,0x80,0x80,0x7f,0x7f,0x80,0x7f,0x7f,0x7f,0x80,0x80,0x80, 0x80,0x80,0x80,0x7f,0x80,0x80,0x80,0x7f,0x7f,0x80,0x7e,0x7f,0x7e,0x7f,0x7f,0x7f,0x7f,0x7f, 0x7e,0x7f,0x7f,0x7f,0x7f,0x7f,0x7f,0x80,0x80,0x80,0x80,0x80,0x80,0x7e,0x7e,0x7f,0x7e,0x7f, 0x7e,0x7f,0x7e,0x7e,0x7e,0x7f,0x7f,0x7f,0x7f}; // irrKlang 3D sound engine example 03, // demonstrating playing sounds directly from memory [STAThread] static void Main(string[] args) { // start the sound engine with default parameters ISoundEngine engine = new ISoundEngine(); // To make irrKlang know about the memory we want to play, we register // the memory chunk as a sound source. We specify the name "testsound.wav", so // we can use the name later for playing back the sound. Note that you // could also specify a better fitting name like "ok.wav". // The method AddSoundSourceFromMemory() also returns a pointer to the created sound source, // it can be used as parameter for play2D() later, if you don't want to // play sounds via string names. ISoundSource source = engine.AddSoundSourceFromMemory(SoundDataArray, "testsound.wav"); // now play the sound until user presses 'q' Console.Out.WriteLine("\nPlaying sounds directly from memory"); Console.Out.WriteLine("Press any key to play some sound, press 'q' to quit."); do { // play the sound we added to memory engine.Play2D("testsound.wav"); } while(_getch() != 'q'); // user pressed 'q' key, cancel } // some simple function for reading keys from the console [System.Runtime.InteropServices.DllImport("msvcrt")] static extern int _getch(); } }
// 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.Net.Test.Common; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { public class PlatformHandler_HttpClientHandler : HttpClientHandlerTestBase { protected override bool UseSocketsHttpHandler => false; public PlatformHandler_HttpClientHandler(ITestOutputHelper output) : base(output) { } [Theory] [InlineData(false)] [InlineData(true)] [PlatformSpecific(TestPlatforms.Windows)] // Curl has issues with trailing headers https://github.com/curl/curl/issues/1354 public async Task GetAsync_TrailingHeaders_Ignored(bool includeTrailerHeader) { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); await TestHelper.WhenAllCompletedOrAnyFailed( getResponseTask, server.AcceptConnectionSendCustomResponseAndCloseAsync( "HTTP/1.1 200 OK\r\n" + "Connection: close\r\n" + "Transfer-Encoding: chunked\r\n" + (includeTrailerHeader ? "Trailer: MyCoolTrailerHeader\r\n" : "") + "\r\n" + "4\r\n" + "data\r\n" + "0\r\n" + "MyCoolTrailerHeader: amazingtrailer\r\n" + "\r\n")); using (HttpResponseMessage response = await getResponseTask) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); if (includeTrailerHeader) { Assert.Contains("MyCoolTrailerHeader", response.Headers.GetValues("Trailer")); } Assert.False(response.Headers.Contains("MyCoolTrailerHeader"), "Trailer should have been ignored"); string data = await response.Content.ReadAsStringAsync(); Assert.Contains("data", data); Assert.DoesNotContain("MyCoolTrailerHeader", data); Assert.DoesNotContain("amazingtrailer", data); } } }); } } public sealed class PlatformHandler_HttpClientHandler_Asynchrony_Test : HttpClientHandler_Asynchrony_Test { public PlatformHandler_HttpClientHandler_Asynchrony_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpProtocolTests : HttpProtocolTests { public PlatformHandler_HttpProtocolTests(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpProtocolTests_Dribble : HttpProtocolTests_Dribble { public PlatformHandler_HttpProtocolTests_Dribble(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_DiagnosticsTest : DiagnosticsTest { public PlatformHandler_DiagnosticsTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClient_SelectedSites_Test : HttpClient_SelectedSites_Test { public PlatformHandler_HttpClient_SelectedSites_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClientEKUTest : HttpClientEKUTest { public PlatformHandler_HttpClientEKUTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } #if NETCOREAPP public sealed class PlatformHandler_HttpClientHandler_Decompression_Tests : HttpClientHandler_Decompression_Test { public PlatformHandler_HttpClientHandler_Decompression_Tests(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test { public PlatformHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } #endif public sealed class PlatformHandler_HttpClientHandler_ClientCertificates_Test : HttpClientHandler_ClientCertificates_Test { public PlatformHandler_HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClientHandler_DefaultProxyCredentials_Test : HttpClientHandler_DefaultProxyCredentials_Test { public PlatformHandler_HttpClientHandler_DefaultProxyCredentials_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClientHandler_MaxConnectionsPerServer_Test : HttpClientHandler_MaxConnectionsPerServer_Test { public PlatformHandler_HttpClientHandler_MaxConnectionsPerServer_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClientHandler_ServerCertificates_Test : HttpClientHandler_ServerCertificates_Test { public PlatformHandler_HttpClientHandler_ServerCertificates_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_PostScenarioTest : PostScenarioTest { public PlatformHandler_PostScenarioTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_ResponseStreamTest : ResponseStreamTest { public PlatformHandler_ResponseStreamTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClientHandler_SslProtocols_Test : HttpClientHandler_SslProtocols_Test { public PlatformHandler_HttpClientHandler_SslProtocols_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClientHandler_Proxy_Test : HttpClientHandler_Proxy_Test { public PlatformHandler_HttpClientHandler_Proxy_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_SchSendAuxRecordHttpTest : SchSendAuxRecordHttpTest { public PlatformHandler_SchSendAuxRecordHttpTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClientHandlerTest : HttpClientHandlerTest { public PlatformHandler_HttpClientHandlerTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandlerTest_AutoRedirect : HttpClientHandlerTest_AutoRedirect { public PlatformHandlerTest_AutoRedirect(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_DefaultCredentialsTest : DefaultCredentialsTest { public PlatformHandler_DefaultCredentialsTest(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_IdnaProtocolTests : IdnaProtocolTests { public PlatformHandler_IdnaProtocolTests(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; // WinHttp on Win7 does not support IDNA protected override bool SupportsIdna => !PlatformDetection.IsWindows7; } public sealed class PlatformHandler_HttpRetryProtocolTests : HttpRetryProtocolTests { public PlatformHandler_HttpRetryProtocolTests(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandlerTest_Cookies : HttpClientHandlerTest_Cookies { public PlatformHandlerTest_Cookies(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandlerTest_Cookies_Http11 : HttpClientHandlerTest_Cookies_Http11 { public PlatformHandlerTest_Cookies_Http11(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClientHandler_MaxResponseHeadersLength_Test : HttpClientHandler_MaxResponseHeadersLength_Test { public PlatformHandler_HttpClientHandler_MaxResponseHeadersLength_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClientHandler_Cancellation_Test : HttpClientHandler_Cancellation_Test { public PlatformHandler_HttpClientHandler_Cancellation_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } public sealed class PlatformHandler_HttpClientHandler_Authentication_Test : HttpClientHandler_Authentication_Test { public PlatformHandler_HttpClientHandler_Authentication_Test(ITestOutputHelper output) : base(output) { } protected override bool UseSocketsHttpHandler => false; } // Enable this to run HTTP2 tests on platform handler #if PLATFORM_HANDLER_HTTP2_TESTS public sealed class PlatformHandlerTest_Http2 : HttpClientHandlerTest_Http2 { protected override bool UseSocketsHttpHandler => false; } [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.SupportsAlpn))] public sealed class PlatformHandlerTest_Cookies_Http2 : HttpClientHandlerTest_Cookies { protected override bool UseSocketsHttpHandler => false; protected override bool UseHttp2LoopbackServer => true; } #endif }