context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Copyright (C) 2012-2018 Luca Piccioni
//
// 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.
// Support for WGL_ARB_multisample or WGL_EXT_multisample
#define SUPPORT_MULTISAMPLE
// Support for WGL_ARB_pbuffer
#define SUPPORT_PBUFFER
// Support WGL_ARB_framebuffer_sRGB or WGL_EXT_framebuffer_sRGB
#define SUPPORT_FRAMEBUFFER_SRGB
// Support WGL_ARB_pixel_format_float || WGL_ATI_pixel_format_float
#define SUPPORT_PIXEL_FORMAT_FLOAT
// Support WGL_EXT_pixel_format_packed_float
#define SUPPORT_PIXEL_FORMAT_PACKED_FLOAT
//
#undef CHOOSE_PIXEL_FORMAT_FALLBACK
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
// ReSharper disable once RedundantUsingDirective
using System.Reflection; // Do not delete me! .NET Core include extension methods
using System.Runtime.InteropServices;
using Khronos;
// ReSharper disable RedundantAssignment
// ReSharper disable InvertIf
// ReSharper disable RedundantIfElseBlock
// ReSharper disable SwitchStatementMissingSomeCases
// ReSharper disable InheritdocConsiderUsage
namespace OpenGL
{
/// <summary>
/// Device context for MS Windows platform.
/// </summary>
internal sealed class DeviceContextWGL : DeviceContext
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DeviceContextWGL"/> class.
/// </summary>
/// <param name='windowHandle'>
/// A <see cref="IntPtr"/> that specifies the window handle used to create the device context.
/// </param>
/// <exception cref='InvalidOperationException'>
/// Is thrown when an operation cannot be performed.
/// </exception>
/// <remarks>
/// The created instance will be bound to the (hidden) window used for initializing <see cref="Gl"/>. The device contextes
/// created by using this constructor are meant to render on framebuffer objects.
/// </remarks>
public DeviceContextWGL()
{
if (Gl.NativeWindow == null)
throw new InvalidOperationException("no underlying native window", Gl.InitializationException);
_WindowHandle = Gl.NativeWindow.Handle;
IsPixelFormatSet = true; // We do not want to reset pixel format
DeviceContext = Wgl.GetDC(_WindowHandle);
if (DeviceContext == IntPtr.Zero)
throw new InvalidOperationException("unable to get device context");
}
/// <summary>
/// Initializes a new instance of the <see cref="DeviceContextWGL"/> class.
/// </summary>
/// <param name='windowHandle'>
/// A <see cref="IntPtr"/> that specifies the window handle used to create the device context.
/// </param>
/// <exception cref="ArgumentException">
/// Exception thrown if <paramref name="windowHandle"/> is <see cref="IntPtr.Zero"/>.
/// </exception>
/// <exception cref='InvalidOperationException'>
/// Is thrown when an operation cannot be performed.
/// </exception>
/// <remarks>
/// The <paramref name="windowHandle"/> must be an handle to a native window. It is normally created by calling
/// CreateWindow(Ex)? methods.
/// </remarks>
public DeviceContextWGL(IntPtr windowHandle)
{
if (windowHandle == IntPtr.Zero)
throw new ArgumentException("null handle", nameof(windowHandle));
_WindowHandle = windowHandle;
DeviceContext = Wgl.GetDC(_WindowHandle);
if (DeviceContext == IntPtr.Zero)
throw new InvalidOperationException("unable to get device context");
}
/// <summary>
/// Initializes a new instance of the <see cref="DeviceContextWGL"/> class.
/// </summary>
/// <param name='nativeBuffer'>
/// A <see cref="INativePBuffer"/> that specifies the P-Buffer used to create the device context.
/// </param>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="nativeBuffer"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Exception thrown if <paramref name="nativeBuffer"/> is not an instance created by
/// <see cref="DeviceContext.CreatePBuffer(DevicePixelFormat, uint, uint)"/>.
/// </exception>
/// <exception cref='InvalidOperationException'>
/// Is thrown when an operation cannot be performed.
/// </exception>
public DeviceContextWGL(INativePBuffer nativeBuffer)
{
if (nativeBuffer == null)
throw new ArgumentNullException(nameof(nativeBuffer));
NativePBuffer nativePBuffer = nativeBuffer as NativePBuffer;
if (nativePBuffer == null)
throw new ArgumentException("INativePBuffer not created with DeviceContext.CreatePBuffer");
if (!Wgl.CurrentExtensions.Pbuffer_ARB && !Wgl.CurrentExtensions.Pbuffer_EXT)
throw new InvalidOperationException("WGL_(ARB|EXT)_pbuffer not supported");
_WindowHandle = nativePBuffer.Handle;
DeviceContext = Wgl.CurrentExtensions.Pbuffer_ARB ? Wgl.GetPbufferDCARB(nativePBuffer.Handle) : Wgl.GetPbufferDCEXT(nativePBuffer.Handle);
if (DeviceContext == IntPtr.Zero)
throw new InvalidOperationException("unable to get device context");
_DeviceContextPBuffer = true;
IsPixelFormatSet = true;
}
#endregion
#region Device Information
/// <summary>
/// The device context of the control.
/// </summary>
internal IntPtr DeviceContext { get; private set; }
/// <summary>
/// The window handle.
/// </summary>
private IntPtr _WindowHandle;
/// <summary>
/// Flag indicating whether <see cref="DeviceContext"/> is obtained by using GetPbufferDC* and
/// <see cref="_WindowHandle"/> is obtained by using CreatePbuffer*.
/// </summary>
private readonly bool _DeviceContextPBuffer;
#endregion
#region Window Factory
/// <summary>
/// Determine whether the hosting platform is able to create a P-Buffer.
/// </summary>
public new static bool IsPBufferSupported => Wgl.CurrentExtensions != null && (Wgl.CurrentExtensions.Pbuffer_ARB || Wgl.CurrentExtensions.Pbuffer_EXT);
/// <summary>
/// Native window implementation for Windows.
/// </summary>
internal class NativeWindow : INativeWindow
{
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public NativeWindow()
: this(1, 1, 16, 16)
{
}
/// <summary>
/// Default constructor.
/// </summary>
public NativeWindow(int x, int y, uint width, uint height)
{
try {
// Register window class
WNDCLASSEX windowClass = new WNDCLASSEX();
const string defaultWindowClass = "OpenGL.Net2";
windowClass.cbSize = Marshal.SizeOf(typeof(WNDCLASSEX));
windowClass.style = (int)(UnsafeNativeMethods.CS_HREDRAW | UnsafeNativeMethods.CS_VREDRAW | UnsafeNativeMethods.CS_OWNDC);
windowClass.lpfnWndProc = Marshal.GetFunctionPointerForDelegate(_WindowsWndProc);
#if NETSTANDARD1_1 || NETSTANDARD1_4
windowClass.hInstance = UnsafeNativeMethods.GetModuleHandle(typeof(Gl).GetTypeInfo().Assembly.FullName); // XXX
#elif NETSTANDARD2_0 || NETCORE
windowClass.hInstance = UnsafeNativeMethods.GetModuleHandle(typeof(Gl).GetTypeInfo().Assembly.Location);
#else
windowClass.hInstance = Marshal.GetHINSTANCE(typeof(Gl).Module);
#endif
windowClass.lpszClassName = defaultWindowClass;
if ((_ClassAtom = UnsafeNativeMethods.RegisterClassEx(ref windowClass)) == 0)
throw new Win32Exception(Marshal.GetLastWin32Error());
// Create window
const uint defaultWindowStyleEx = UnsafeNativeMethods.WS_EX_APPWINDOW | UnsafeNativeMethods.WS_EX_WINDOWEDGE;
const uint defaultWindowStyle = UnsafeNativeMethods.WS_OVERLAPPED | UnsafeNativeMethods.WS_CLIPCHILDREN | UnsafeNativeMethods.WS_CLIPSIBLINGS;
_Handle = UnsafeNativeMethods.CreateWindowEx(
defaultWindowStyleEx, windowClass.lpszClassName, string.Empty, defaultWindowStyle,
x, y, (int)width, (int)height,
IntPtr.Zero, IntPtr.Zero, windowClass.hInstance, IntPtr.Zero
);
if (_Handle == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
} catch {
Dispose();
throw;
}
}
#endregion
#region P/Invoke
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "MemberCanBePrivate.Local")]
[SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Local")]
private struct WNDCLASSEX {
public int cbSize;
public int style;
public IntPtr lpfnWndProc;
public int cbClsExtra;
public int cbWndExtra;
public IntPtr hInstance;
public IntPtr hIcon;
public IntPtr hCursor;
public IntPtr hbrBackground;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszMenuName;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszClassName;
public IntPtr hIconSm;
}
[SuppressMessage("ReSharper", "InconsistentNaming")]
private static class UnsafeNativeMethods
{
// CLASS STYLE
public const uint CS_VREDRAW = 0x0001;
public const uint CS_HREDRAW = 0x0002;
public const uint CS_OWNDC = 0x0020;
// WINDOWS STYLE
public const uint WS_CLIPCHILDREN = 0x2000000;
public const uint WS_CLIPSIBLINGS = 0x4000000;
public const uint WS_OVERLAPPED = 0x0;
// WINDOWS STYLE EX
public const uint WS_EX_APPWINDOW = 0x00040000;
public const uint WS_EX_WINDOWEDGE = 0x00000100;
internal delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "DefWindowProc", SetLastError = true)]
internal static extern IntPtr DefWindowProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "RegisterClassEx", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern ushort RegisterClassEx([In] ref WNDCLASSEX lpWndClass);
[DllImport("user32.dll", EntryPoint = "UnregisterClass", SetLastError = true)]
public static extern bool UnregisterClass(ushort lpClassAtom, IntPtr hInstance);
[DllImport("user32.dll", EntryPoint = "CreateWindowEx", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern IntPtr CreateWindowEx(uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle, int x, int y, int nWidth, int nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool DestroyWindow(IntPtr hWnd);
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern IntPtr GetModuleHandle(string lpModuleName);
}
private static IntPtr WindowsWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
return UnsafeNativeMethods.DefWindowProc(hWnd, msg, wParam, lParam);
}
private static readonly UnsafeNativeMethods.WndProc _WindowsWndProc = WindowsWndProc;
#endregion
#region INativeWindow Implementation
/// <summary>
/// Get the display handle associated this instance.
/// </summary>
IntPtr INativeWindow.Display => IntPtr.Zero;
/// <summary>
/// Get the native window handle.
/// </summary>
IntPtr INativeWindow.Handle => _Handle;
/// <summary>
/// The native window handle.
/// </summary>
private IntPtr _Handle;
/// <summary>
/// The atom associated to the window class.
/// </summary>
private ushort _ClassAtom;
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (_Handle != IntPtr.Zero) {
UnsafeNativeMethods.DestroyWindow(_Handle);
_Handle = IntPtr.Zero;
}
if (_ClassAtom != 0) {
#if NETSTANDARD1_1 || NETSTANDARD1_4 || NETSTANDARD2_0 || NETCORE
// XXX
#else
UnsafeNativeMethods.UnregisterClass(_ClassAtom, Marshal.GetHINSTANCE(typeof(Gl).Module));
#endif
_ClassAtom = 0;
}
}
#endregion
}
/// <summary>
/// P-Buffer implementation for Windows.
/// </summary>
internal class NativePBuffer : INativePBuffer
{
#region Constructors
/// <summary>
/// Construct a NativePBuffer with a specific pixel format and size.
/// </summary>
/// <param name="pixelFormat">
/// A <see cref="DevicePixelFormat"/> that specifies the pixel format and the ancillary buffers required.
/// </param>
/// <param name="width">
/// A <see cref="UInt32"/> that specifies the width of the P-Buffer, in pixels.
/// </param>
/// <param name="height">
/// A <see cref="UInt32"/> that specifies the height of the P-Buffer, in pixels.
/// </param>
[RequiredByFeature("WGL_ARB__pbuffer")]
public NativePBuffer(DevicePixelFormat pixelFormat, uint width, uint height)
{
if (pixelFormat == null)
throw new ArgumentNullException(nameof(pixelFormat));
if (!Wgl.CurrentExtensions.Pbuffer_ARB && !Wgl.CurrentExtensions.Pbuffer_EXT)
throw new NotSupportedException("WGL_(ARB|EXT)_pbuffer not implemented");
if (Gl.NativeWindow == null)
throw new InvalidOperationException("no underlying native window", Gl.InitializationException);
try {
// Uses screen device context
_DeviceContext = Wgl.GetDC(Gl.NativeWindow.Handle);
// Choose appropriate pixel format
pixelFormat.RenderWindow = false; // XXX
pixelFormat.RenderPBuffer = true;
pixelFormat.DoubleBuffer = true;
int pixelFormatIndex = ChoosePixelFormat(_DeviceContext, pixelFormat);
Handle = Wgl.CurrentExtensions.Pbuffer_ARB ? Wgl.CreatePbufferARB(_DeviceContext, pixelFormatIndex, (int)width, (int)height, new[] { 0 }) : Wgl.CreatePbufferEXT(_DeviceContext, pixelFormatIndex, (int)width, (int)height, new[] { 0 });
if (Handle == IntPtr.Zero)
throw new InvalidOperationException("unable to create P-Buffer", GetPlatformExceptionCore());
} catch {
Dispose();
throw;
}
}
#endregion
#region Handles
/// <summary>
/// The device context used for allocating the P-Buffer resources.
/// </summary>
private IntPtr _DeviceContext;
/// <summary>
/// Get the P-Buffer handle.
/// </summary>
[RequiredByFeature("WGL_ARB__pbuffer")]
public IntPtr Handle { get; private set; }
#endregion
#region INativePBuffer Implementation
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
[RequiredByFeature("WGL_ARB__pbuffer")]
public void Dispose()
{
if (Handle != IntPtr.Zero) {
if (Wgl.CurrentExtensions.Pbuffer_ARB) {
bool res = Wgl.DestroyPbufferARB(Handle);
Debug.Assert(res);
} else {
bool res = Wgl.DestroyPbufferEXT(Handle);
Debug.Assert(res);
}
Handle = IntPtr.Zero;
}
if (_DeviceContext != IntPtr.Zero) {
Wgl.ReleaseDC(IntPtr.Zero, _DeviceContext);
_DeviceContext = IntPtr.Zero;
}
}
#endregion
}
#endregion
#region DeviceContext Overrides
/// <summary>
/// Get this DeviceContext API version.
/// </summary>
public override KhronosVersion Version => new KhronosVersion(1, 0, KhronosVersion.ApiWgl);
/// <summary>
/// Create a simple context.
/// </summary>
/// <returns>
/// A <see cref="IntPtr"/> that represents the handle of the created context. If the context cannot be
/// created, it returns IntPtr.Zero.
/// </returns>
internal override IntPtr CreateSimpleContext()
{
// Define most compatible pixel format
Wgl.PIXELFORMATDESCRIPTOR pfd = new Wgl.PIXELFORMATDESCRIPTOR(24);
// Find pixel format match
pfd.dwFlags |= Wgl.PixelFormatDescriptorFlags.DepthDontCare | Wgl.PixelFormatDescriptorFlags.DoublebufferDontCare | Wgl.PixelFormatDescriptorFlags.StereoDontCare;
int pFormat = Wgl.ChoosePixelFormat(DeviceContext, ref pfd);
Debug.Assert(pFormat != 0);
// Get exact description of the pixel format
bool res = Wgl.DescribePixelFormat(DeviceContext, pFormat, (uint)pfd.nSize, ref pfd) != 0;
Debug.Assert(res);
// Set pixel format before creating OpenGL context
res = Wgl.SetPixelFormat(DeviceContext, pFormat, ref pfd);
Debug.Assert(res);
// Create a dummy OpenGL context to retrieve initial informations.
IntPtr rContext = CreateContext(IntPtr.Zero);
Debug.Assert(rContext != IntPtr.Zero);
return rContext;
}
/// <summary>
/// Get the APIs available on this device context. The API tokens are space separated, and they can be
/// found in <see cref="KhronosVersion"/> definition.
/// </summary>
public override IEnumerable<string> AvailableAPIs => GetAvailableApis();
/// <summary>
/// Get the APIs available on the WGL device context.
/// </summary>
/// <returns></returns>
internal static string[] GetAvailableApis()
{
List<string> deviceApi = new List<string> { KhronosVersion.ApiGl };
// OpenGL ES via WGL_EXT_create_context_es(2)?_profile
if (Wgl.CurrentExtensions != null && Wgl.CurrentExtensions.CreateContextEsProfile_EXT) {
deviceApi.Add(KhronosVersion.ApiGles1);
deviceApi.Add(KhronosVersion.ApiGles2);
// OpenGL SC2 is based on OpenGL ES2
deviceApi.Add(KhronosVersion.ApiGlsc2);
}
return deviceApi.ToArray();
}
/// <summary>
/// Creates a context.
/// </summary>
/// <param name="sharedContext">
/// A <see cref="IntPtr"/> that specify a context that will share objects with the returned one. If
/// it is IntPtr.Zero, no sharing is performed.
/// </param>
/// <returns>
/// A <see cref="IntPtr"/> that represents the handle of the created context. If the context cannot be
/// created, it returns IntPtr.Zero.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Exception thrown in the case <paramref name="sharedContext"/> is different from IntPtr.Zero, and the objects
/// cannot be shared with it.
/// </exception>
public override IntPtr CreateContext(IntPtr sharedContext)
{
if (Wgl.CurrentExtensions == null || Wgl.CurrentExtensions.CreateContext_ARB == false) {
IntPtr renderContext = Wgl.CreateContext(DeviceContext);
if (renderContext == IntPtr.Zero)
throw new WglException(Marshal.GetLastWin32Error());
if (sharedContext != IntPtr.Zero) {
bool res = Wgl.ShareLists(renderContext, sharedContext);
if (res == false)
throw new WglException(Marshal.GetLastWin32Error());
}
return renderContext;
} else
return CreateContextAttrib(sharedContext, new[] { Gl.NONE });
}
/// <summary>
/// Creates a context, specifying attributes.
/// </summary>
/// <param name="sharedContext">
/// A <see cref="IntPtr"/> that specify a context that will share objects with the returned one. If
/// it is IntPtr.Zero, no sharing is performed.
/// </param>
/// <param name="attribsList">
/// A <see cref="T:Int32[]"/> that specifies the attributes list.
/// </param>
/// <returns>
/// A <see cref="IntPtr"/> that represents the handle of the created context. If the context cannot be
/// created, it returns IntPtr.Zero.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="attribsList"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Exception thrown if <paramref name="attribsList"/> length is zero or if the last item of <paramref name="attribsList"/>
/// is not zero.
/// </exception>
[RequiredByFeature("WGL_ARB_create_context")]
public override IntPtr CreateContextAttrib(IntPtr sharedContext, int[] attribsList)
{
return CreateContextAttrib(sharedContext, attribsList, new KhronosVersion(1, 0, CurrentAPI));
}
/// <summary>
/// Creates a context, specifying attributes.
/// </summary>
/// <param name="sharedContext">
/// A <see cref="IntPtr"/> that specify a context that will share objects with the returned one. If
/// it is IntPtr.Zero, no sharing is performed.
/// </param>
/// <param name="attribsList">
/// A <see cref="T:Int32[]"/> that specifies the attributes list.
/// </param>
/// <param name="api">
/// A <see cref="KhronosVersion"/> that specifies the API to be implemented by the returned context. It can be null indicating the
/// default API for this DeviceContext implementation. If it is possible, try to determine the API version also.
/// </param>
/// <returns>
/// A <see cref="IntPtr"/> that represents the handle of the created context. If the context cannot be
/// created, it returns IntPtr.Zero.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="attribsList"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// Exception thrown if <paramref name="attribsList"/> length is zero or if the last item of <paramref name="attribsList"/>
/// is not zero.
/// </exception>
[RequiredByFeature("WGL_ARB_create_context")]
public override IntPtr CreateContextAttrib(IntPtr sharedContext, int[] attribsList, KhronosVersion api)
{
if (Wgl.CurrentExtensions != null && Wgl.CurrentExtensions.CreateContext_ARB == false)
throw new InvalidOperationException("WGL_ARB_create_context not supported");
if (attribsList != null && attribsList.Length == 0)
throw new ArgumentException("zero length array", nameof(attribsList));
if (attribsList != null && attribsList[attribsList.Length - 1] != Gl.NONE)
throw new ArgumentException("not zero-terminated array", nameof(attribsList));
// Defaults null attributes
if (attribsList == null)
attribsList = new[] { Gl.NONE };
IntPtr ctx;
if (api != null) {
List<int> adulteredAttribs = new List<int>(attribsList);
// Support check
switch (api.Api) {
case KhronosVersion.ApiGl:
break;
case KhronosVersion.ApiGles1:
case KhronosVersion.ApiGles2:
case KhronosVersion.ApiGlsc2:
if (Wgl.CurrentExtensions != null && Wgl.CurrentExtensions.CreateContextEsProfile_EXT == false)
throw new NotSupportedException("OpenGL ES API not supported");
break;
default:
throw new NotSupportedException($"'{api.Api}' API not supported");
}
// Remove trailing 0
if (adulteredAttribs.Count > 0 && adulteredAttribs[adulteredAttribs.Count - 1] == Gl.NONE)
adulteredAttribs.RemoveAt(adulteredAttribs.Count - 1);
// Add required attributes
int major = api.Major, minor = api.Minor, profileMask = 0;
switch (api.Api) {
case KhronosVersion.ApiGl:
switch (api.Profile) {
case KhronosVersion.ProfileCompatibility:
profileMask |= (int)Wgl.CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
break;
case KhronosVersion.ProfileCore:
profileMask |= (int)Wgl.CONTEXT_CORE_PROFILE_BIT_ARB;
break;
case null:
// No specific profile required, leaving the default (core profile)
break;
default:
throw new NotSupportedException($"'{api.Profile}' Profile not supported");
}
break;
case KhronosVersion.ApiGles1:
// Ignore API version: force always to 1.0
major = 1;
minor = 0;
profileMask |= (int)Wgl.CONTEXT_ES_PROFILE_BIT_EXT;
break;
case KhronosVersion.ApiGles2:
case KhronosVersion.ApiGlsc2:
major = 2;
minor = 0;
profileMask |= (int)Wgl.CONTEXT_ES_PROFILE_BIT_EXT;
break;
default:
throw new NotSupportedException($"'{api.Api}' API not supported");
}
// Add/Replace attributes
int majorVersionIndex, minorVersionIndex;
if ((majorVersionIndex = adulteredAttribs.FindIndex(item => item == Wgl.CONTEXT_MAJOR_VERSION_ARB)) >= 0)
adulteredAttribs[majorVersionIndex + 1] = major;
else
adulteredAttribs.AddRange(new[] { Wgl.CONTEXT_MAJOR_VERSION_ARB, major });
if ((minorVersionIndex = adulteredAttribs.FindIndex(item => item == Wgl.CONTEXT_MINOR_VERSION_ARB)) >= 0)
adulteredAttribs[minorVersionIndex + 1] = minor;
else
adulteredAttribs.AddRange(new[] { Wgl.CONTEXT_MINOR_VERSION_ARB, api.Minor });
if (profileMask != 0) {
int profileMaskIndex;
if ((profileMaskIndex = adulteredAttribs.FindIndex(item => item == Wgl.CONTEXT_PROFILE_MASK_ARB)) >= 0)
adulteredAttribs[profileMaskIndex + 1] = profileMask;
else
adulteredAttribs.AddRange(new[] { Wgl.CONTEXT_PROFILE_MASK_ARB, profileMask });
}
// Restore trailing 0
adulteredAttribs.Add(Gl.NONE);
ctx = Wgl.CreateContextAttribsARB(DeviceContext, sharedContext, adulteredAttribs.ToArray());
} else
ctx = Wgl.CreateContextAttribsARB(DeviceContext, sharedContext, attribsList);
if (ctx == IntPtr.Zero)
throw new WglException(Marshal.GetLastWin32Error());
return (ctx);
}
/// <summary>
/// Makes the context current on the calling thread.
/// </summary>
/// <param name="ctx">
/// A <see cref="IntPtr"/> that specify the context to be current on the calling thread, bound to
/// thise device context. It can be IntPtr.Zero indicating that no context will be current.
/// </param>
/// <returns>
/// It returns a boolean value indicating whether the operation was successful.
/// </returns>
/// <exception cref="NotSupportedException">
/// Exception thrown if the current platform is not supported.
/// </exception>
public override bool MakeCurrent(IntPtr ctx)
{
// Avoid actual call to wglMakeCurrent if it is not necessary
// Efficient on simple/nominal applications
IntPtr currentContext = Wgl.GetCurrentContext(), currentDc = Wgl.GetCurrentDC();
if (ctx == currentContext && DeviceContext == currentDc)
return true;
// Base implementation
return base.MakeCurrent(ctx);
}
/// <summary>
/// Makes the context current on the calling thread.
/// </summary>
/// <param name="ctx">
/// A <see cref="IntPtr"/> that specify the context to be current on the calling thread, bound to
/// thise device context. It can be IntPtr.Zero indicating that no context will be current.
/// </param>
/// <returns>
/// It returns a boolean value indicating whether the operation was successful.
/// </returns>
/// <exception cref="NotSupportedException">
/// Exception thrown if the current platform is not supported.
/// </exception>
protected override bool MakeCurrentCore(IntPtr ctx)
{
return Wgl.MakeCurrent(DeviceContext, ctx);
}
/// <summary>
/// Deletes a context.
/// </summary>
/// <param name="ctx">
/// A <see cref="IntPtr"/> that specify the context to be deleted.
/// </param>
/// <returns>
/// It returns a boolean value indicating whether the operation was successful. If it returns false,
/// query the exception by calling <see cref="GetPlatformException"/>.
/// </returns>
/// <remarks>
/// <para>The context <paramref name="ctx"/> must not be current on any thread.</para>
/// </remarks>
/// <exception cref="ArgumentException">
/// Exception thrown if <paramref name="ctx"/> is IntPtr.Zero.
/// </exception>
public override bool DeleteContext(IntPtr ctx)
{
if (ctx == IntPtr.Zero)
throw new ArgumentException("ctx");
return Wgl.DeleteContext(ctx);
}
/// <summary>
/// Swap the buffers of a device.
/// </summary>
public override void SwapBuffers()
{
Wgl.UnsafeNativeMethods.GdiSwapBuffersFast(DeviceContext);
}
/// <summary>
/// Control the the buffers swap of a device.
/// </summary>
/// <param name="interval">
/// A <see cref="System.Int32"/> that specifies the minimum number of video frames that are displayed
/// before a buffer swap will occur.
/// </param>
/// <returns>
/// It returns a boolean value indicating whether the operation was successful.
/// </returns>
[RequiredByFeature("WGL_EXT_swap_control")]
public override bool SwapInterval(int interval)
{
if (Wgl.CurrentExtensions.SwapControl_EXT == false)
throw new InvalidOperationException("WGL_EXT_swap_control not supported");
if (interval == -1 && Wgl.CurrentExtensions.SwapControlTear_EXT == false)
throw new InvalidOperationException("WGL_EXT_swap_control_tear not supported");
return Wgl.SwapIntervalEXT(interval);
}
/// <summary>
/// Query platform extensions available.
/// </summary>
internal override void QueryPlatformExtensions()
{
Wgl.CurrentExtensions = new Wgl.Extensions();
Wgl.CurrentExtensions.Query(this);
}
/// <summary>
/// Gets the platform exception relative to the last operation performed.
/// </summary>
/// <returns>
/// The platform exception relative to the last operation performed.
/// </returns>
[SuppressMessage("Microsoft.Interoperability", "CA1404:CallGetLastErrorImmediatelyAfterPInvoke")]
public override Exception GetPlatformException()
{
return GetPlatformExceptionCore();
}
/// <summary>
/// Gets the platform exception relative to the last operation performed.
/// </summary>
/// <returns>
/// The platform exception relative to the last operation performed.
/// </returns>
internal static Exception GetPlatformExceptionCore()
{
Exception platformException = null;
int win32Error = Marshal.GetLastWin32Error();
if (win32Error != 0)
platformException = new Win32Exception(win32Error);
return platformException;
}
/// <summary>
/// Get the pixel formats supported by this device.
/// </summary>
public override DevicePixelFormatCollection PixelsFormats
{
get
{
// Use cached pixel formats
if (_PixelFormatCache != null)
return _PixelFormatCache;
// Query pixel formats
_PixelFormatCache = Wgl.CurrentExtensions != null && Wgl.CurrentExtensions.PixelFormat_ARB ? GetPixelFormats_ARB_pixel_format(Wgl.CurrentExtensions) : GetPixelFormats_Win32();
return _PixelFormatCache;
}
}
[RequiredByFeature("WGL_ARB_pixel_format")]
private DevicePixelFormatCollection GetPixelFormats_ARB_pixel_format(Wgl.Extensions wglExtensions)
{
// Get the number of pixel formats
int[] countFormatAttribsCodes = { Wgl.NUMBER_PIXEL_FORMATS_ARB };
int[] countFormatAttribsValues = new int[countFormatAttribsCodes.Length];
Wgl.GetPixelFormatAttribARB(DeviceContext, 1, 0, (uint)countFormatAttribsCodes.Length, countFormatAttribsCodes, countFormatAttribsValues);
// Request configurations
List<int> pixelFormatAttribsCodes = new List<int>(12)
{
Wgl.SUPPORT_OPENGL_ARB, // Required to be Gl.TRUE
Wgl.ACCELERATION_ARB, // Required to be Wgl.FULL_ACCELERATION or Wgl.ACCELERATION_ARB
Wgl.PIXEL_TYPE_ARB,
Wgl.DRAW_TO_WINDOW_ARB,
Wgl.DRAW_TO_BITMAP_ARB,
Wgl.DOUBLE_BUFFER_ARB,
Wgl.SWAP_METHOD_ARB,
Wgl.STEREO_ARB,
Wgl.COLOR_BITS_ARB,
Wgl.DEPTH_BITS_ARB,
Wgl.STENCIL_BITS_ARB
};
#if SUPPORT_MULTISAMPLE
// Multisample extension
if (wglExtensions.Multisample_ARB || wglExtensions.Multisample_EXT) {
pixelFormatAttribsCodes.Add(Wgl.SAMPLE_BUFFERS_ARB);
pixelFormatAttribsCodes.Add(Wgl.SAMPLES_ARB);
}
int pixelFormatAttribMultisampleIndex = pixelFormatAttribsCodes.Count - 1;
#endif
#if SUPPORT_PBUFFER
if (wglExtensions.Pbuffer_ARB || wglExtensions.Pbuffer_EXT) {
pixelFormatAttribsCodes.Add(Wgl.DRAW_TO_PBUFFER_ARB);
}
int pixelFormatAttribPBufferIndex = pixelFormatAttribsCodes.Count - 1;
#endif
#if SUPPORT_FRAMEBUFFER_SRGB
// Framebuffer sRGB extension
if (wglExtensions.FramebufferSRGB_ARB || wglExtensions.FramebufferSRGB_EXT)
pixelFormatAttribsCodes.Add(Wgl.FRAMEBUFFER_SRGB_CAPABLE_ARB);
int pixelFormatAttribFramebufferSrgbIndex = pixelFormatAttribsCodes.Count - 1;
#endif
// Create pixel format collection
DevicePixelFormatCollection pixelFormats = new DevicePixelFormatCollection();
// Retrieve information about available pixel formats
int[] pixelFormatAttribValues = new int[pixelFormatAttribsCodes.Count];
for (int pixelFormatIndex = 1; pixelFormatIndex < countFormatAttribsValues[0]; pixelFormatIndex++) {
DevicePixelFormat pixelFormat = new DevicePixelFormat();
Wgl.GetPixelFormatAttribARB(DeviceContext, pixelFormatIndex, 0, (uint)pixelFormatAttribsCodes.Count, pixelFormatAttribsCodes.ToArray(), pixelFormatAttribValues);
// Check minimum requirements
if (pixelFormatAttribValues[0] != Gl.TRUE)
continue; // No OpenGL support
if (pixelFormatAttribValues[1] != Wgl.FULL_ACCELERATION_ARB)
continue; // No hardware acceleration
switch (pixelFormatAttribValues[2]) {
case Wgl.TYPE_RGBA_ARB:
#if SUPPORT_PIXEL_FORMAT_FLOAT
case Wgl.TYPE_RGBA_FLOAT_ARB:
#endif
#if SUPPORT_PIXEL_FORMAT_PACKED_FLOAT
case Wgl.TYPE_RGBA_UNSIGNED_FLOAT_EXT:
#endif
break;
default:
continue; // Ignored pixel type
}
// Collect pixel format attributes
pixelFormat.FormatIndex = pixelFormatIndex;
switch (pixelFormatAttribValues[2]) {
case Wgl.TYPE_RGBA_ARB:
pixelFormat.RgbaUnsigned = true;
break;
case Wgl.TYPE_RGBA_FLOAT_ARB:
pixelFormat.RgbaFloat = true;
break;
case Wgl.TYPE_RGBA_UNSIGNED_FLOAT_EXT:
pixelFormat.RgbaFloat = pixelFormat.RgbaUnsigned = true;
break;
}
pixelFormat.RenderWindow = pixelFormatAttribValues[3] == Gl.TRUE;
pixelFormat.RenderBuffer = pixelFormatAttribValues[4] == Gl.TRUE;
pixelFormat.DoubleBuffer = pixelFormatAttribValues[5] == Gl.TRUE;
pixelFormat.SwapMethod = pixelFormatAttribValues[6];
pixelFormat.StereoBuffer = pixelFormatAttribValues[7] == Gl.TRUE;
pixelFormat.ColorBits = pixelFormatAttribValues[8];
pixelFormat.DepthBits = pixelFormatAttribValues[9];
pixelFormat.StencilBits = pixelFormatAttribValues[10];
#if SUPPORT_MULTISAMPLE
if (wglExtensions.Multisample_ARB || wglExtensions.Multisample_EXT) {
Debug.Assert(pixelFormatAttribMultisampleIndex >= 0);
pixelFormat.MultisampleBits = pixelFormatAttribValues[pixelFormatAttribMultisampleIndex];
}
#endif
#if SUPPORT_PBUFFER
if (wglExtensions.Pbuffer_ARB || wglExtensions.Pbuffer_EXT) {
Debug.Assert(pixelFormatAttribPBufferIndex >= 0);
pixelFormat.RenderPBuffer = pixelFormatAttribValues[pixelFormatAttribPBufferIndex] == Gl.TRUE;
}
#endif
#if SUPPORT_FRAMEBUFFER_SRGB
if (wglExtensions.FramebufferSRGB_ARB || wglExtensions.FramebufferSRGB_EXT) {
Debug.Assert(pixelFormatAttribFramebufferSrgbIndex >= 0);
pixelFormat.SRGBCapable = pixelFormatAttribValues[pixelFormatAttribFramebufferSrgbIndex] != 0;
}
#endif
pixelFormats.Add(pixelFormat);
}
return pixelFormats;
}
private DevicePixelFormatCollection GetPixelFormats_Win32()
{
DevicePixelFormatCollection pixelFormats = new DevicePixelFormatCollection();
Wgl.PIXELFORMATDESCRIPTOR pixelDescr = new Wgl.PIXELFORMATDESCRIPTOR();
int pixelFormatsCount = Wgl.DescribePixelFormat(DeviceContext, 0, 0, ref pixelDescr);
for (int i = 1; i <= pixelFormatsCount; i++) {
Wgl.DescribePixelFormat(DeviceContext, i, (uint)Marshal.SizeOf(typeof(Wgl.PIXELFORMATDESCRIPTOR)), ref pixelDescr);
if ((pixelDescr.dwFlags & Wgl.PixelFormatDescriptorFlags.SupportOpenGL) == 0)
continue;
DevicePixelFormat pixelFormat = new DevicePixelFormat
{
FormatIndex = i,
RgbaUnsigned = true,
RgbaFloat = false,
RenderWindow = true,
RenderBuffer = false,
DoubleBuffer = (pixelDescr.dwFlags & Wgl.PixelFormatDescriptorFlags.Doublebuffer) != 0,
SwapMethod = 0,
StereoBuffer = (pixelDescr.dwFlags & Wgl.PixelFormatDescriptorFlags.Stereo) != 0,
ColorBits = pixelDescr.cColorBits,
DepthBits = pixelDescr.cDepthBits,
StencilBits = pixelDescr.cStencilBits,
MultisampleBits = 0,
RenderPBuffer = false,
SRGBCapable = false
};
pixelFormats.Add(pixelFormat);
}
return pixelFormats;
}
/// <summary>
/// Pixel formats available on this DeviceContext (cache).
/// </summary>
private DevicePixelFormatCollection _PixelFormatCache;
/// <summary>
/// Set the device pixel format.
/// </summary>
/// <param name="pixelFormat">
/// A <see cref="DevicePixelFormat"/> that specifies the pixel format to set.
/// </param>
public override void ChoosePixelFormat(DevicePixelFormat pixelFormat)
{
if (pixelFormat == null)
throw new ArgumentNullException(nameof(pixelFormat));
if (IsPixelFormatSet)
throw new InvalidOperationException("pixel format already set");
// Choose pixel format
int pixelFormatIndex = ChoosePixelFormat(DeviceContext, pixelFormat);
// Set choosen pixel format
Wgl.PIXELFORMATDESCRIPTOR pDescriptor = new Wgl.PIXELFORMATDESCRIPTOR();
if (Wgl.SetPixelFormat(DeviceContext, pixelFormatIndex, ref pDescriptor) == false)
throw new InvalidOperationException("unable to set pixel format", GetPlatformException());
IsPixelFormatSet = true;
}
/// <summary>
/// Set the device pixel format.
/// </summary>
/// <param name="pixelFormat">
/// A <see cref="DevicePixelFormat"/> that specifies the pixel format to set.
/// </param>
private static int ChoosePixelFormat(IntPtr deviceContext, DevicePixelFormat pixelFormat)
{
if (pixelFormat == null)
throw new ArgumentNullException(nameof(pixelFormat));
List<int> attribIList = new List<int>();
uint[] countFormatAttribsValues = new uint[1];
int[] choosenFormats = new int[4];
attribIList.AddRange(new[] { Wgl.SUPPORT_OPENGL_ARB, Gl.TRUE });
if (pixelFormat.RenderWindow)
attribIList.AddRange(new[] { Wgl.DRAW_TO_WINDOW_ARB, Gl.TRUE });
if (pixelFormat.RenderPBuffer)
attribIList.AddRange(new[] { Wgl.DRAW_TO_PBUFFER_ARB, Gl.TRUE });
if (pixelFormat.RgbaUnsigned)
attribIList.AddRange(new[] { Wgl.PIXEL_TYPE_ARB, Wgl.TYPE_RGBA_ARB });
if (pixelFormat.RgbaFloat)
attribIList.AddRange(new[] { Wgl.PIXEL_TYPE_ARB, Wgl.TYPE_RGBA_FLOAT_ARB });
if (pixelFormat.ColorBits > 0)
attribIList.AddRange(new[] { Wgl.COLOR_BITS_ARB, pixelFormat.ColorBits });
if (pixelFormat.DepthBits > 0)
attribIList.AddRange(new[] { Wgl.DEPTH_BITS_ARB, pixelFormat.DepthBits });
if (pixelFormat.StencilBits > 0)
attribIList.AddRange(new[] { Wgl.STENCIL_BITS_ARB, pixelFormat.StencilBits });
if (pixelFormat.DoubleBuffer)
attribIList.AddRange(new[] { Wgl.DOUBLE_BUFFER_ARB, 1 });
attribIList.Add(0);
// Let choose pixel formats
if (!Wgl.ChoosePixelFormatARB(deviceContext, attribIList.ToArray(), new List<float>().ToArray(), (uint)choosenFormats.Length, choosenFormats, countFormatAttribsValues))
throw new InvalidOperationException("unable to choose pixel format", GetPlatformExceptionCore());
return choosenFormats[0];
}
/// <summary>
/// Set the device pixel format.
/// </summary>
/// <param name="pixelFormat">
/// A <see cref="DevicePixelFormat"/> that specifies the pixel format to set.
/// </param>
/// <exception cref="ArgumentNullException">
/// Exception thrown if <paramref name="pixelFormat"/> is null.
/// </exception>
public override void SetPixelFormat(DevicePixelFormat pixelFormat)
{
if (pixelFormat == null)
throw new ArgumentNullException(nameof(pixelFormat));
if (IsPixelFormatSet)
throw new InvalidOperationException("pixel format already set");
#if CHOOSE_PIXEL_FORMAT_FALLBACK
try {
#endif
Wgl.PIXELFORMATDESCRIPTOR pDescriptor = new Wgl.PIXELFORMATDESCRIPTOR();
// Note (from MSDN): Setting the pixel format of a window more than once can lead to significant complications for the Window Manager
// and for multithread applications, so it is not allowed. An application can only set the pixel format of a window one time. Once a
// window's pixel format is set, it cannot be changed.
if (Wgl.DescribePixelFormat(DeviceContext, pixelFormat.FormatIndex, (uint)pDescriptor.nSize, ref pDescriptor) == 0)
throw new InvalidOperationException($"unable to describe pixel format {pixelFormat.FormatIndex}", GetPlatformException());
// Set choosen pixel format
if (!Wgl.SetPixelFormat(DeviceContext, pixelFormat.FormatIndex, ref pDescriptor))
throw new InvalidOperationException($"unable to set pixel format {pixelFormat.FormatIndex}", GetPlatformException());
#if CHOOSE_PIXEL_FORMAT_FALLBACK
} catch (InvalidOperationException) {
// Try using default ChoosePixelFormat*
SetDisplayablePixelFormat(pixelFormat);
}
#endif
IsPixelFormatSet = true;
}
#if CHOOSE_PIXEL_FORMAT_FALLBACK
/// <summary>
/// Set pixel format by letting the driver choose the best pixel format following the criteria.
/// </summary>
/// <param name="pixelFormat">
///
/// </param>
private void SetDisplayablePixelFormat(DevicePixelFormat pixelFormat)
{
if (pixelFormat == null)
throw new ArgumentNullException("pixelFormat");
List<int> attribIList = new List<int>();
List<float> attribFList = new List<float>();
Wgl.PIXELFORMATDESCRIPTOR pDescriptor = new Wgl.PIXELFORMATDESCRIPTOR();
uint[] countFormatAttribsValues = new uint[1];
int[] choosenFormats = new int[4];
// Let choose pixel formats
if (!Wgl.ChoosePixelFormatARB(_DeviceContext, attribIList.ToArray(), attribFList.ToArray(), (uint)choosenFormats.Length, choosenFormats, countFormatAttribsValues)) {
Win32Exception innerException = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(String.Format("unable to choose pixel format: {0}", innerException.Message), innerException);
}
// Set choosen pixel format
if (Wgl.SetPixelFormat(_DeviceContext, choosenFormats[0], ref pDescriptor) == false) {
Win32Exception innerException = new Win32Exception(Marshal.GetLastWin32Error());
throw new InvalidOperationException(String.Format("unable to set pixel format {0}: {1}", pixelFormat.FormatIndex, innerException.Message), innerException);
}
}
#endif
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting managed/unmanaged resources.
/// </summary>
/// <param name="disposing">
/// A <see cref="System.Boolean"/> indicating whether the disposition is requested explictly.
/// </param>
protected override void Dispose(bool disposing)
{
if (disposing) {
// Release device context
if (DeviceContext != IntPtr.Zero) {
if (_DeviceContextPBuffer == false) {
bool res = Wgl.ReleaseDC(_WindowHandle, DeviceContext);
Debug.Assert(res);
} else {
int res = Wgl.ReleasePbufferDCARB(_WindowHandle, DeviceContext);
Debug.Assert(res == 1);
}
DeviceContext = IntPtr.Zero;
_WindowHandle = IntPtr.Zero;
}
}
// Base implementation
base.Dispose(disposing);
}
#endregion
}
}
| |
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 RealMocking.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;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using Microsoft.Extensions.Logging;
using mvc5.Models;
using mvc5.Services;
using mvc5.ViewModels.Account;
namespace mvc5.Controllers
{
[Authorize]
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<AccountController>();
}
//
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning(2, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[HttpGet]
[AllowAnonymous]
public IActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
// "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User created a new account with password.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LogOff()
{
await _signInManager.SignOutAsync();
_logger.LogInformation(4, "User logged out.");
return RedirectToAction(nameof(HomeController.Index), "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
{
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction(nameof(Login));
}
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (User.IsSignedIn())
{
return RedirectToAction(nameof(ManageController.Index), "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
result = await _userManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await _userManager.GeneratePasswordResetTokenAsync(user);
//var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
//await _emailSender.SendEmailAsync(model.Email, "Reset Password",
// "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
//return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await _userManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
_logger.LogWarning(7, "User account locked out.");
return View("Lockout");
}
else
{
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Home");
}
}
#endregion
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using Axiom.Core;
using Axiom.Configuration;
namespace Axiom.Graphics {
///<summary>
/// Class representing a Compositor object. Compositors provide the means
/// to flexibly "composite" the final rendering result from multiple scene renders
/// and intermediate operations like rendering fullscreen quads. This makes
/// it possible to apply postfilter effects, HDRI postprocessing, and shadow
/// effects to a Viewport.
///</summary>
public class Compositor : Resource {
#region Fields
protected List<CompositionTechnique> techniques;
protected List<CompositionTechnique> supportedTechniques;
///<summary>
/// This is set if the techniques change and the supportedness of techniques has to be
/// re-evaluated.
///</summary>
protected bool compilationRequired;
/// <summary>
/// Auto incrementing number for creating unique names.
/// </summary>
static protected int autoNumber;
#endregion Fields
#region Constructors
public Compositor(string name) {
techniques = new List<CompositionTechnique>();
supportedTechniques = new List<CompositionTechnique>();
this.name = name;
this.compilationRequired = true;
}
public Compositor() {
techniques = new List<CompositionTechnique>();
supportedTechniques = new List<CompositionTechnique>();
this.name = String.Format("_Compositor{0}", autoNumber++);
this.compilationRequired = true;
}
#endregion Constructors
#region Properties
public List<CompositionTechnique> Techniques {
get { return techniques; }
}
public List<CompositionTechnique> SupportedTechniques {
get { return supportedTechniques; }
}
#endregion Properties
#region Implementation of Resource
public override void Preload() {
if (!isLoaded) {
// compile if needed
if (compilationRequired)
Compile();
}
}
/// <summary>
/// Overridden from Resource.
/// </summary>
/// <remarks>
/// By default, Materials are not loaded, and adding additional textures etc do not cause those
/// textures to be loaded. When the <code>Load</code> method is called, all textures are loaded (if they
/// are not already), GPU programs are created if applicable, and Controllers are instantiated.
/// Once a material has been loaded, all changes made to it are immediately loaded too
/// </remarks>
protected override void LoadImpl() {
// compile if needed
if(compilationRequired)
Compile();
}
protected override void UnloadImpl() {
}
/// <summary>
/// Disposes of any resources used by this object.
/// </summary>
public override void Dispose() {
RemoveAllTechniques();
Unload();
}
/// <summary>
/// Overridden to ensure a recompile occurs if needed before use.
/// </summary>
public override void Touch() {
if(compilationRequired) {
Compile();
}
// call base class
base.Touch();
}
#endregion
#region Methods
///<summary>
/// Create a new technique, and return a pointer to it.
///</summary
public CompositionTechnique CreateTechnique() {
CompositionTechnique t = new CompositionTechnique(this);
techniques.Add(t);
compilationRequired = true;
return t;
}
///<summary>
/// Remove a technique.
///</summary
public void RemoveTechnique(int idx) {
techniques.RemoveAt(idx);
supportedTechniques.Clear();
compilationRequired = true;
}
///<summary>
/// Get a technique.
///</summary
public CompositionTechnique GetTechnique(int idx) {
return techniques[idx];
}
///<summary>
/// Get a supported technique.
///</summary
///<remarks>
/// The supported technique list is only available after this compositor has been compiled,
/// which typically happens on loading it. Therefore, if this method returns
/// an empty list, try calling Compositor.Load.
///</remarks>
public CompositionTechnique GetSupportedTechnique(int idx) {
return supportedTechniques[idx];
}
///<summary>
/// Remove all techniques.
///</summary
public void RemoveAllTechniques() {
techniques.Clear();
supportedTechniques.Clear();
compilationRequired = true;
}
///<summary>
/// Check supportedness of techniques.
///</summary
protected void Compile() {
/// Sift out supported techniques
supportedTechniques.Clear();
// Try looking for exact technique support with no texture fallback
foreach (CompositionTechnique t in techniques) {
// Look for exact texture support first
if(t.IsSupported(false))
supportedTechniques.Add(t);
}
if (supportedTechniques.Count == 0) {
// Check again, being more lenient with textures
foreach (CompositionTechnique t in techniques) {
// Allow texture support with degraded pixel format
if(t.IsSupported(true))
supportedTechniques.Add(t);
}
}
compilationRequired = false;
}
#endregion Methods
}
}
| |
// 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.Azure.AcceptanceTestsAzureSpecials
{
using Fixtures.Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SkipUrlEncodingOperations.
/// </summary>
public static partial class SkipUrlEncodingOperationsExtensions
{
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetMethodPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
operations.GetMethodPathValidAsync(unencodedPathParam).GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodPathValidAsync(this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.GetMethodPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
public static void GetPathPathValid(this ISkipUrlEncodingOperations operations, string unencodedPathParam)
{
operations.GetPathPathValidAsync(unencodedPathParam).GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='unencodedPathParam'>
/// Unencoded path parameter with value 'path1/path2/path3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetPathPathValidAsync(this ISkipUrlEncodingOperations operations, string unencodedPathParam, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.GetPathPathValidWithHttpMessagesAsync(unencodedPathParam, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void GetSwaggerPathValid(this ISkipUrlEncodingOperations operations)
{
operations.GetSwaggerPathValidAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded path parameter with value 'path1/path2/path3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetSwaggerPathValidAsync(this ISkipUrlEncodingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.GetSwaggerPathValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetMethodQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
operations.GetMethodQueryValidAsync(q1).GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodQueryValidAsync(this ISkipUrlEncodingOperations operations, string q1, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.GetMethodQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
public static void GetMethodQueryNull(this ISkipUrlEncodingOperations operations, string q1 = default(string))
{
operations.GetMethodQueryNullAsync(q1).GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value null
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value null
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetMethodQueryNullAsync(this ISkipUrlEncodingOperations operations, string q1 = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.GetMethodQueryNullWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
public static void GetPathQueryValid(this ISkipUrlEncodingOperations operations, string q1)
{
operations.GetPathQueryValidAsync(q1).GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='q1'>
/// Unencoded query parameter with value 'value1&q2=value2&q3=value3'
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetPathQueryValidAsync(this ISkipUrlEncodingOperations operations, string q1, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.GetPathQueryValidWithHttpMessagesAsync(q1, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void GetSwaggerQueryValid(this ISkipUrlEncodingOperations operations)
{
operations.GetSwaggerQueryValidAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Get method with unencoded query parameter with value
/// 'value1&q2=value2&q3=value3'
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task GetSwaggerQueryValidAsync(this ISkipUrlEncodingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.GetSwaggerQueryValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)).Dispose();
}
}
}
| |
//-----------------------------------------------------------------------------
// CurveControl.designer.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace Xna.Tools
{
partial class CurveControl
{
/// <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.menuStrip = new System.Windows.Forms.MenuStrip();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.frameAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.frameSelectionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.autoFrameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.curveSmoothnessToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.coarseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.roughToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.mediumToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.keysToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.alwaysToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.neverToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.activeOnlyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tangentsToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.alwaysToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.neverToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.activeOnlyToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.infinityToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.curvesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.preInfinityToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cycleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cycleWithOffsetToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.oscillateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.linearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.constantToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.postInfinityToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cycleToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.cycleWithOffsetToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.oscillateToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.linearToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.constantToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.tangentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.smoothToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.linearToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.steppedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.flatToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fixedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.inTangentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.smoothToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.linearToolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem();
this.flatToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.fixedToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.outTangentToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.smoothToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.linearToolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem();
this.flatToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.fixedToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.BottomToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.TopToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.RightToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.LeftToolStripPanel = new System.Windows.Forms.ToolStripPanel();
this.ContentPanel = new System.Windows.Forms.ToolStripContentPanel();
this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.toolStrip = new System.Windows.Forms.ToolStrip();
this.selectionButton = new System.Windows.Forms.ToolStripButton();
this.addKeyButton = new System.Windows.Forms.ToolStripButton();
this.moveKeyButton = new System.Windows.Forms.ToolStripButton();
this.panButton = new System.Windows.Forms.ToolStripButton();
this.zoomButton = new System.Windows.Forms.ToolStripButton();
this.keyPositionLabel = new System.Windows.Forms.ToolStripLabel();
this.keyPositionTextBox = new System.Windows.Forms.ToolStripTextBox();
this.keyValueLabel = new System.Windows.Forms.ToolStripLabel();
this.keyValueTextBox = new System.Windows.Forms.ToolStripTextBox();
this.curveView = new Xna.Tools.GridControl();
this.menuStrip.SuspendLayout();
this.toolStripContainer1.ContentPanel.SuspendLayout();
this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
this.toolStripContainer1.SuspendLayout();
this.toolStrip.SuspendLayout();
this.SuspendLayout();
//
// menuStrip
//
this.menuStrip.Dock = System.Windows.Forms.DockStyle.None;
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.editToolStripMenuItem,
this.viewToolStripMenuItem,
this.curvesToolStripMenuItem,
this.tangentsToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(464, 24);
this.menuStrip.TabIndex = 0;
this.menuStrip.Text = "menuStrip1";
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.undoToolStripMenuItem,
this.redoToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20);
this.editToolStripMenuItem.Text = "&Edit";
//
// undoToolStripMenuItem
//
this.undoToolStripMenuItem.Enabled = false;
this.undoToolStripMenuItem.Name = "undoToolStripMenuItem";
this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z)));
this.undoToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.undoToolStripMenuItem.Text = "Undo";
this.undoToolStripMenuItem.Click += new System.EventHandler(this.undoRedoToolStripMenuItems_Click);
//
// redoToolStripMenuItem
//
this.redoToolStripMenuItem.Enabled = false;
this.redoToolStripMenuItem.Name = "redoToolStripMenuItem";
this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Y)));
this.redoToolStripMenuItem.Size = new System.Drawing.Size(144, 22);
this.redoToolStripMenuItem.Text = "Redo";
this.redoToolStripMenuItem.Click += new System.EventHandler(this.undoRedoToolStripMenuItems_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.frameAllToolStripMenuItem,
this.frameSelectionToolStripMenuItem,
this.autoFrameToolStripMenuItem,
this.toolStripMenuItem2,
this.curveSmoothnessToolStripMenuItem,
this.keysToolStripMenuItem,
this.tangentsToolStripMenuItem1,
this.infinityToolStripMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
this.viewToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
this.viewToolStripMenuItem.Text = "&View";
//
// frameAllToolStripMenuItem
//
this.frameAllToolStripMenuItem.Name = "frameAllToolStripMenuItem";
this.frameAllToolStripMenuItem.ShortcutKeyDisplayString = "F";
this.frameAllToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
this.frameAllToolStripMenuItem.Text = "Frame &All";
this.frameAllToolStripMenuItem.Click += new System.EventHandler(this.frameAllToolStripMenuItem_Click);
//
// frameSelectionToolStripMenuItem
//
this.frameSelectionToolStripMenuItem.Name = "frameSelectionToolStripMenuItem";
this.frameSelectionToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
this.frameSelectionToolStripMenuItem.Text = "&Frame Selection";
this.frameSelectionToolStripMenuItem.Click += new System.EventHandler(this.frameSelectionToolStripMenuItem_Click);
//
// autoFrameToolStripMenuItem
//
this.autoFrameToolStripMenuItem.Name = "autoFrameToolStripMenuItem";
this.autoFrameToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
this.autoFrameToolStripMenuItem.Text = "Aut&o Frame";
this.autoFrameToolStripMenuItem.Click += new System.EventHandler(this.autoFrameToolStripMenuItem_Click);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(170, 6);
//
// curveSmoothnessToolStripMenuItem
//
this.curveSmoothnessToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.coarseToolStripMenuItem,
this.roughToolStripMenuItem,
this.mediumToolStripMenuItem,
this.fineToolStripMenuItem});
this.curveSmoothnessToolStripMenuItem.Name = "curveSmoothnessToolStripMenuItem";
this.curveSmoothnessToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
this.curveSmoothnessToolStripMenuItem.Text = "Curve &Smoothness";
//
// coarseToolStripMenuItem
//
this.coarseToolStripMenuItem.Name = "coarseToolStripMenuItem";
this.coarseToolStripMenuItem.Size = new System.Drawing.Size(119, 22);
this.coarseToolStripMenuItem.Tag = "Coarse";
this.coarseToolStripMenuItem.Text = "&Coarse";
this.coarseToolStripMenuItem.Click += new System.EventHandler(this.curveSmoothnessMenuItem_Click);
//
// roughToolStripMenuItem
//
this.roughToolStripMenuItem.Name = "roughToolStripMenuItem";
this.roughToolStripMenuItem.Size = new System.Drawing.Size(119, 22);
this.roughToolStripMenuItem.Tag = "Rough";
this.roughToolStripMenuItem.Text = "&Rough";
this.roughToolStripMenuItem.Click += new System.EventHandler(this.curveSmoothnessMenuItem_Click);
//
// mediumToolStripMenuItem
//
this.mediumToolStripMenuItem.Name = "mediumToolStripMenuItem";
this.mediumToolStripMenuItem.Size = new System.Drawing.Size(119, 22);
this.mediumToolStripMenuItem.Tag = "Medium";
this.mediumToolStripMenuItem.Text = "&Medium";
this.mediumToolStripMenuItem.Click += new System.EventHandler(this.curveSmoothnessMenuItem_Click);
//
// fineToolStripMenuItem
//
this.fineToolStripMenuItem.Checked = true;
this.fineToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.fineToolStripMenuItem.Name = "fineToolStripMenuItem";
this.fineToolStripMenuItem.Size = new System.Drawing.Size(119, 22);
this.fineToolStripMenuItem.Tag = "Fine";
this.fineToolStripMenuItem.Text = "&Fine";
this.fineToolStripMenuItem.Click += new System.EventHandler(this.curveSmoothnessMenuItem_Click);
//
// keysToolStripMenuItem
//
this.keysToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.alwaysToolStripMenuItem,
this.neverToolStripMenuItem,
this.activeOnlyToolStripMenuItem});
this.keysToolStripMenuItem.Name = "keysToolStripMenuItem";
this.keysToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
this.keysToolStripMenuItem.Text = "&Keys";
//
// alwaysToolStripMenuItem
//
this.alwaysToolStripMenuItem.Checked = true;
this.alwaysToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.alwaysToolStripMenuItem.Name = "alwaysToolStripMenuItem";
this.alwaysToolStripMenuItem.Size = new System.Drawing.Size(135, 22);
this.alwaysToolStripMenuItem.Tag = "Always";
this.alwaysToolStripMenuItem.Text = "&Always";
this.alwaysToolStripMenuItem.Click += new System.EventHandler(this.keyViewToolStripMenuItem_Click);
//
// neverToolStripMenuItem
//
this.neverToolStripMenuItem.Name = "neverToolStripMenuItem";
this.neverToolStripMenuItem.Size = new System.Drawing.Size(135, 22);
this.neverToolStripMenuItem.Tag = "Never";
this.neverToolStripMenuItem.Text = "&Never";
this.neverToolStripMenuItem.Click += new System.EventHandler(this.keyViewToolStripMenuItem_Click);
//
// activeOnlyToolStripMenuItem
//
this.activeOnlyToolStripMenuItem.Name = "activeOnlyToolStripMenuItem";
this.activeOnlyToolStripMenuItem.Size = new System.Drawing.Size(135, 22);
this.activeOnlyToolStripMenuItem.Tag = "ActiveOnly";
this.activeOnlyToolStripMenuItem.Text = "A&ctive Only";
this.activeOnlyToolStripMenuItem.Click += new System.EventHandler(this.keyViewToolStripMenuItem_Click);
//
// tangentsToolStripMenuItem1
//
this.tangentsToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.alwaysToolStripMenuItem1,
this.neverToolStripMenuItem1,
this.activeOnlyToolStripMenuItem1});
this.tangentsToolStripMenuItem1.Name = "tangentsToolStripMenuItem1";
this.tangentsToolStripMenuItem1.Size = new System.Drawing.Size(173, 22);
this.tangentsToolStripMenuItem1.Text = "&Tangents";
//
// alwaysToolStripMenuItem1
//
this.alwaysToolStripMenuItem1.Name = "alwaysToolStripMenuItem1";
this.alwaysToolStripMenuItem1.Size = new System.Drawing.Size(135, 22);
this.alwaysToolStripMenuItem1.Tag = "Always";
this.alwaysToolStripMenuItem1.Text = "&Always";
this.alwaysToolStripMenuItem1.Click += new System.EventHandler(this.tangentViewToolStripMenuItem_Click);
//
// neverToolStripMenuItem1
//
this.neverToolStripMenuItem1.Name = "neverToolStripMenuItem1";
this.neverToolStripMenuItem1.Size = new System.Drawing.Size(135, 22);
this.neverToolStripMenuItem1.Tag = "Never";
this.neverToolStripMenuItem1.Text = "&Never";
this.neverToolStripMenuItem1.Click += new System.EventHandler(this.tangentViewToolStripMenuItem_Click);
//
// activeOnlyToolStripMenuItem1
//
this.activeOnlyToolStripMenuItem1.Checked = true;
this.activeOnlyToolStripMenuItem1.CheckState = System.Windows.Forms.CheckState.Checked;
this.activeOnlyToolStripMenuItem1.Name = "activeOnlyToolStripMenuItem1";
this.activeOnlyToolStripMenuItem1.Size = new System.Drawing.Size(135, 22);
this.activeOnlyToolStripMenuItem1.Tag = "ActiveOnly";
this.activeOnlyToolStripMenuItem1.Text = "A&ctive Only";
this.activeOnlyToolStripMenuItem1.Click += new System.EventHandler(this.tangentViewToolStripMenuItem_Click);
//
// infinityToolStripMenuItem
//
this.infinityToolStripMenuItem.Checked = true;
this.infinityToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.infinityToolStripMenuItem.Name = "infinityToolStripMenuItem";
this.infinityToolStripMenuItem.Size = new System.Drawing.Size(173, 22);
this.infinityToolStripMenuItem.Text = "&Infinity";
this.infinityToolStripMenuItem.Click += new System.EventHandler(this.infinityToolStripMenuItem_Click);
//
// curvesToolStripMenuItem
//
this.curvesToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.preInfinityToolStripMenuItem,
this.postInfinityToolStripMenuItem});
this.curvesToolStripMenuItem.Name = "curvesToolStripMenuItem";
this.curvesToolStripMenuItem.Size = new System.Drawing.Size(55, 20);
this.curvesToolStripMenuItem.Text = "&Curves";
//
// preInfinityToolStripMenuItem
//
this.preInfinityToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cycleToolStripMenuItem,
this.cycleWithOffsetToolStripMenuItem,
this.oscillateToolStripMenuItem,
this.linearToolStripMenuItem,
this.constantToolStripMenuItem});
this.preInfinityToolStripMenuItem.Name = "preInfinityToolStripMenuItem";
this.preInfinityToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
this.preInfinityToolStripMenuItem.Text = "&Pre Infinity";
//
// cycleToolStripMenuItem
//
this.cycleToolStripMenuItem.Name = "cycleToolStripMenuItem";
this.cycleToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.cycleToolStripMenuItem.Tag = "Pre,Cycle";
this.cycleToolStripMenuItem.Text = "C&ycle";
this.cycleToolStripMenuItem.Click += new System.EventHandler(this.curveLoopToolStripMenuItem_Click);
//
// cycleWithOffsetToolStripMenuItem
//
this.cycleWithOffsetToolStripMenuItem.Name = "cycleWithOffsetToolStripMenuItem";
this.cycleWithOffsetToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.cycleWithOffsetToolStripMenuItem.Tag = "Pre,CycleOffset";
this.cycleWithOffsetToolStripMenuItem.Text = "Cycle with &Offset";
this.cycleWithOffsetToolStripMenuItem.Click += new System.EventHandler(this.curveLoopToolStripMenuItem_Click);
//
// oscillateToolStripMenuItem
//
this.oscillateToolStripMenuItem.Name = "oscillateToolStripMenuItem";
this.oscillateToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.oscillateToolStripMenuItem.Tag = "Pre,Oscillate";
this.oscillateToolStripMenuItem.Text = "O&scillate";
this.oscillateToolStripMenuItem.Click += new System.EventHandler(this.curveLoopToolStripMenuItem_Click);
//
// linearToolStripMenuItem
//
this.linearToolStripMenuItem.Name = "linearToolStripMenuItem";
this.linearToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.linearToolStripMenuItem.Tag = "Pre,Linear";
this.linearToolStripMenuItem.Text = "&Linear";
this.linearToolStripMenuItem.Click += new System.EventHandler(this.curveLoopToolStripMenuItem_Click);
//
// constantToolStripMenuItem
//
this.constantToolStripMenuItem.Name = "constantToolStripMenuItem";
this.constantToolStripMenuItem.Size = new System.Drawing.Size(164, 22);
this.constantToolStripMenuItem.Tag = "Pre,Constant";
this.constantToolStripMenuItem.Text = "&Constant";
this.constantToolStripMenuItem.Click += new System.EventHandler(this.curveLoopToolStripMenuItem_Click);
//
// postInfinityToolStripMenuItem
//
this.postInfinityToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cycleToolStripMenuItem1,
this.cycleWithOffsetToolStripMenuItem1,
this.oscillateToolStripMenuItem1,
this.linearToolStripMenuItem1,
this.constantToolStripMenuItem1});
this.postInfinityToolStripMenuItem.Name = "postInfinityToolStripMenuItem";
this.postInfinityToolStripMenuItem.Size = new System.Drawing.Size(137, 22);
this.postInfinityToolStripMenuItem.Text = "P&ost Infinity";
//
// cycleToolStripMenuItem1
//
this.cycleToolStripMenuItem1.Name = "cycleToolStripMenuItem1";
this.cycleToolStripMenuItem1.Size = new System.Drawing.Size(164, 22);
this.cycleToolStripMenuItem1.Tag = "Post,Cycle";
this.cycleToolStripMenuItem1.Text = "C&ycle";
this.cycleToolStripMenuItem1.Click += new System.EventHandler(this.curveLoopToolStripMenuItem_Click);
//
// cycleWithOffsetToolStripMenuItem1
//
this.cycleWithOffsetToolStripMenuItem1.Name = "cycleWithOffsetToolStripMenuItem1";
this.cycleWithOffsetToolStripMenuItem1.Size = new System.Drawing.Size(164, 22);
this.cycleWithOffsetToolStripMenuItem1.Tag = "Post,CycleOffset";
this.cycleWithOffsetToolStripMenuItem1.Text = "Cycle with &Offset";
this.cycleWithOffsetToolStripMenuItem1.Click += new System.EventHandler(this.curveLoopToolStripMenuItem_Click);
//
// oscillateToolStripMenuItem1
//
this.oscillateToolStripMenuItem1.Name = "oscillateToolStripMenuItem1";
this.oscillateToolStripMenuItem1.Size = new System.Drawing.Size(164, 22);
this.oscillateToolStripMenuItem1.Tag = "Post,Oscillate";
this.oscillateToolStripMenuItem1.Text = "O&scillate";
this.oscillateToolStripMenuItem1.Click += new System.EventHandler(this.curveLoopToolStripMenuItem_Click);
//
// linearToolStripMenuItem1
//
this.linearToolStripMenuItem1.Name = "linearToolStripMenuItem1";
this.linearToolStripMenuItem1.Size = new System.Drawing.Size(164, 22);
this.linearToolStripMenuItem1.Tag = "Post,Linear";
this.linearToolStripMenuItem1.Text = "&Linear";
this.linearToolStripMenuItem1.Click += new System.EventHandler(this.curveLoopToolStripMenuItem_Click);
//
// constantToolStripMenuItem1
//
this.constantToolStripMenuItem1.Name = "constantToolStripMenuItem1";
this.constantToolStripMenuItem1.Size = new System.Drawing.Size(164, 22);
this.constantToolStripMenuItem1.Tag = "Post,Constant";
this.constantToolStripMenuItem1.Text = "&Constant";
this.constantToolStripMenuItem1.Click += new System.EventHandler(this.curveLoopToolStripMenuItem_Click);
//
// tangentsToolStripMenuItem
//
this.tangentsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.smoothToolStripMenuItem,
this.linearToolStripMenuItem2,
this.steppedToolStripMenuItem,
this.flatToolStripMenuItem,
this.fixedToolStripMenuItem,
this.toolStripMenuItem1,
this.inTangentToolStripMenuItem,
this.outTangentToolStripMenuItem});
this.tangentsToolStripMenuItem.Name = "tangentsToolStripMenuItem";
this.tangentsToolStripMenuItem.Size = new System.Drawing.Size(68, 20);
this.tangentsToolStripMenuItem.Text = "&Tangents";
//
// smoothToolStripMenuItem
//
this.smoothToolStripMenuItem.Name = "smoothToolStripMenuItem";
this.smoothToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.smoothToolStripMenuItem.Tag = "Tangents,Smooth";
this.smoothToolStripMenuItem.Text = "&Smooth";
this.smoothToolStripMenuItem.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// linearToolStripMenuItem2
//
this.linearToolStripMenuItem2.Name = "linearToolStripMenuItem2";
this.linearToolStripMenuItem2.Size = new System.Drawing.Size(141, 22);
this.linearToolStripMenuItem2.Tag = "Tangents,Linear";
this.linearToolStripMenuItem2.Text = "&Linear";
this.linearToolStripMenuItem2.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// steppedToolStripMenuItem
//
this.steppedToolStripMenuItem.Name = "steppedToolStripMenuItem";
this.steppedToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.steppedToolStripMenuItem.Tag = "Tangents,Stepped";
this.steppedToolStripMenuItem.Text = "S&tepped";
this.steppedToolStripMenuItem.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// flatToolStripMenuItem
//
this.flatToolStripMenuItem.Name = "flatToolStripMenuItem";
this.flatToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.flatToolStripMenuItem.Tag = "Tangents,Flat";
this.flatToolStripMenuItem.Text = "&Flat";
this.flatToolStripMenuItem.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// fixedToolStripMenuItem
//
this.fixedToolStripMenuItem.Name = "fixedToolStripMenuItem";
this.fixedToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.fixedToolStripMenuItem.Tag = "Tangents,Fixed";
this.fixedToolStripMenuItem.Text = "Fi&xed";
this.fixedToolStripMenuItem.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(138, 6);
//
// inTangentToolStripMenuItem
//
this.inTangentToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.smoothToolStripMenuItem1,
this.linearToolStripMenuItem3,
this.flatToolStripMenuItem1,
this.fixedToolStripMenuItem1});
this.inTangentToolStripMenuItem.Name = "inTangentToolStripMenuItem";
this.inTangentToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.inTangentToolStripMenuItem.Text = "In Tangent";
//
// smoothToolStripMenuItem1
//
this.smoothToolStripMenuItem1.Name = "smoothToolStripMenuItem1";
this.smoothToolStripMenuItem1.Size = new System.Drawing.Size(116, 22);
this.smoothToolStripMenuItem1.Tag = "TangentIn,Smooth";
this.smoothToolStripMenuItem1.Text = "&Smooth";
this.smoothToolStripMenuItem1.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// linearToolStripMenuItem3
//
this.linearToolStripMenuItem3.Name = "linearToolStripMenuItem3";
this.linearToolStripMenuItem3.Size = new System.Drawing.Size(116, 22);
this.linearToolStripMenuItem3.Tag = "TangentIn,Linear";
this.linearToolStripMenuItem3.Text = "&Linear";
this.linearToolStripMenuItem3.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// flatToolStripMenuItem1
//
this.flatToolStripMenuItem1.Name = "flatToolStripMenuItem1";
this.flatToolStripMenuItem1.Size = new System.Drawing.Size(116, 22);
this.flatToolStripMenuItem1.Tag = "TangentIn,Flat";
this.flatToolStripMenuItem1.Text = "&Flat";
this.flatToolStripMenuItem1.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// fixedToolStripMenuItem1
//
this.fixedToolStripMenuItem1.Name = "fixedToolStripMenuItem1";
this.fixedToolStripMenuItem1.Size = new System.Drawing.Size(116, 22);
this.fixedToolStripMenuItem1.Tag = "TangentIn,Fixed";
this.fixedToolStripMenuItem1.Text = "Fi&xed";
this.fixedToolStripMenuItem1.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// outTangentToolStripMenuItem
//
this.outTangentToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.smoothToolStripMenuItem2,
this.linearToolStripMenuItem4,
this.flatToolStripMenuItem2,
this.fixedToolStripMenuItem2});
this.outTangentToolStripMenuItem.Name = "outTangentToolStripMenuItem";
this.outTangentToolStripMenuItem.Size = new System.Drawing.Size(141, 22);
this.outTangentToolStripMenuItem.Text = "Out Tangent";
//
// smoothToolStripMenuItem2
//
this.smoothToolStripMenuItem2.Name = "smoothToolStripMenuItem2";
this.smoothToolStripMenuItem2.Size = new System.Drawing.Size(116, 22);
this.smoothToolStripMenuItem2.Tag = "TangentOut,Smooth";
this.smoothToolStripMenuItem2.Text = "&Smooth";
this.smoothToolStripMenuItem2.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// linearToolStripMenuItem4
//
this.linearToolStripMenuItem4.Name = "linearToolStripMenuItem4";
this.linearToolStripMenuItem4.Size = new System.Drawing.Size(116, 22);
this.linearToolStripMenuItem4.Tag = "TangentOut,Linear";
this.linearToolStripMenuItem4.Text = "&Linear";
this.linearToolStripMenuItem4.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// flatToolStripMenuItem2
//
this.flatToolStripMenuItem2.Name = "flatToolStripMenuItem2";
this.flatToolStripMenuItem2.Size = new System.Drawing.Size(116, 22);
this.flatToolStripMenuItem2.Tag = "TangentOut,Flat";
this.flatToolStripMenuItem2.Text = "&Flat";
this.flatToolStripMenuItem2.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// fixedToolStripMenuItem2
//
this.fixedToolStripMenuItem2.Name = "fixedToolStripMenuItem2";
this.fixedToolStripMenuItem2.Size = new System.Drawing.Size(116, 22);
this.fixedToolStripMenuItem2.Tag = "TangentOut,Fixed";
this.fixedToolStripMenuItem2.Text = "Fi&xed";
this.fixedToolStripMenuItem2.Click += new System.EventHandler(this.tangentsToolStripMenuItems_Click);
//
// BottomToolStripPanel
//
this.BottomToolStripPanel.Location = new System.Drawing.Point(0, 0);
this.BottomToolStripPanel.Name = "BottomToolStripPanel";
this.BottomToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.BottomToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.BottomToolStripPanel.Size = new System.Drawing.Size(0, 0);
//
// TopToolStripPanel
//
this.TopToolStripPanel.Location = new System.Drawing.Point(0, 0);
this.TopToolStripPanel.Name = "TopToolStripPanel";
this.TopToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.TopToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.TopToolStripPanel.Size = new System.Drawing.Size(0, 0);
//
// RightToolStripPanel
//
this.RightToolStripPanel.Location = new System.Drawing.Point(0, 0);
this.RightToolStripPanel.Name = "RightToolStripPanel";
this.RightToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.RightToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.RightToolStripPanel.Size = new System.Drawing.Size(0, 0);
//
// LeftToolStripPanel
//
this.LeftToolStripPanel.Location = new System.Drawing.Point(0, 0);
this.LeftToolStripPanel.Name = "LeftToolStripPanel";
this.LeftToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.LeftToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.LeftToolStripPanel.Size = new System.Drawing.Size(0, 0);
//
// ContentPanel
//
this.ContentPanel.Size = new System.Drawing.Size(150, 175);
//
// toolStripContainer1
//
//
// toolStripContainer1.ContentPanel
//
this.toolStripContainer1.ContentPanel.Controls.Add(this.curveView);
this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(464, 192);
this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.toolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.toolStripContainer1.Name = "toolStripContainer1";
this.toolStripContainer1.Size = new System.Drawing.Size(464, 241);
this.toolStripContainer1.TabIndex = 1;
this.toolStripContainer1.Text = "toolStripContainer1";
//
// toolStripContainer1.TopToolStripPanel
//
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.menuStrip);
this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip);
//
// toolStrip
//
this.toolStrip.Dock = System.Windows.Forms.DockStyle.None;
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.selectionButton,
this.addKeyButton,
this.moveKeyButton,
this.panButton,
this.zoomButton,
this.keyPositionLabel,
this.keyPositionTextBox,
this.keyValueLabel,
this.keyValueTextBox});
this.toolStrip.Location = new System.Drawing.Point(3, 24);
this.toolStrip.Name = "toolStrip";
this.toolStrip.Size = new System.Drawing.Size(417, 25);
this.toolStrip.TabIndex = 1;
//
// selectionButton
//
this.selectionButton.Checked = true;
this.selectionButton.CheckState = System.Windows.Forms.CheckState.Checked;
this.selectionButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.selectionButton.Image = global::Xna.Tools.CurveControlResources.SelectImage;
this.selectionButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.selectionButton.Name = "selectionButton";
this.selectionButton.Size = new System.Drawing.Size(23, 22);
this.selectionButton.Tag = "Select";
this.selectionButton.Text = "Select Keys (S)";
this.selectionButton.Click += new System.EventHandler(this.editButton_Click);
//
// addKeyButton
//
this.addKeyButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.addKeyButton.Image = global::Xna.Tools.CurveControlResources.AddKeyImage;
this.addKeyButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.addKeyButton.Name = "addKeyButton";
this.addKeyButton.Size = new System.Drawing.Size(23, 22);
this.addKeyButton.Tag = "Add";
this.addKeyButton.Text = "toolStripButton2";
this.addKeyButton.ToolTipText = "Add Key (A)";
this.addKeyButton.Click += new System.EventHandler(this.editButton_Click);
//
// moveKeyButton
//
this.moveKeyButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.moveKeyButton.Image = global::Xna.Tools.CurveControlResources.MoveKeyImage;
this.moveKeyButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.moveKeyButton.Name = "moveKeyButton";
this.moveKeyButton.Size = new System.Drawing.Size(23, 22);
this.moveKeyButton.Tag = "Move";
this.moveKeyButton.Text = "Move Keys (D)";
this.moveKeyButton.Click += new System.EventHandler(this.editButton_Click);
//
// panButton
//
this.panButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.panButton.Image = global::Xna.Tools.CurveControlResources.MoveImage;
this.panButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.panButton.Name = "panButton";
this.panButton.Size = new System.Drawing.Size(23, 22);
this.panButton.Tag = "Pan";
this.panButton.Text = "toolStripButton2";
this.panButton.ToolTipText = "Pan Camera (W)";
this.panButton.Click += new System.EventHandler(this.editButton_Click);
//
// zoomButton
//
this.zoomButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.zoomButton.Image = global::Xna.Tools.CurveControlResources.ZoomImage;
this.zoomButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.zoomButton.Name = "zoomButton";
this.zoomButton.Size = new System.Drawing.Size(23, 22);
this.zoomButton.Tag = "Zoom";
this.zoomButton.Text = "toolStripButton1";
this.zoomButton.ToolTipText = "Zoom (E)";
this.zoomButton.Click += new System.EventHandler(this.editButton_Click);
//
// keyPositionLabel
//
this.keyPositionLabel.Enabled = false;
this.keyPositionLabel.Name = "keyPositionLabel";
this.keyPositionLabel.Size = new System.Drawing.Size(50, 22);
this.keyPositionLabel.Text = "Position";
//
// keyPositionTextBox
//
this.keyPositionTextBox.Enabled = false;
this.keyPositionTextBox.Name = "keyPositionTextBox";
this.keyPositionTextBox.Size = new System.Drawing.Size(100, 25);
this.keyPositionTextBox.TextChanged += new System.EventHandler(this.singleKeyEdit_TextChanged);
//
// keyValueLabel
//
this.keyValueLabel.Enabled = false;
this.keyValueLabel.Name = "keyValueLabel";
this.keyValueLabel.Size = new System.Drawing.Size(36, 22);
this.keyValueLabel.Text = "Value";
//
// keyValueTextBox
//
this.keyValueTextBox.Enabled = false;
this.keyValueTextBox.Name = "keyValueTextBox";
this.keyValueTextBox.Size = new System.Drawing.Size(100, 25);
this.keyValueTextBox.TextChanged += new System.EventHandler(this.singleKeyEdit_TextChanged);
//
// curveView
//
this.curveView.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(228)))), ((int)(((byte)(233)))), ((int)(((byte)(240)))));
this.curveView.Dock = System.Windows.Forms.DockStyle.Fill;
this.curveView.Location = new System.Drawing.Point(0, 0);
this.curveView.Name = "curveView";
this.curveView.Size = new System.Drawing.Size(464, 192);
this.curveView.TabIndex = 0;
this.curveView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.curveView_MouseDown);
this.curveView.MouseMove += new System.Windows.Forms.MouseEventHandler(this.curveView_MouseMove);
this.curveView.KeyUp += new System.Windows.Forms.KeyEventHandler(this.curveView_KeyUp);
this.curveView.Paint += new System.Windows.Forms.PaintEventHandler(this.curveView_Paint);
this.curveView.MouseUp += new System.Windows.Forms.MouseEventHandler(this.curveView_MouseUp);
this.curveView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.curveView_KeyDown);
//
// CurveControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.toolStripContainer1);
this.Name = "CurveControl";
this.Size = new System.Drawing.Size(464, 241);
this.Load += new System.EventHandler(this.CurveControl_Load);
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.toolStripContainer1.ContentPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.toolStripContainer1.TopToolStripPanel.PerformLayout();
this.toolStripContainer1.ResumeLayout(false);
this.toolStripContainer1.PerformLayout();
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem curvesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tangentsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem preInfinityToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cycleToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cycleWithOffsetToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem postInfinityToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem oscillateToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem linearToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem constantToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cycleToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem cycleWithOffsetToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem oscillateToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem linearToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem constantToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem smoothToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem linearToolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem steppedToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem flatToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem fixedToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem inTangentToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem smoothToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem linearToolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem flatToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem fixedToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem outTangentToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem smoothToolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem linearToolStripMenuItem4;
private System.Windows.Forms.ToolStripMenuItem flatToolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem fixedToolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem frameAllToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem frameSelectionToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem autoFrameToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem curveSmoothnessToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem coarseToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem roughToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem mediumToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem fineToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem keysToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem alwaysToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem neverToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem activeOnlyToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem tangentsToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem alwaysToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem neverToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem activeOnlyToolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem infinityToolStripMenuItem;
private System.Windows.Forms.ToolStripPanel BottomToolStripPanel;
private System.Windows.Forms.ToolStripPanel TopToolStripPanel;
private System.Windows.Forms.ToolStripPanel RightToolStripPanel;
private System.Windows.Forms.ToolStripPanel LeftToolStripPanel;
private System.Windows.Forms.ToolStripContentPanel ContentPanel;
private System.Windows.Forms.ToolStripContainer toolStripContainer1;
private System.Windows.Forms.ToolStrip toolStrip;
private System.Windows.Forms.ToolStripLabel keyPositionLabel;
private GridControl curveView;
private System.Windows.Forms.ToolStripTextBox keyPositionTextBox;
private System.Windows.Forms.ToolStripLabel keyValueLabel;
private System.Windows.Forms.ToolStripTextBox keyValueTextBox;
private System.Windows.Forms.ToolStripButton selectionButton;
private System.Windows.Forms.ToolStripButton addKeyButton;
private System.Windows.Forms.ToolStripButton zoomButton;
private System.Windows.Forms.ToolStripButton panButton;
private System.Windows.Forms.ToolStripButton moveKeyButton;
}
}
| |
// 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.AcceptanceTestsAzureCompositeModelClient
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PolymorphicrecursiveOperations operations.
/// </summary>
internal partial class PolymorphicrecursiveOperations : Microsoft.Rest.IServiceOperations<AzureCompositeModel>, IPolymorphicrecursiveOperations
{
/// <summary>
/// Initializes a new instance of the PolymorphicrecursiveOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PolymorphicrecursiveOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Fish>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Fish>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Fish>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic and have recursive references
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// "fishtype": "salmon",
/// "species": "king",
/// "length": 1,
/// "age": 1,
/// "location": "alaska",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6,
/// "siblings": [
/// {
/// "fishtype": "salmon",
/// "species": "coho",
/// "length": 2,
/// "age": 2,
/// "location": "atlantic",
/// "iswild": true,
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (complexBody == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphicrecursive/valid").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Linq;
using System.Management.Automation;
using EnvDTE;
using Moq;
using NuGet.Test;
using NuGet.Test.Mocks;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Test;
using Xunit;
using Xunit.Extensions;
namespace NuGet.PowerShell.Commands.Test
{
using PackageUtility = NuGet.Test.PackageUtility;
public class UpdatePackageCommandTest
{
[Fact]
public void UpdatePackageCmdletThrowsWhenSolutionIsClosed()
{
// Arrange
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns((IVsPackageManager)null);
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManager(isSolutionOpen: false), packageManagerFactory.Object, null, null, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
// Act and Assert
ExceptionAssert.Throws<InvalidOperationException>(() => cmdlet.GetResults(),
"The current environment doesn't have a solution open.");
}
[Fact]
public void UpdatePackageCmdletUsesPackageManangerWithSourceIfSpecified()
{
// Arrange
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
var vsPackageManager = new MockVsPackageManager();
var sourceVsPackageManager = new MockVsPackageManager();
var mockPackageRepository = new MockPackageRepository();
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager);
packageManagerFactory.Setup(m => m.CreatePackageManager(mockPackageRepository, true)).Returns(sourceVsPackageManager);
var sourceProvider = GetPackageSourceProvider(new PackageSource("somesource"));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(It.Is<string>(s => s == "somesource"))).Returns(mockPackageRepository);
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManagerWithProjects("foo"), packageManagerFactory.Object, repositoryFactory.Object, sourceProvider, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Source = "somesource";
cmdlet.Id = "my-id";
cmdlet.Version = new SemanticVersion("2.8");
cmdlet.ProjectName = "foo";
// Act
cmdlet.Execute();
// Assert
Assert.Same(sourceVsPackageManager, cmdlet.PackageManager);
}
[Fact]
public void UpdatePackageCmdletPassesParametersCorrectlyWhenIdAndVersionAreSpecified()
{
// Arrange
var vsPackageManager = new MockVsPackageManager();
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager);
var mockPackageRepository = new MockPackageRepository();
var sourceProvider = GetPackageSourceProvider(new PackageSource("somesource"));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(It.Is<string>(s => s == "somesource"))).Returns(mockPackageRepository);
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManagerWithProjects("foo"), packageManagerFactory.Object, repositoryFactory.Object, sourceProvider, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "my-id";
cmdlet.Version = new SemanticVersion("2.8");
cmdlet.ProjectName = "foo";
// Act
cmdlet.Execute();
// Assert
Assert.Equal("my-id", vsPackageManager.PackageId);
Assert.Equal(new SemanticVersion("2.8"), vsPackageManager.Version);
}
[Fact]
public void UpdatePackageCmdletSpecifiesUpdateOperationDuringExecution()
{
// Arrange
var mockPackageRepository = new MockPackageRepository();
var vsPackageManager = new MockVsPackageManager(mockPackageRepository);
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager);
var sourceProvider = GetPackageSourceProvider(new PackageSource("somesource"));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(It.Is<string>(s => s == "somesource"))).Returns(mockPackageRepository);
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManagerWithProjects("foo"), packageManagerFactory.Object, repositoryFactory.Object, sourceProvider, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "my-id";
cmdlet.Version = new SemanticVersion("2.8");
cmdlet.ProjectName = "foo";
// Act
cmdlet.Execute();
// Assert
Assert.Equal(RepositoryOperationNames.Update, mockPackageRepository.LastOperation);
}
[Fact]
public void UpdatePackageCmdletSpecifiesReinstallOperationDuringReinstall()
{
// Arrange
var mockPackageRepository = new MockPackageRepository();
var projectManager = new Mock<IProjectManager>();
projectManager.Setup(p => p.LocalRepository).Returns(new MockPackageRepository());
var vsPackageManager = new Mock<IVsPackageManager>();
vsPackageManager.Setup(v => v.SourceRepository).Returns(mockPackageRepository);
vsPackageManager.Setup(v => v.GetProjectManager(It.IsAny<Project>())).Returns(projectManager.Object);
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager.Object);
var sourceProvider = GetPackageSourceProvider(new PackageSource("somesource"));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(It.Is<string>(s => s == "somesource"))).Returns(mockPackageRepository);
var cmdlet = new UpdatePackageCommand(
TestUtils.GetSolutionManagerWithProjects("foo"),
packageManagerFactory.Object,
repositoryFactory.Object,
sourceProvider,
null,
null,
new Mock<IVsCommonOperations>().Object,
new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "my-id";
cmdlet.Reinstall = true;
cmdlet.ProjectName = "foo";
// Act
cmdlet.Execute();
// Assert
Assert.Equal(RepositoryOperationNames.Reinstall, mockPackageRepository.LastOperation);
}
[Fact]
public void UpdatePackageCmdletSpecifiesReinstallOperationDuringReinstallWhenIdIsNull()
{
// Arrange
var mockPackageRepository = new MockPackageRepository();
var projectManager = new Mock<IProjectManager>();
projectManager.Setup(p => p.LocalRepository).Returns(new MockPackageRepository());
var vsPackageManager = new Mock<IVsPackageManager>();
vsPackageManager.Setup(v => v.SourceRepository).Returns(mockPackageRepository);
vsPackageManager.Setup(v => v.GetProjectManager(It.IsAny<Project>())).Returns(projectManager.Object);
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager.Object);
var sourceProvider = GetPackageSourceProvider(new PackageSource("somesource"));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(It.Is<string>(s => s == "somesource"))).Returns(mockPackageRepository);
var cmdlet = new UpdatePackageCommand(
TestUtils.GetSolutionManagerWithProjects("foo"),
packageManagerFactory.Object,
repositoryFactory.Object,
sourceProvider,
null,
null,
new Mock<IVsCommonOperations>().Object,
new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Reinstall = true;
cmdlet.ProjectName = "foo";
// Act
cmdlet.Execute();
// Assert
Assert.Equal(RepositoryOperationNames.Reinstall, mockPackageRepository.LastOperation);
}
[Fact]
public void UpdatePackageCmdletSpecifiesReinstallOperationDuringReinstallWhenProjectNameIsNull()
{
// Arrange
var mockPackageRepository = new MockPackageRepository();
var projectManager = new Mock<IProjectManager>();
projectManager.Setup(p => p.LocalRepository).Returns(new MockPackageRepository());
var vsPackageManager = new Mock<IVsPackageManager>();
vsPackageManager.Setup(v => v.SourceRepository).Returns(mockPackageRepository);
vsPackageManager.Setup(v => v.GetProjectManager(It.IsAny<Project>())).Returns(projectManager.Object);
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager.Object);
var sourceProvider = GetPackageSourceProvider(new PackageSource("somesource"));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(It.Is<string>(s => s == "somesource"))).Returns(mockPackageRepository);
var cmdlet = new UpdatePackageCommand(
TestUtils.GetSolutionManagerWithProjects("foo"),
packageManagerFactory.Object,
repositoryFactory.Object,
sourceProvider,
null,
null,
new Mock<IVsCommonOperations>().Object,
new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "my-id";
cmdlet.Reinstall = true;
// Act
cmdlet.Execute();
// Assert
Assert.Equal(RepositoryOperationNames.Reinstall, mockPackageRepository.LastOperation);
}
[Fact]
public void UpdatePackageCmdletSpecifiesReinstallOperationDuringReinstallWhenIdAndProjectNameAreNull()
{
// Arrange
var mockPackageRepository = new MockPackageRepository();
var projectManager = new Mock<IProjectManager>();
projectManager.Setup(p => p.LocalRepository).Returns(new MockPackageRepository());
var vsPackageManager = new Mock<IVsPackageManager>();
vsPackageManager.Setup(v => v.SourceRepository).Returns(mockPackageRepository);
vsPackageManager.Setup(v => v.GetProjectManager(It.IsAny<Project>())).Returns(projectManager.Object);
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager.Object);
var sourceProvider = GetPackageSourceProvider(new PackageSource("somesource"));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(It.Is<string>(s => s == "somesource"))).Returns(mockPackageRepository);
var cmdlet = new UpdatePackageCommand(
TestUtils.GetSolutionManagerWithProjects("foo"),
packageManagerFactory.Object,
repositoryFactory.Object,
sourceProvider,
null,
null,
new Mock<IVsCommonOperations>().Object,
new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Reinstall = true;
// Act
cmdlet.Execute();
// Assert
Assert.Equal(RepositoryOperationNames.Reinstall, mockPackageRepository.LastOperation);
}
[Fact]
public void UpdatePackageCmdletPassesIgnoreDependencySwitchCorrectly()
{
// Arrange
var vsPackageManager = new MockVsPackageManager();
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager);
var mockPackageRepository = new MockPackageRepository();
var sourceProvider = GetPackageSourceProvider(new PackageSource("somesource"));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(It.Is<string>(s => s == "somesource"))).Returns(mockPackageRepository);
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManagerWithProjects("foo"), packageManagerFactory.Object, repositoryFactory.Object, sourceProvider, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "my-id";
cmdlet.Version = new SemanticVersion("2.8");
cmdlet.ProjectName = "foo";
// Act
cmdlet.Execute();
// Assert
Assert.Equal("my-id", vsPackageManager.PackageId);
Assert.Equal(new SemanticVersion("2.8"), vsPackageManager.Version);
Assert.True(vsPackageManager.UpdateDependencies);
}
[Fact]
public void UpdatePackageCmdletPassesIgnoreDependencySwitchCorrectlyWhenPresent()
{
// Arrange
var vsPackageManager = new MockVsPackageManager();
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(vsPackageManager);
var mockPackageRepository = new MockPackageRepository();
var sourceProvider = GetPackageSourceProvider(new PackageSource("somesource"));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(It.Is<string>(s => s == "somesource"))).Returns(mockPackageRepository);
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManagerWithProjects("foo"), packageManagerFactory.Object, repositoryFactory.Object, sourceProvider, null, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "my-id";
cmdlet.Version = new SemanticVersion("2.8");
cmdlet.IgnoreDependencies = new SwitchParameter(isPresent: true);
cmdlet.ProjectName = "foo";
// Act
cmdlet.Execute();
// Assert
Assert.Equal("my-id", vsPackageManager.PackageId);
Assert.Equal(new SemanticVersion("2.8"), vsPackageManager.Version);
Assert.False(vsPackageManager.UpdateDependencies);
}
[Fact]
public void UpdatePackageCmdletInvokeProductUpdateCheckWhenSourceIsHttpAddress()
{
// Arrange
string source = "http://bing.com";
var productUpdateService = new Mock<IProductUpdateService>();
var sourceRepository = new Mock<IPackageRepository>();
sourceRepository.Setup(p => p.Source).Returns(source);
var vsPackageManager = new MockVsPackageManager(sourceRepository.Object);
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(c => c.CreatePackageManager(sourceRepository.Object, true)).Returns(vsPackageManager);
var mockPackageRepository = new MockPackageRepository();
var sourceProvider = GetPackageSourceProvider(new PackageSource(source));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(source)).Returns(sourceRepository.Object);
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManagerWithProjects("foo"), packageManagerFactory.Object, repositoryFactory.Object, sourceProvider, null, productUpdateService.Object, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "my-id";
cmdlet.Version = new SemanticVersion("2.8");
cmdlet.IgnoreDependencies = new SwitchParameter(isPresent: true);
cmdlet.Source = source;
cmdlet.ProjectName = "foo";
// Act
cmdlet.Execute();
// Assert
productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Once());
}
[Fact]
public void UpdatePackageCmdletInvokeProductUpdateCheckWhenSourceIsHttpAddressAndSourceIsSpecified()
{
// Arrange
string source = "http://bing.com";
var productUpdateService = new Mock<IProductUpdateService>();
var sourceRepository = new Mock<IPackageRepository>();
sourceRepository.Setup(p => p.Source).Returns(source);
var vsPackageManager = new MockVsPackageManager(sourceRepository.Object);
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(c => c.CreatePackageManager(sourceRepository.Object, true)).Returns(vsPackageManager);
var sourceProvider = GetPackageSourceProvider(new PackageSource(source, "bing"));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(source)).Returns(sourceRepository.Object);
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManagerWithProjects("foo"), packageManagerFactory.Object, repositoryFactory.Object, sourceProvider, null, productUpdateService.Object, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "my-id";
cmdlet.Version = new SemanticVersion("2.8");
cmdlet.IgnoreDependencies = new SwitchParameter(isPresent: true);
cmdlet.Source = "bing";
cmdlet.ProjectName = "foo";
// Act
cmdlet.Execute();
// Assert
productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Once());
}
[Fact]
public void UpdatePackageCmdletDoNotInvokeProductUpdateCheckWhenSourceIsNotHttpAddress()
{
// Arrange
string source = "ftp://bing.com";
var productUpdateService = new Mock<IProductUpdateService>();
var sourceRepository = new Mock<IPackageRepository>();
sourceRepository.Setup(p => p.Source).Returns(source);
var vsPackageManager = new MockVsPackageManager(sourceRepository.Object);
var packageManagerFactory = new Mock<IVsPackageManagerFactory>();
packageManagerFactory.Setup(m => m.CreatePackageManager(sourceRepository.Object, true)).Returns(vsPackageManager);
var sourceProvider = GetPackageSourceProvider(new PackageSource(source, "bing"));
var repositoryFactory = new Mock<IPackageRepositoryFactory>();
repositoryFactory.Setup(c => c.CreateRepository(source)).Returns(sourceRepository.Object);
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManagerWithProjects("foo"), packageManagerFactory.Object, repositoryFactory.Object, sourceProvider, null, productUpdateService.Object, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "my-id";
cmdlet.Version = new SemanticVersion("2.8");
cmdlet.IgnoreDependencies = new SwitchParameter(isPresent: true);
cmdlet.Source = source;
cmdlet.ProjectName = "foo";
// Act
cmdlet.Execute();
// Assert
productUpdateService.Verify(p => p.CheckForAvailableUpdateAsync(), Times.Never());
}
[Theory]
[InlineData("1.0.0", "2.0.0-alpha")]
[InlineData("1.0.0-beta", "2.0.0")]
[InlineData("1.0.0-beta", "1.0.1-beta")]
[InlineData("1.0.0", "1.0.1")]
public void UpdatePackageDoNotUpdateToUnlistedPackageWithPrerelease(string versionA1, string versionA2)
{
// Arrange
var packageA1 = PackageUtility.CreatePackage("A", versionA1, dependencies: new[] { new PackageDependency("B") });
var packageA2 = PackageUtility.CreatePackage("A", versionA2, listed: false);
var sharedRepository = new Mock<ISharedPackageRepository>();
sharedRepository.Setup(s => s.GetPackages()).Returns(new [] { packageA1 }.AsQueryable());
var packageRepository = new MockPackageRepository { packageA1, packageA2 };
var packageManager = new VsPackageManager(TestUtils.GetSolutionManagerWithProjects("foo"), packageRepository, new Mock<IFileSystemProvider>().Object, new MockFileSystem(), sharedRepository.Object, new Mock<IDeleteOnRestartManager>().Object, new VsPackageInstallerEvents());
var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict);
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager);
// Act
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "A";
cmdlet.IncludePrerelease = true;
cmdlet.Execute();
// Assert
sharedRepository.Verify(s => s.AddPackage(packageA2), Times.Never());
}
[Theory]
[InlineData("1.0.0", "1.0.1-alpha")]
[InlineData("1.0.0-beta", "1.0.9")]
[InlineData("1.0.0-beta", "1.0.1-beta")]
[InlineData("1.0.0", "1.0.1")]
public void SafeUpdatePackageDoNotUpdateToUnlistedPackageWithPrerelease(string versionA1, string versionA2)
{
// Arrange
var packageA1 = PackageUtility.CreatePackage("A", versionA1, dependencies: new[] { new PackageDependency("B") });
var packageA2 = PackageUtility.CreatePackage("A", versionA2, listed: false);
var sharedRepository = new Mock<ISharedPackageRepository>();
sharedRepository.Setup(s => s.GetPackages()).Returns(new[] { packageA1 }.AsQueryable());
var packageRepository = new MockPackageRepository { packageA1, packageA2 };
var packageManager = new VsPackageManager(TestUtils.GetSolutionManagerWithProjects("foo"), packageRepository, new Mock<IFileSystemProvider>().Object, new MockFileSystem(), sharedRepository.Object, new Mock<IDeleteOnRestartManager>().Object, new VsPackageInstallerEvents());
var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict);
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager);
// Act
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "A";
cmdlet.IncludePrerelease = true;
cmdlet.Safe = true;
cmdlet.Execute();
// Assert
sharedRepository.Verify(s => s.AddPackage(packageA2), Times.Never());
}
[Theory]
[InlineData("1.0.0", "2.0.0")]
[InlineData("1.0.0", "1.0.1")]
public void UpdatePackageDoNotUpdateToUnlistedPackage(string versionA1, string versionA2)
{
// Arrange
var packageA1 = PackageUtility.CreatePackage("A", versionA1, dependencies: new[] { new PackageDependency("B") });
var packageA2 = PackageUtility.CreatePackage("A", versionA2, listed: false);
var sharedRepository = new Mock<ISharedPackageRepository>();
sharedRepository.Setup(s => s.GetPackages()).Returns(new[] { packageA1 }.AsQueryable());
var packageRepository = new MockPackageRepository { packageA1, packageA2 };
var packageManager = new VsPackageManager(TestUtils.GetSolutionManagerWithProjects("foo"), packageRepository, new Mock<IFileSystemProvider>().Object, new MockFileSystem(), sharedRepository.Object, new Mock<IDeleteOnRestartManager>().Object, new VsPackageInstallerEvents());
var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict);
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager);
// Act
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "A";
cmdlet.Execute();
// Assert
sharedRepository.Verify(s => s.AddPackage(packageA2), Times.Never());
}
[Theory]
[InlineData("1.0.0", "1.0.0.2")]
[InlineData("1.0.0", "1.0.1.3")]
public void SafeUpdatePackageDoNotUpdateToUnlistedPackage(string versionA1, string versionA2)
{
// Arrange
var packageA1 = PackageUtility.CreatePackage("A", versionA1, dependencies: new[] { new PackageDependency("B") });
var packageA2 = PackageUtility.CreatePackage("A", versionA2, listed: false);
var sharedRepository = new Mock<ISharedPackageRepository>();
sharedRepository.Setup(s => s.GetPackages()).Returns(new[] { packageA1 }.AsQueryable());
var packageRepository = new MockPackageRepository { packageA1, packageA2 };
var packageManager = new VsPackageManager(TestUtils.GetSolutionManagerWithProjects("foo"), packageRepository, new Mock<IFileSystemProvider>().Object, new MockFileSystem(), sharedRepository.Object, new Mock<IDeleteOnRestartManager>().Object, new VsPackageInstallerEvents());
var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict);
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager);
// Act
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "A";
cmdlet.Safe = true;
cmdlet.Execute();
// Assert
sharedRepository.Verify(s => s.AddPackage(packageA2), Times.Never());
}
[Theory]
[InlineData("1.0.0", "2.0.0")]
[InlineData("1.0.0", "1.0.1")]
[InlineData("1.0.0", "2.0.0-alpha")]
[InlineData("1.0.0-beta", "2.0.0")]
[InlineData("1.0.0-beta", "1.0.1-beta")]
public void UpdatePackageUpdateToUnlistedPackageIfVersionIsSet(string versionA1, string versionA2)
{
// Arrange
var packageA1 = PackageUtility.CreatePackage("A", versionA1, dependencies: new[] { new PackageDependency("B") });
var packageA2 = PackageUtility.CreatePackage("A", versionA2, listed: false);
var sharedRepository = new Mock<ISharedPackageRepository>();
sharedRepository.Setup(s => s.GetPackages()).Returns(new[] { packageA1 }.AsQueryable());
sharedRepository.Setup(s => s.AddPackage(packageA2)).Verifiable();
var packageRepository = new MockPackageRepository { packageA1, packageA2 };
var packageManager = new VsPackageManager(TestUtils.GetSolutionManagerWithProjects("foo"), packageRepository, new Mock<IFileSystemProvider>().Object, new MockFileSystem(), sharedRepository.Object, new Mock<IDeleteOnRestartManager>().Object, new VsPackageInstallerEvents());
var packageManagerFactory = new Mock<IVsPackageManagerFactory>(MockBehavior.Strict);
packageManagerFactory.Setup(m => m.CreatePackageManager()).Returns(packageManager);
// Act
var cmdlet = new UpdatePackageCommand(TestUtils.GetSolutionManager(), packageManagerFactory.Object, null, new Mock<IVsPackageSourceProvider>().Object, new Mock<IHttpClientEvents>().Object, null, new Mock<IVsCommonOperations>().Object, new Mock<IDeleteOnRestartManager>().Object);
cmdlet.Id = "A";
cmdlet.Version = new SemanticVersion(versionA2);
cmdlet.Execute();
// Assert
sharedRepository.Verify();
}
private static IVsPackageSourceProvider GetPackageSourceProvider(params PackageSource[] sources)
{
var sourceProvider = new Mock<IVsPackageSourceProvider>();
sourceProvider.Setup(c => c.LoadPackageSources()).Returns(sources);
return sourceProvider.Object;
}
private class MockVsPackageManager : VsPackageManager
{
public MockVsPackageManager()
: this(new Mock<IPackageRepository>().Object)
{
}
public MockVsPackageManager(IPackageRepository sourceRepository)
: base(new Mock<ISolutionManager>().Object, sourceRepository, new Mock<IFileSystemProvider>().Object, new Mock<IFileSystem>().Object, new Mock<ISharedPackageRepository>().Object, new Mock<IDeleteOnRestartManager>().Object, new Mock<VsPackageInstallerEvents>().Object)
{
}
public IProjectManager ProjectManager { get; set; }
public string PackageId { get; set; }
public SemanticVersion Version { get; set; }
public bool UpdateDependencies { get; set; }
public override void UpdatePackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPreReleaseVersions, ILogger logger)
{
ProjectManager = projectManager;
PackageId = packageId;
Version = version;
UpdateDependencies = updateDependencies;
}
public override IProjectManager GetProjectManager(Project project)
{
return new Mock<IProjectManager>().Object;
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Javax.Xml.Transform.Stream.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Javax.Xml.Transform.Stream
{
/// <summary>
/// <para>Acts as an holder for a transformation result, which may be XML, plain Text, HTML, or some other form of markup.</para><para><para> </para></para>
/// </summary>
/// <java-name>
/// javax/xml/transform/stream/StreamResult
/// </java-name>
[Dot42.DexImport("javax/xml/transform/stream/StreamResult", AccessFlags = 33)]
public partial class StreamResult : global::Javax.Xml.Transform.IResult
/* scope: __dot42__ */
{
/// <summary>
/// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the Transformer supports Result output of this type. </para>
/// </summary>
/// <java-name>
/// FEATURE
/// </java-name>
[Dot42.DexImport("FEATURE", "Ljava/lang/String;", AccessFlags = 25)]
public const string FEATURE = "http://javax.xml.transform.stream.StreamResult/feature";
/// <summary>
/// <para>Zero-argument default constructor. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public StreamResult() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/OutputStream;)V", AccessFlags = 1)]
public StreamResult(global::Java.Io.OutputStream outputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/Writer;)V", AccessFlags = 1)]
public StreamResult(global::Java.Io.Writer outputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public StreamResult(string outputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamResult from a byte stream. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/File;)V", AccessFlags = 1)]
public StreamResult(global::Java.Io.File outputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Set the ByteStream that is to be written to. Normally, a stream should be used rather than a reader, so that the transformer may use instructions contained in the transformation instructions to control the encoding.</para><para></para>
/// </summary>
/// <java-name>
/// setOutputStream
/// </java-name>
[Dot42.DexImport("setOutputStream", "(Ljava/io/OutputStream;)V", AccessFlags = 1)]
public virtual void SetOutputStream(global::Java.Io.OutputStream outputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the byte stream that was set with setOutputStream.</para><para></para>
/// </summary>
/// <returns>
/// <para>The byte stream that was set with setOutputStream, or null if setOutputStream or the ByteStream constructor was not called. </para>
/// </returns>
/// <java-name>
/// getOutputStream
/// </java-name>
[Dot42.DexImport("getOutputStream", "()Ljava/io/OutputStream;", AccessFlags = 1)]
public virtual global::Java.Io.OutputStream GetOutputStream() /* MethodBuilder.Create */
{
return default(global::Java.Io.OutputStream);
}
/// <summary>
/// <para>Set the writer that is to receive the result. Normally, a stream should be used rather than a writer, so that the transformer may use instructions contained in the transformation instructions to control the encoding. However, there are times when it is useful to write to a writer, such as when using a StringWriter.</para><para></para>
/// </summary>
/// <java-name>
/// setWriter
/// </java-name>
[Dot42.DexImport("setWriter", "(Ljava/io/Writer;)V", AccessFlags = 1)]
public virtual void SetWriter(global::Java.Io.Writer writer) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the character stream that was set with setWriter.</para><para></para>
/// </summary>
/// <returns>
/// <para>The character stream that was set with setWriter, or null if setWriter or the Writer constructor was not called. </para>
/// </returns>
/// <java-name>
/// getWriter
/// </java-name>
[Dot42.DexImport("getWriter", "()Ljava/io/Writer;", AccessFlags = 1)]
public virtual global::Java.Io.Writer GetWriter() /* MethodBuilder.Create */
{
return default(global::Java.Io.Writer);
}
/// <summary>
/// <para>Set the system ID from a <code>File</code> reference.</para><para>Note the use of File#toURI() and File#toURL(). <code>toURI()</code> is preferred and used if possible. To allow JAXP 1.3 to run on J2SE 1.3, <code>toURL()</code> is used if a NoSuchMethodException is thrown by the attempt to use <code>toURI()</code>.</para><para></para>
/// </summary>
/// <java-name>
/// setSystemId
/// </java-name>
[Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetSystemId(string f) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Set the system ID from a <code>File</code> reference.</para><para>Note the use of File#toURI() and File#toURL(). <code>toURI()</code> is preferred and used if possible. To allow JAXP 1.3 to run on J2SE 1.3, <code>toURL()</code> is used if a NoSuchMethodException is thrown by the attempt to use <code>toURI()</code>.</para><para></para>
/// </summary>
/// <java-name>
/// setSystemId
/// </java-name>
[Dot42.DexImport("setSystemId", "(Ljava/io/File;)V", AccessFlags = 1)]
public virtual void SetSystemId(global::Java.Io.File f) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the system identifier that was set with setSystemId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para>
/// </returns>
/// <java-name>
/// getSystemId
/// </java-name>
[Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetSystemId() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Get the byte stream that was set with setOutputStream.</para><para></para>
/// </summary>
/// <returns>
/// <para>The byte stream that was set with setOutputStream, or null if setOutputStream or the ByteStream constructor was not called. </para>
/// </returns>
/// <java-name>
/// getOutputStream
/// </java-name>
public global::Java.Io.OutputStream OutputStream
{
[Dot42.DexImport("getOutputStream", "()Ljava/io/OutputStream;", AccessFlags = 1)]
get{ return GetOutputStream(); }
[Dot42.DexImport("setOutputStream", "(Ljava/io/OutputStream;)V", AccessFlags = 1)]
set{ SetOutputStream(value); }
}
/// <summary>
/// <para>Get the character stream that was set with setWriter.</para><para></para>
/// </summary>
/// <returns>
/// <para>The character stream that was set with setWriter, or null if setWriter or the Writer constructor was not called. </para>
/// </returns>
/// <java-name>
/// getWriter
/// </java-name>
public global::Java.Io.Writer Writer
{
[Dot42.DexImport("getWriter", "()Ljava/io/Writer;", AccessFlags = 1)]
get{ return GetWriter(); }
[Dot42.DexImport("setWriter", "(Ljava/io/Writer;)V", AccessFlags = 1)]
set{ SetWriter(value); }
}
/// <summary>
/// <para>Get the system identifier that was set with setSystemId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para>
/// </returns>
/// <java-name>
/// getSystemId
/// </java-name>
public string SystemId
{
[Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSystemId(); }
[Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetSystemId(value); }
}
}
/// <summary>
/// <para>Acts as an holder for a transformation Source in the form of a stream of XML markup.</para><para><b>Note:</b> Due to their internal use of either a Reader or InputStream instance, <code>StreamSource</code> instances may only be used once.</para><para><para> </para><para></para><title>Revision:</title><para>829971 </para>, <title>Date:</title><para>2009-10-26 14:15:39 -0700 (Mon, 26 Oct 2009) </para></para>
/// </summary>
/// <java-name>
/// javax/xml/transform/stream/StreamSource
/// </java-name>
[Dot42.DexImport("javax/xml/transform/stream/StreamSource", AccessFlags = 33)]
public partial class StreamSource : global::Javax.Xml.Transform.ISource
/* scope: __dot42__ */
{
/// <summary>
/// <para>If javax.xml.transform.TransformerFactory#getFeature returns true when passed this value as an argument, the Transformer supports Source input of this type. </para>
/// </summary>
/// <java-name>
/// FEATURE
/// </java-name>
[Dot42.DexImport("FEATURE", "Ljava/lang/String;", AccessFlags = 25)]
public const string FEATURE = "http://javax.xml.transform.stream.StreamSource/feature";
/// <summary>
/// <para>Zero-argument default constructor. If this constructor is used, and no Stream source is set using setInputStream(java.io.InputStream inputStream) or setReader(java.io.Reader reader), then the <code>Transformer</code> will create an empty source java.io.InputStream using new InputStream().</para><para><para>javax.xml.transform.Transformer::transform(Source xmlSource, Result outputTarget) </para></para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public StreamSource() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so the XML parser can resolve character encoding specified by the XML declaration.</para><para>If this constructor is used to process a stylesheet, normally setSystemId should also be called, so that relative URI references can be resolved.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/InputStream;)V", AccessFlags = 1)]
public StreamSource(global::Java.Io.InputStream inputStream) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/io/InputStream;Ljava/lang/String;)V", AccessFlags = 1)]
public StreamSource(global::Java.Io.InputStream inputStream, string @string) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so the XML parser can resolve character encoding specified by the XML declaration.</para><para>If this constructor is used to process a stylesheet, normally setSystemId should also be called, so that relative URI references can be resolved.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/Reader;)V", AccessFlags = 1)]
public StreamSource(global::Java.Io.Reader inputStream) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/io/Reader;Ljava/lang/String;)V", AccessFlags = 1)]
public StreamSource(global::Java.Io.Reader reader, string @string) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so the XML parser can resolve character encoding specified by the XML declaration.</para><para>If this constructor is used to process a stylesheet, normally setSystemId should also be called, so that relative URI references can be resolved.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public StreamSource(string inputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Construct a StreamSource from a byte stream. Normally, a stream should be used rather than a reader, so the XML parser can resolve character encoding specified by the XML declaration.</para><para>If this constructor is used to process a stylesheet, normally setSystemId should also be called, so that relative URI references can be resolved.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/io/File;)V", AccessFlags = 1)]
public StreamSource(global::Java.Io.File inputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Set the byte stream to be used as input. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration.</para><para>If this Source object is used to process a stylesheet, normally setSystemId should also be called, so that relative URL references can be resolved.</para><para></para>
/// </summary>
/// <java-name>
/// setInputStream
/// </java-name>
[Dot42.DexImport("setInputStream", "(Ljava/io/InputStream;)V", AccessFlags = 1)]
public virtual void SetInputStream(global::Java.Io.InputStream inputStream) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the byte stream that was set with setByteStream.</para><para></para>
/// </summary>
/// <returns>
/// <para>The byte stream that was set with setByteStream, or null if setByteStream or the ByteStream constructor was not called. </para>
/// </returns>
/// <java-name>
/// getInputStream
/// </java-name>
[Dot42.DexImport("getInputStream", "()Ljava/io/InputStream;", AccessFlags = 1)]
public virtual global::Java.Io.InputStream GetInputStream() /* MethodBuilder.Create */
{
return default(global::Java.Io.InputStream);
}
/// <summary>
/// <para>Set the input to be a character reader. Normally, a stream should be used rather than a reader, so that the XML parser can resolve character encoding specified by the XML declaration. However, in many cases the encoding of the input stream is already resolved, as in the case of reading XML from a StringReader.</para><para></para>
/// </summary>
/// <java-name>
/// setReader
/// </java-name>
[Dot42.DexImport("setReader", "(Ljava/io/Reader;)V", AccessFlags = 1)]
public virtual void SetReader(global::Java.Io.Reader reader) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the character stream that was set with setReader.</para><para></para>
/// </summary>
/// <returns>
/// <para>The character stream that was set with setReader, or null if setReader or the Reader constructor was not called. </para>
/// </returns>
/// <java-name>
/// getReader
/// </java-name>
[Dot42.DexImport("getReader", "()Ljava/io/Reader;", AccessFlags = 1)]
public virtual global::Java.Io.Reader GetReader() /* MethodBuilder.Create */
{
return default(global::Java.Io.Reader);
}
/// <summary>
/// <para>Set the public identifier for this Source.</para><para>The public identifier is always optional: if the application writer includes one, it will be provided as part of the location information.</para><para></para>
/// </summary>
/// <java-name>
/// setPublicId
/// </java-name>
[Dot42.DexImport("setPublicId", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetPublicId(string publicId) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the public identifier that was set with setPublicId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The public identifier that was set with setPublicId, or null if setPublicId was not called. </para>
/// </returns>
/// <java-name>
/// getPublicId
/// </java-name>
[Dot42.DexImport("getPublicId", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetPublicId() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Set the system ID from a File reference.</para><para></para>
/// </summary>
/// <java-name>
/// setSystemId
/// </java-name>
[Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void SetSystemId(string f) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the system identifier that was set with setSystemId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para>
/// </returns>
/// <java-name>
/// getSystemId
/// </java-name>
[Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetSystemId() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Set the system ID from a File reference.</para><para></para>
/// </summary>
/// <java-name>
/// setSystemId
/// </java-name>
[Dot42.DexImport("setSystemId", "(Ljava/io/File;)V", AccessFlags = 1)]
public virtual void SetSystemId(global::Java.Io.File f) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Get the byte stream that was set with setByteStream.</para><para></para>
/// </summary>
/// <returns>
/// <para>The byte stream that was set with setByteStream, or null if setByteStream or the ByteStream constructor was not called. </para>
/// </returns>
/// <java-name>
/// getInputStream
/// </java-name>
public global::Java.Io.InputStream InputStream
{
[Dot42.DexImport("getInputStream", "()Ljava/io/InputStream;", AccessFlags = 1)]
get{ return GetInputStream(); }
[Dot42.DexImport("setInputStream", "(Ljava/io/InputStream;)V", AccessFlags = 1)]
set{ SetInputStream(value); }
}
/// <summary>
/// <para>Get the character stream that was set with setReader.</para><para></para>
/// </summary>
/// <returns>
/// <para>The character stream that was set with setReader, or null if setReader or the Reader constructor was not called. </para>
/// </returns>
/// <java-name>
/// getReader
/// </java-name>
public global::Java.Io.Reader Reader
{
[Dot42.DexImport("getReader", "()Ljava/io/Reader;", AccessFlags = 1)]
get{ return GetReader(); }
[Dot42.DexImport("setReader", "(Ljava/io/Reader;)V", AccessFlags = 1)]
set{ SetReader(value); }
}
/// <summary>
/// <para>Get the public identifier that was set with setPublicId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The public identifier that was set with setPublicId, or null if setPublicId was not called. </para>
/// </returns>
/// <java-name>
/// getPublicId
/// </java-name>
public string PublicId
{
[Dot42.DexImport("getPublicId", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPublicId(); }
[Dot42.DexImport("setPublicId", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetPublicId(value); }
}
/// <summary>
/// <para>Get the system identifier that was set with setSystemId.</para><para></para>
/// </summary>
/// <returns>
/// <para>The system identifier that was set with setSystemId, or null if setSystemId was not called. </para>
/// </returns>
/// <java-name>
/// getSystemId
/// </java-name>
public string SystemId
{
[Dot42.DexImport("getSystemId", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSystemId(); }
[Dot42.DexImport("setSystemId", "(Ljava/lang/String;)V", AccessFlags = 1)]
set{ SetSystemId(value); }
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
#if UNITY_WINRT && !UNITY_EDITOR
//using MarkerMetro.Unity.WinLegacy.IO;
//using MarkerMetro.Unity.WinLegacy.Reflection;
#endif
namespace Pathfinding {
[System.Serializable]
/** Stores the navigation graphs for the A* Pathfinding System.
* \ingroup relevant
*
* An instance of this class is assigned to AstarPath.astarData, from it you can access all graphs loaded through the #graphs variable.\n
* This class also handles a lot of the high level serialization.
*/
public class AstarData {
/** Shortcut to AstarPath.active */
public static AstarPath active {
get {
return AstarPath.active;
}
}
#region Fields
/** Shortcut to the first NavMeshGraph.
* Updated at scanning time
*/
public NavMeshGraph navmesh {get; private set;}
/** Shortcut to the first GridGraph.
* Updated at scanning time
*/
public GridGraph gridGraph {get; private set;}
/** Shortcut to the first PointGraph.
* Updated at scanning time
*/
public PointGraph pointGraph {get; private set;}
/** All supported graph types.
* Populated through reflection search
*/
public System.Type[] graphTypes {get; private set;}
#if ASTAR_FAST_NO_EXCEPTIONS || UNITY_WINRT || UNITY_WEBGL
/** Graph types to use when building with Fast But No Exceptions for iPhone.
* If you add any custom graph types, you need to add them to this hard-coded list.
*/
public static readonly System.Type[] DefaultGraphTypes = new System.Type[] {
typeof(GridGraph),
typeof(PointGraph),
typeof(NavMeshGraph),
};
#endif
/** All graphs this instance holds.
* This will be filled only after deserialization has completed.
* May contain null entries if graph have been removed.
*/
[System.NonSerialized]
public NavGraph[] graphs = new NavGraph[0];
//Serialization Settings
/** Serialized data for all graphs and settings.
* Stored as a base64 encoded string because otherwise Unity's Undo system would sometimes corrupt the byte data (because it only stores deltas).
*
* This can be accessed as a byte array from the #data property.
*
* \since 3.6.1
*/
[SerializeField]
string dataString;
/** Data from versions from before 3.6.1.
* Used for handling upgrades
* \since 3.6.1
*/
[SerializeField]
[UnityEngine.Serialization.FormerlySerializedAs("data")]
private byte[] upgradeData;
/** Serialized data for all graphs and settings */
private byte[] data {
get {
// Handle upgrading from earlier versions than 3.6.1
if (upgradeData != null && upgradeData.Length > 0) {
data = upgradeData;
upgradeData = null;
}
return dataString != null ? System.Convert.FromBase64String (dataString) : null;
}
set {
dataString = value != null ? System.Convert.ToBase64String (value) : null;
}
}
/** Backup data if deserialization failed.
*/
public byte[] data_backup;
/** Serialized data for cached startup.
* If set, on start the graphs will be deserialized from this file.
*/
public TextAsset file_cachedStartup;
/** Serialized data for cached startup.
*
* \deprecated Deprecated since 3.6, AstarData.file_cachedStartup is now used instead
*/
public byte[] data_cachedStartup;
/** Should graph-data be cached.
* Caching the startup means saving the whole graphs, not only the settings to an internal array (#data_cachedStartup) which can
* be loaded faster than scanning all graphs at startup. This is setup from the editor.
*/
[SerializeField]
public bool cacheStartup;
//End Serialization Settings
#endregion
public byte[] GetData () {
return data;
}
public void SetData (byte[] data) {
this.data = data;
}
/** Loads the graphs from memory, will load cached graphs if any exists */
public void Awake () {
graphs = new NavGraph[0];
if (cacheStartup && file_cachedStartup != null) {
LoadFromCache ();
} else {
DeserializeGraphs ();
}
}
/** Updates shortcuts to the first graph of different types.
* Hard coding references to some graph types is not really a good thing imo. I want to keep it dynamic and flexible.
* But these references ease the use of the system, so I decided to keep them.\n
*/
public void UpdateShortcuts () {
navmesh = (NavMeshGraph)FindGraphOfType (typeof(NavMeshGraph));
gridGraph = (GridGraph)FindGraphOfType (typeof(GridGraph));
pointGraph = (PointGraph)FindGraphOfType (typeof(PointGraph));
}
/** Load from data from #file_cachedStartup */
public void LoadFromCache () {
AstarPath.active.BlockUntilPathQueueBlocked();
if (file_cachedStartup != null) {
var bytes = file_cachedStartup.bytes;
DeserializeGraphs (bytes);
GraphModifier.TriggerEvent (GraphModifier.EventType.PostCacheLoad);
} else {
Debug.LogError ("Can't load from cache since the cache is empty");
}
}
#region Serialization
/** Serializes all graphs settings to a byte array.
* \see DeserializeGraphs(byte[])
*/
public byte[] SerializeGraphs () {
return SerializeGraphs (Pathfinding.Serialization.SerializeSettings.Settings);
}
/** Serializes all graphs settings and optionally node data to a byte array.
* \see DeserializeGraphs(byte[])
* \see Pathfinding.Serialization.SerializeSettings
*/
public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings) {
uint checksum;
return SerializeGraphs (settings, out checksum);
}
/** Main serializer function.
* Serializes all graphs to a byte array
* A similar function exists in the AstarPathEditor.cs script to save additional info */
public byte[] SerializeGraphs (Pathfinding.Serialization.SerializeSettings settings, out uint checksum) {
AstarPath.active.BlockUntilPathQueueBlocked();
var sr = new Pathfinding.Serialization.AstarSerializer(this, settings);
sr.OpenSerialize();
SerializeGraphsPart (sr);
byte[] bytes = sr.CloseSerialize();
checksum = sr.GetChecksum ();
return bytes;
}
/** Serializes common info to the serializer.
* Common info is what is shared between the editor serialization and the runtime serializer.
* This is mostly everything except the graph inspectors which serialize some extra data in the editor
*/
public void SerializeGraphsPart (Pathfinding.Serialization.AstarSerializer sr) {
sr.SerializeGraphs(graphs);
sr.SerializeNodes();
sr.SerializeExtraInfo();
}
/** Deserializes graphs from #data */
public void DeserializeGraphs () {
if (data != null) {
DeserializeGraphs (data);
}
}
/** Destroys all graphs and sets graphs to null */
void ClearGraphs () {
if ( graphs == null ) return;
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] != null) graphs[i].OnDestroy ();
}
graphs = null;
UpdateShortcuts ();
}
public void OnDestroy () {
ClearGraphs ();
}
/** Deserializes graphs from the specified byte array.
* If an error occured, it will try to deserialize using the old deserializer.
* A warning will be logged if all deserializers failed.
*/
public void DeserializeGraphs (byte[] bytes) {
AstarPath.active.BlockUntilPathQueueBlocked();
try {
if (bytes != null) {
var sr = new Pathfinding.Serialization.AstarSerializer(this);
if (sr.OpenDeserialize(bytes)) {
DeserializeGraphsPart (sr);
sr.CloseDeserialize();
UpdateShortcuts ();
} else {
Debug.Log ("Invalid data file (cannot read zip).\nThe data is either corrupt or it was saved using a 3.0.x or earlier version of the system");
}
} else {
throw new System.ArgumentNullException ("bytes");
}
active.VerifyIntegrity ();
} catch (System.Exception e) {
Debug.LogWarning ("Caught exception while deserializing data.\n"+e);
data_backup = bytes;
}
}
/** Deserializes graphs from the specified byte array additively.
* If an error ocurred, it will try to deserialize using the old deserializer.
* A warning will be logged if all deserializers failed.
* This function will add loaded graphs to the current ones
*/
public void DeserializeGraphsAdditive (byte[] bytes) {
AstarPath.active.BlockUntilPathQueueBlocked();
try {
if (bytes != null) {
var sr = new Pathfinding.Serialization.AstarSerializer(this);
if (sr.OpenDeserialize(bytes)) {
DeserializeGraphsPartAdditive (sr);
sr.CloseDeserialize();
} else {
Debug.Log ("Invalid data file (cannot read zip).");
}
} else {
throw new System.ArgumentNullException ("bytes");
}
active.VerifyIntegrity ();
} catch (System.Exception e) {
Debug.LogWarning ("Caught exception while deserializing data.\n"+e);
}
}
/** Deserializes common info.
* Common info is what is shared between the editor serialization and the runtime serializer.
* This is mostly everything except the graph inspectors which serialize some extra data in the editor
*/
public void DeserializeGraphsPart (Pathfinding.Serialization.AstarSerializer sr) {
ClearGraphs ();
graphs = sr.DeserializeGraphs ();
sr.DeserializeExtraInfo();
//Assign correct graph indices.
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] == null) continue;
graphs[i].GetNodes (node => {
node.GraphIndex = (uint)i;
return true;
});
}
sr.PostDeserialization();
}
/** Deserializes common info additively
* Common info is what is shared between the editor serialization and the runtime serializer.
* This is mostly everything except the graph inspectors which serialize some extra data in the editor
*/
public void DeserializeGraphsPartAdditive (Pathfinding.Serialization.AstarSerializer sr) {
if (graphs == null) graphs = new NavGraph[0];
var gr = new List<NavGraph>(graphs);
// Set an offset so that the deserializer will load
// the graphs with the correct graph indexes
sr.SetGraphIndexOffset (gr.Count);
gr.AddRange (sr.DeserializeGraphs ());
graphs = gr.ToArray();
//Assign correct graph indices. Issue #21
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] == null) continue;
graphs[i].GetNodes (node => {
node.GraphIndex = (uint)i;
return true;
});
}
sr.DeserializeExtraInfo();
sr.PostDeserialization();
for (int i=0;i<graphs.Length;i++) {
for (int j=i+1;j<graphs.Length;j++) {
if (graphs[i] != null && graphs[j] != null && graphs[i].guid == graphs[j].guid) {
Debug.LogWarning ("Guid Conflict when importing graphs additively. Imported graph will get a new Guid.\nThis message is (relatively) harmless.");
graphs[i].guid = Pathfinding.Util.Guid.NewGuid ();
break;
}
}
}
}
#endregion
/** Find all graph types supported in this build.
* Using reflection, the assembly is searched for types which inherit from NavGraph. */
public void FindGraphTypes () {
#if !ASTAR_FAST_NO_EXCEPTIONS && !UNITY_WINRT && !UNITY_WEBGL
var asm = Assembly.GetAssembly (typeof(AstarPath));
System.Type[] types = asm.GetTypes ();
var graphList = new List<System.Type> ();
foreach (System.Type type in types) {
#if NETFX_CORE && !UNITY_EDITOR
System.Type baseType = type.GetTypeInfo().BaseType;
#else
System.Type baseType = type.BaseType;
#endif
while (baseType != null) {
if (System.Type.Equals ( baseType, typeof(NavGraph) )) {
graphList.Add (type);
break;
}
#if NETFX_CORE && !UNITY_EDITOR
baseType = baseType.GetTypeInfo().BaseType;
#else
baseType = baseType.BaseType;
#endif
}
}
graphTypes = graphList.ToArray ();
#else
graphTypes = DefaultGraphTypes;
#endif
}
#region GraphCreation
/**
* \returns A System.Type which matches the specified \a type string. If no mathing graph type was found, null is returned
*
* \deprecated
*/
[System.Obsolete("If really necessary. Use System.Type.GetType instead.")]
public System.Type GetGraphType (string type) {
for (int i=0;i<graphTypes.Length;i++) {
if (graphTypes[i].Name == type) {
return graphTypes[i];
}
}
return null;
}
/** Creates a new instance of a graph of type \a type. If no matching graph type was found, an error is logged and null is returned
* \returns The created graph
* \see CreateGraph(System.Type)
*
* \deprecated
*/
[System.Obsolete("Use CreateGraph(System.Type) instead")]
public NavGraph CreateGraph (string type) {
Debug.Log ("Creating Graph of type '"+type+"'");
for (int i=0;i<graphTypes.Length;i++) {
if (graphTypes[i].Name == type) {
return CreateGraph (graphTypes[i]);
}
}
Debug.LogError ("Graph type ("+type+") wasn't found");
return null;
}
/** Creates a new graph instance of type \a type
* \see CreateGraph(string) */
public NavGraph CreateGraph (System.Type type) {
var g = System.Activator.CreateInstance (type) as NavGraph;
g.active = active;
return g;
}
/** Adds a graph of type \a type to the #graphs array
*
* \deprecated
*/
[System.Obsolete("Use AddGraph(System.Type) instead")]
public NavGraph AddGraph (string type) {
NavGraph graph = null;
for (int i=0;i<graphTypes.Length;i++) {
if (graphTypes[i].Name == type) {
graph = CreateGraph (graphTypes[i]);
}
}
if (graph == null) {
Debug.LogError ("No NavGraph of type '"+type+"' could be found");
return null;
}
AddGraph (graph);
return graph;
}
/** Adds a graph of type \a type to the #graphs array */
public NavGraph AddGraph (System.Type type) {
NavGraph graph = null;
for (int i=0;i<graphTypes.Length;i++) {
if (System.Type.Equals (graphTypes[i], type)) {
graph = CreateGraph (graphTypes[i]);
}
}
if (graph == null) {
Debug.LogError ("No NavGraph of type '"+type+"' could be found, "+graphTypes.Length+" graph types are avaliable");
return null;
}
AddGraph (graph);
return graph;
}
/** Adds the specified graph to the #graphs array */
public void AddGraph (NavGraph graph) {
// Make sure to not interfere with pathfinding
AstarPath.active.BlockUntilPathQueueBlocked();
//Try to fill in an empty position
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] == null) {
graphs[i] = graph;
graph.active = active;
graph.Awake ();
graph.graphIndex = (uint)i;
UpdateShortcuts ();
return;
}
}
if (graphs != null && graphs.Length >= GraphNode.MaxGraphIndex) {
throw new System.Exception("Graph Count Limit Reached. You cannot have more than " + GraphNode.MaxGraphIndex +
" graphs. Some compiler directives can change this limit, e.g ASTAR_MORE_AREAS, look under the " +
"'Optimizations' tab in the A* Inspector");
}
//Add a new entry to the list
var ls = new List<NavGraph> (graphs);
ls.Add (graph);
graphs = ls.ToArray ();
UpdateShortcuts ();
graph.active = active;
graph.Awake ();
graph.graphIndex = (uint)(graphs.Length-1);
}
/** Removes the specified graph from the #graphs array and Destroys it in a safe manner.
* To avoid changing graph indices for the other graphs, the graph is simply nulled in the array instead
* of actually removing it from the array.
* The empty position will be reused if a new graph is added.
*
* \returns True if the graph was sucessfully removed (i.e it did exist in the #graphs array). False otherwise.
*
*
* \version Changed in 3.2.5 to call SafeOnDestroy before removing
* and nulling it in the array instead of removing the element completely in the #graphs array.
*
*/
public bool RemoveGraph (NavGraph graph) {
// Make sure all graph updates and other callbacks are done
active.FlushWorkItems (false, true);
// Make sure the pathfinding threads are stopped
active.BlockUntilPathQueueBlocked ();
// //Safe OnDestroy is called since there is a risk that the pathfinding is searching through the graph right now,
// //and if we don't wait until the search has completed we could end up with evil NullReferenceExceptions
graph.OnDestroy ();
int i = System.Array.IndexOf (graphs, graph);
if (i == -1) {
return false;
}
graphs[i] = null;
UpdateShortcuts ();
return true;
}
#endregion
#region GraphUtility
/** Returns the graph which contains the specified node.
* The graph must be in the #graphs array.
*
* \returns Returns the graph which contains the node. Null if the graph wasn't found
*/
public static NavGraph GetGraph (GraphNode node) {
if (node == null) return null;
AstarPath script = AstarPath.active;
if (script == null) return null;
AstarData data = script.astarData;
if (data == null) return null;
if (data.graphs == null) return null;
uint graphIndex = node.GraphIndex;
if (graphIndex >= data.graphs.Length) {
return null;
}
return data.graphs[(int)graphIndex];
}
/** Returns the first graph of type \a type found in the #graphs array. Returns null if none was found */
public NavGraph FindGraphOfType (System.Type type) {
if ( graphs != null ) {
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] != null && System.Type.Equals (graphs[i].GetType (), type)) {
return graphs[i];
}
}
}
return null;
}
/** Loop through this function to get all graphs of type 'type'
* \code foreach (GridGraph graph in AstarPath.astarData.FindGraphsOfType (typeof(GridGraph))) {
* //Do something with the graph
* } \endcode
* \see AstarPath.RegisterSafeNodeUpdate */
public IEnumerable FindGraphsOfType (System.Type type) {
if (graphs == null) { yield break; }
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] != null && System.Type.Equals (graphs[i].GetType (), type)) {
yield return graphs[i];
}
}
}
/** All graphs which implements the UpdateableGraph interface
* \code foreach (IUpdatableGraph graph in AstarPath.astarData.GetUpdateableGraphs ()) {
* //Do something with the graph
* } \endcode
* \see AstarPath.RegisterSafeNodeUpdate
* \see Pathfinding.IUpdatableGraph */
public IEnumerable GetUpdateableGraphs () {
if (graphs == null) { yield break; }
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] is IUpdatableGraph) {
yield return graphs[i];
}
}
}
/** All graphs which implements the UpdateableGraph interface
* \code foreach (IRaycastableGraph graph in AstarPath.astarData.GetRaycastableGraphs ()) {
* //Do something with the graph
* } \endcode
* \see Pathfinding.IRaycastableGraph*/
public IEnumerable GetRaycastableGraphs () {
if (graphs == null) { yield break; }
for (int i=0;i<graphs.Length;i++) {
if (graphs[i] is IRaycastableGraph) {
yield return graphs[i];
}
}
}
/** Gets the index of the NavGraph in the #graphs array */
public int GetGraphIndex (NavGraph graph) {
if (graph == null) throw new System.ArgumentNullException ("graph");
if ( graphs != null ) {
for (int i=0;i<graphs.Length;i++) {
if (graph == graphs[i]) {
return i;
}
}
}
Debug.LogError ("Graph doesn't exist");
return -1;
}
#endregion
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* 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;
using System.IO;
using System.Text;
using log4net;
using log4net.Core;
using log4net.ObjectRenderer;
using MindTouch.Tasking;
namespace MindTouch {
/// <summary>
/// Provides extension and static helper methods for working with a log4Net <see cref="ILog"/> instance.
/// </summary>
public static class LogUtils {
//--- Constants ---
private static readonly Type _type = typeof(LogUtils);
//--- Extension Methods ---
/// <summary>
/// Short-cut for <see cref="ILogger.IsEnabledFor"/> with <see cref="Level.Trace"/>.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <returns><see langword="True"/> if the the logger is running trace loggging.</returns>
public static bool IsTraceEnabled(this ILog log) {
return log.Logger.IsEnabledFor(Level.Trace);
}
/// <summary>
/// Log a method call at <see cref="Level.Trace"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void TraceMethodCall(this ILog log, string method, params object[] args) {
if(log.IsTraceEnabled()) {
log.Logger.Log(_type, Level.Trace, string.Format("{0}{1}", method, Render(args)), null);
}
}
/// <summary>
/// Log an exception in a specific method at <see cref="Level.Trace"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void TraceExceptionMethodCall(this ILog log, Exception exception, string method, params object[] args) {
if(log.IsTraceEnabled()) {
log.Logger.Log(_type, Level.Trace, string.Format("{0}{1}", method, Render(args)), exception);
}
}
/// <summary>
/// Log a formatted string at <see cref="Level.Trace"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="format">A format string.</param>
/// <param name="args">Format string parameters.</param>
public static void TraceFormat(this ILog log, string format, params object[] args) {
if(log.IsTraceEnabled()) {
log.Logger.Log(_type, Level.Trace, string.Format(format, args), null);
}
}
/// <summary>
/// Log a method call at <see cref="Level.Debug"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void DebugMethodCall(this ILog log, string method, params object[] args) {
if(log.IsDebugEnabled) {
log.DebugFormat("{0}{1}", method, Render(args));
}
}
/// <summary>
/// Log an exception in a specific method at <see cref="Level.Debug"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void DebugExceptionMethodCall(this ILog log, Exception exception, string method, params object[] args) {
if(log.IsDebugEnabled) {
log.Debug(string.Format("{0}{1}", method, Render(args)), exception);
}
}
/// <summary>
/// Log an exception with a formatted text message.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="message">Message format string.</param>
/// <param name="args">Format arguments.</param>
public static void DebugFormat(this ILog log, Exception exception, string message, params object[] args) {
if(log.IsDebugEnabled) {
log.Debug(string.Format(message,args),exception);
}
}
/// <summary>
/// Log a method call at <see cref="Level.Info"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void InfoMethodCall(this ILog log, string method, params object[] args) {
if(log.IsInfoEnabled) {
log.InfoFormat("{0}{1}", method, Render(args));
}
}
/// <summary>
/// Log a method call at <see cref="Level.Warn"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void WarnMethodCall(this ILog log, string method, params object[] args) {
if(log.IsWarnEnabled) {
log.WarnFormat("{0}{1}", method, Render(args));
}
}
/// <summary>
/// Log an exception in a specific method at <see cref="Level.Warn"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void WarnExceptionMethodCall(this ILog log, Exception exception, string method, params object[] args) {
if(log.IsWarnEnabled) {
log.Warn(string.Format("{0}{1}", method, Render(args)), exception);
}
}
/// <summary>
/// Log a formatted string message about an exception at <see cref="Level.Warn"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="format">A format string.</param>
/// <param name="args">Format string parameters.</param>
public static void WarnExceptionFormat(this ILog log, Exception exception, string format, params object[] args) {
if(log.IsWarnEnabled) {
log.Warn(string.Format(format, args), exception);
}
}
/// <summary>
/// Log an exception in a specific method at <see cref="Level.Error"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="method">Method name.</param>
/// <param name="args">Method arguments.</param>
public static void ErrorExceptionMethodCall(this ILog log, Exception exception, string method, params object[] args) {
if(log.IsErrorEnabled) {
log.Error(string.Format("{0}{1}", method, Render(args)), exception);
}
}
/// <summary>
/// Log a formatted string message about an exception at <see cref="Level.Error"/> level.
/// </summary>
/// <param name="log">Logger instance.</param>
/// <param name="exception">Exception that triggered this log call.</param>
/// <param name="format">A format string.</param>
/// <param name="args">Format string parameters.</param>
public static void ErrorExceptionFormat(this ILog log, Exception exception, string format, params object[] args) {
if(log.IsErrorEnabled) {
log.Error(string.Format(format, args), exception);
}
}
//--- Class Methods ---
/// <summary>
/// Create an <see cref="ILog"/> instance for the enclosing type.
/// </summary>
/// <returns></returns>
public static ILog CreateLog() {
var frame = new System.Diagnostics.StackFrame(1, false);
var type = frame.GetMethod().DeclaringType;
return LogManager.GetLogger(type);
}
/// <summary>
/// This methods is deprecated please use <see cref="CreateLog()"/>instead.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
[Obsolete("This methods is deprecated please use LogUtils.CreateLog() instead.")]
public static ILog CreateLog<T>() {
return LogManager.GetLogger(typeof(T));
}
/// <summary>
/// Create an <see cref="ILog"/> instance for a given type.
/// </summary>
/// <param name="classType">Type of class to create the logger for</param>
/// <returns></returns>
public static ILog CreateLog(Type classType) {
return LogManager.GetLogger(classType);
}
private static string Render(ICollection args) {
if((args == null) || (args.Count == 0)) {
return string.Empty;
}
var builder = new StringBuilder();
Render(builder, args);
return builder.ToString();
}
private static void Render(StringBuilder builder, object arg) {
if(arg is ICollection) {
builder.Append("(");
RenderCollection(builder, (ICollection)arg);
builder.Append(")");
} else {
builder.Append(arg);
}
}
private static void RenderCollection(StringBuilder builder, ICollection args) {
if(args is IDictionary) {
var dict = (IDictionary)args;
var first = true;
foreach(var key in dict.Keys) {
// append ',' if need be
if(!first) {
builder.Append(", ");
}
first = false;
// append item in collection
try {
var arg = dict[key];
builder.Append(key);
builder.Append("=");
Render(builder, arg);
} catch { }
}
} else {
var first = true;
foreach(var arg in args) {
// append ',' if need be
if(!first) {
builder.Append(", ");
}
first = false;
// append item in collection
try {
Render(builder, arg);
} catch { }
}
}
}
}
}
namespace MindTouch.Logging {
internal class ExceptionRenderer : IObjectRenderer {
//--- Methods ---
public void RenderObject(RendererMap rendererMap, object obj, TextWriter writer) {
if(obj is Exception) {
writer.Write(((Exception)obj).GetCoroutineStackTrace());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;
namespace com.github.yedijas.util
{
class ExcelUtil
{
#region static methods
/// <summary>
/// Export data in DataTable to Excel file.
/// </summary>
/// <param name="DataToExport">DataTable contains data to export.</param>
/// <param name="Path">Target path of export without the file name.</param>
/// <param name="FileName">Name of the target excel file.</param>
public static void DataTableToExcel(DataTable DataToExport, string Path, string FileName)
{
if (!string.IsNullOrEmpty(
System.IO.Path.GetExtension(FileName)))
{
DataTableToExcel(DataToExport, (Path + @"\" + FileName));
}
else
{
DataTableToExcel(DataToExport, (Path + @"\" + FileName + ".xls"));
}
}
/// <summary>
/// Export data in DataTable to Excel file.
/// </summary>
/// <param name="DataToExport">DataTable contains data to export.</param>
/// <param name="CompleteFilePath">Target path of export complete with
/// the file name and extension.</param>
public static void DataTableToExcel(DataTable DataToExport, string CompleteFilePath)
{
Excel.Application excelApplication = null;
Excel.Workbook excelWorkbook = null;
Excel.Worksheet excelWorkSheet = null;
#region logic
if (DataToExport == null || DataToExport.Columns.Count == 0)
throw new Exception("No data in DataTable");
try
{
excelApplication = new Microsoft.Office.Interop.Excel.Application();
excelWorkbook = excelApplication.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
excelWorkSheet = (Excel.Worksheet)excelWorkbook.Worksheets.get_Item(1);
for (int i = 0; i < DataToExport.Columns.Count; i++)
{
excelWorkSheet.Cells[1, (i + 1)] = DataToExport.Columns[i].ColumnName;
}
for (int i = 0; i < DataToExport.Rows.Count; i++)
{
for (int j = 0; j < DataToExport.Columns.Count; j++)
{
excelWorkSheet.Cells[(i + 2), (j + 1)] = DataToExport.Rows[i][j];
}
}
excelWorkSheet.UsedRange.NumberFormat = "@";
try
{
excelWorkSheet.SaveAs(CompleteFilePath,
Excel.XlFileFormat.xlWorkbookNormal,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing
);
}
catch (Exception SaveExcelFileEx)
{
throw SaveExcelFileEx;
}
}
#endregion
#region exception handling
catch (Exception AllEx)
{
throw AllEx;
}
finally
{
if (excelWorkSheet != null &&
System.Runtime.InteropServices.Marshal.IsComObject(excelWorkSheet))
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkSheet);
}
excelWorkSheet = null;
excelWorkbook.Close(true, Type.Missing, Type.Missing);
if (excelWorkbook != null &&
System.Runtime.InteropServices.Marshal.IsComObject(excelWorkbook))
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
}
excelWorkSheet = null;
if (excelApplication != null)
{
excelApplication.Quit();
}
if (excelApplication != null &&
System.Runtime.InteropServices.Marshal.IsComObject(excelApplication))
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication);
}
excelApplication = null;
GC.Collect();
}
#endregion
}
/// <summary>
/// Export table in Excel to DataTable.
/// Good for data which started from A1 to end.
/// Row 1 will be automatically treated as header.
/// Total row and column will automatically counted.
/// </summary>
/// <param name="FileName">Excel file name complete with path and extension.</param>
/// <returns>DataTable containing data from exce file.</returns>
public static DataTable ExcelToDataTable(string FileName)
{
DataTable result = ExcelToDataTable(FileName, 1, 1, 0, 0);
return result;
}
/// <summary>
/// Export table in Excel to DataTable.
/// Good for data which are not started from A1 to end.
/// Total row and column will be automatically counted.
/// </summary>
/// <param name="FileName">Excel file name complete with path and extension.</param>
/// <param name="HeaderRowIndex">Row number that contains header.</param>
/// <param name="ColumnStartIndex">Start Index of column.</param>
/// <returns>DataTable containing data from exce file.</returns>
public static DataTable ExcelToDataTable(string FileName,
int ColumnStartIndex,
int HeaderRowIndex)
{
DataTable result = ExcelToDataTable(FileName, HeaderRowIndex, ColumnStartIndex, 0, 0);
return result;
}
/// <summary>
/// Export table in Excel to DataTable.
/// Good for data which are not started from A1 and ended to specific row number.
/// Total column will be automatically counted.
/// </summary>
/// <param name="FileName">Excel file name complete with path and extension.</param>
/// <param name="HeaderRowIndex">Row number that contains header.</param>
/// <param name="ColumnStartIndex">Start Index of column.</param>
/// <param name="TotalRow">Total row that contains data in excel table.</param>
/// <returns>DataTable containing data from exce file.</returns>
public static DataTable ExcelToDataTable(string FileName,
int HeaderRowIndex,
int ColumnStartIndex,
int TotalRow)
{
DataTable result = ExcelToDataTable(FileName, HeaderRowIndex, ColumnStartIndex, TotalRow, 0);
return result;
}
/// <summary>
/// Export table in Excel to DataTable.
/// Total column will be automatically counted.
/// </summary>
/// <param name="FileName">Excel file name complete with path and extension.</param>
/// <param name="HeaderRowIndex">Row number that contains header.</param>
/// <param name="ColumnStartIndex">Start Index of column.</param>
/// <param name="TotalRow">Total row that contains data in excel table.</param>
/// <param name="WorkSheetIndex">Index of worksheet containing data to take.</param>
/// <returns>DataTable containing data from exce file.</returns>
public static DataTable ExcelToDataTable(string FileName,
int HeaderRowIndex,
int ColumnStartIndex,
int TotalRow,
int WorkSheetIndex)
{
DataTable result = null;
Excel.Application excelApplication = null;
Excel.Workbook excelWorkbook = null;
Excel.Worksheet excelWorksheet = null;
#region logic
try
{
excelApplication = new Microsoft.Office.Interop.Excel.Application();
excelWorkbook = excelApplication.Workbooks.Open(FileName,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
if (WorkSheetIndex == 0)
{// default active
excelWorksheet = (Excel.Worksheet)excelWorkbook.ActiveSheet;
}
else
{
excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets.get_Item(WorkSheetIndex);
}
if (TotalRow == 0)
{// default is checked
TotalRow = GetTotalRowsFromWorksheet(excelWorksheet);
}
int TotalColumn = GetTotalTableColumnFromWorksheet(excelWorksheet,
HeaderRowIndex, ColumnStartIndex);
List<string> headers = GetTableHeader(excelWorksheet, HeaderRowIndex);
try
{
foreach (string header in headers)
{
DataColumn tempColumn = new DataColumn();
tempColumn.ColumnName = header;
tempColumn.DataType = Type.GetType("System.String");
result.Columns.Add(tempColumn);
}
for (int i = HeaderRowIndex + 1; i <= (HeaderRowIndex + TotalRow); i++)
{
DataRow tempRow = result.NewRow();
for (int j = ColumnStartIndex; j < (ColumnStartIndex + TotalColumn); i++)
{
tempRow.ItemArray[j] = (excelWorksheet.Cells[i, j] as Excel.Range)
.Value2.ToString();
}
result.Rows.Add(tempRow);
}
}
catch
{
throw;
}
}
#endregion
#region exception handling
catch (Exception AllEx)
{
throw AllEx;
}
finally
{
if (excelWorksheet != null &&
System.Runtime.InteropServices.Marshal.IsComObject(excelWorksheet))
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorksheet);
}
excelWorksheet = null;
excelWorkbook.Close(false, Type.Missing, Type.Missing);
if (excelWorkbook != null &&
System.Runtime.InteropServices.Marshal.IsComObject(excelWorkbook))
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
}
excelWorkbook = null;
if (excelApplication != null)
{
excelApplication.Quit();
}
if (excelApplication != null &&
System.Runtime.InteropServices.Marshal.IsComObject(excelApplication))
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication);
}
excelApplication = null;
GC.Collect();
}
#endregion
return result;
}
/// <summary>
/// Get total column filled with data in worksheet.
/// </summary>
/// <param name="ExcelWorksheet">Worksheet containing data to count.</param>
/// <returns>Number of used (contain data) columns.</returns>
public static int GetTotalColumnFromWorksheet(Excel.Worksheet ExcelWorksheet)
{
ExcelWorksheet.Columns.ClearFormats();
ExcelWorksheet.Rows.ClearFormats();
return ExcelWorksheet.UsedRange.Columns.Count;
}
/// <summary>
/// Get total rows filled with data in worksheet.
/// </summary>
/// <param name="ExcelWorksheet">Worksheet containing data to count.</param>
/// <returns>Number of used (contain data) rows.</returns>
public static int GetTotalRowsFromWorksheet(Excel.Worksheet ExcelWorksheet)
{
ExcelWorksheet.Columns.ClearFormats();
ExcelWorksheet.Rows.ClearFormats();
return ExcelWorksheet.UsedRange.Columns.Count;
}
/// <summary>
/// Get total column in worksheet given the row with header.
/// </summary>
/// <param name="ExcelWorksheet">Worksheet containing data to count.</param>
/// <param name="HeaderRowIndex">Row index which header is located.</param>
/// <param name="ColumnStartIndex">Start index of column. Set 1 for column A.</param>
/// <returns>Number of used (contain data) columns.</returns>
public static int GetTotalTableColumnFromWorksheet(Excel.Worksheet ExcelWorksheet,
int HeaderRowIndex,
int ColumnStartIndex)
{
ExcelWorksheet.Columns.ClearFormats();
ExcelWorksheet.Rows.ClearFormats();
int index = ColumnStartIndex;
bool flag = true;
while (flag)
{
if (string.IsNullOrEmpty(
(ExcelWorksheet.Cells[HeaderRowIndex, index] as Excel.Range)
.Value2.ToString()))
{
flag = false;
}
index++;
}
return index;
}
/// <summary>
/// Get the table header in Worksheet, given the header index.
/// </summary>
/// <param name="ExcelWorksheet">Worksheet containing data to get.</param>
/// <param name="HeaderRowIndex">Index of row that contain the header.</param>
/// <returns>List of string containing header.</returns>
public static List<string> GetTableHeader(Excel.Worksheet ExcelWorksheet,
int HeaderRowIndex)
{
List<string> result = new List<string>();
int TotalColumn = GetTotalColumnFromWorksheet(ExcelWorksheet);
for (int i = 1; i <= TotalColumn; i++)
{
result.Add((ExcelWorksheet.Cells[HeaderRowIndex, i] as Excel.Range).Value2.ToString());
}
return result;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace Python.Runtime
{
/// <summary>
/// Managed class that provides the implementation for reflected types.
/// Managed classes and value types are represented in Python by actual
/// Python type objects. Each of those type objects is associated with
/// an instance of ClassObject, which provides its implementation.
/// </summary>
/// <remarks>
/// interface used to identify which C# types were dynamically created as python subclasses
/// </remarks>
public interface IPythonDerivedType
{
}
[Serializable]
internal class ClassDerivedObject : ClassObject
{
private static Dictionary<string, AssemblyBuilder> assemblyBuilders;
private static Dictionary<Tuple<string, string>, ModuleBuilder> moduleBuilders;
static ClassDerivedObject()
{
assemblyBuilders = new Dictionary<string, AssemblyBuilder>();
moduleBuilders = new Dictionary<Tuple<string, string>, ModuleBuilder>();
}
public static void Reset()
{
assemblyBuilders = new Dictionary<string, AssemblyBuilder>();
moduleBuilders = new Dictionary<Tuple<string, string>, ModuleBuilder>();
}
internal ClassDerivedObject(Type tp) : base(tp)
{
}
/// <summary>
/// Implements __new__ for derived classes of reflected classes.
/// </summary>
public new static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw)
{
var cls = GetManagedObject(tp) as ClassDerivedObject;
// call the managed constructor
object obj = cls.binder.InvokeRaw(IntPtr.Zero, args, kw);
if (obj == null)
{
return IntPtr.Zero;
}
// return the pointer to the python object
// (this indirectly calls ClassDerivedObject.ToPython)
return Converter.ToPython(obj, cls.GetType());
}
public new static void tp_dealloc(IntPtr ob)
{
var self = (CLRObject)GetManagedObject(ob);
// don't let the python GC destroy this object
Runtime.PyObject_GC_UnTrack(self.pyHandle);
// The python should now have a ref count of 0, but we don't actually want to
// deallocate the object until the C# object that references it is destroyed.
// So we don't call PyObject_GC_Del here and instead we set the python
// reference to a weak reference so that the C# object can be collected.
GCHandle gc = GCHandle.Alloc(self, GCHandleType.Weak);
int gcOffset = ObjectOffset.magic(Runtime.PyObject_TYPE(self.pyHandle));
Marshal.WriteIntPtr(self.pyHandle, gcOffset, (IntPtr)gc);
self.gcHandle.Free();
self.gcHandle = gc;
}
/// <summary>
/// Called from Converter.ToPython for types that are python subclasses of managed types.
/// The referenced python object is returned instead of a new wrapper.
/// </summary>
internal static IntPtr ToPython(IPythonDerivedType obj)
{
// derived types have a __pyobj__ field that gets set to the python
// object in the overridden constructor
FieldInfo fi = obj.GetType().GetField("__pyobj__");
var self = (CLRObject)fi.GetValue(obj);
Runtime.XIncref(self.pyHandle);
// when the C# constructor creates the python object it starts as a weak
// reference with a reference count of 0. Now we're passing this object
// to Python the reference count needs to be incremented and the reference
// needs to be replaced with a strong reference to stop the C# object being
// collected while Python still has a reference to it.
if (Runtime.Refcount(self.pyHandle) == 1)
{
#if PYTHON_WITH_PYDEBUG
Runtime._Py_NewReference(self.pyHandle);
#endif
GCHandle gc = GCHandle.Alloc(self, GCHandleType.Normal);
Marshal.WriteIntPtr(self.pyHandle, ObjectOffset.magic(self.tpHandle), (IntPtr)gc);
self.gcHandle.Free();
self.gcHandle = gc;
// now the object has a python reference it's safe for the python GC to track it
Runtime.PyObject_GC_Track(self.pyHandle);
}
return self.pyHandle;
}
/// <summary>
/// Creates a new managed type derived from a base type with any virtual
/// methods overridden to call out to python if the associated python
/// object has overridden the method.
/// </summary>
internal static Type CreateDerivedType(string name,
Type baseType,
IntPtr py_dict,
string namespaceStr,
string assemblyName,
string moduleName = "Python.Runtime.Dynamic.dll")
{
if (null != namespaceStr)
{
name = namespaceStr + "." + name;
}
if (null == assemblyName)
{
assemblyName = "Python.Runtime.Dynamic";
}
ModuleBuilder moduleBuilder = GetModuleBuilder(assemblyName, moduleName);
Type baseClass = baseType;
var interfaces = new List<Type> { typeof(IPythonDerivedType) };
// if the base type is an interface then use System.Object as the base class
// and add the base type to the list of interfaces this new class will implement.
if (baseType.IsInterface)
{
interfaces.Add(baseType);
baseClass = typeof(object);
}
TypeBuilder typeBuilder = moduleBuilder.DefineType(name,
TypeAttributes.Public | TypeAttributes.Class,
baseClass,
interfaces.ToArray());
// add a field for storing the python object pointer
// FIXME: fb not used
FieldBuilder fb = typeBuilder.DefineField("__pyobj__", typeof(CLRObject), FieldAttributes.Public);
// override any constructors
ConstructorInfo[] constructors = baseClass.GetConstructors();
foreach (ConstructorInfo ctor in constructors)
{
AddConstructor(ctor, baseType, typeBuilder);
}
// Override any properties explicitly overridden in python
var pyProperties = new HashSet<string>();
if (py_dict != IntPtr.Zero && Runtime.PyDict_Check(py_dict))
{
Runtime.XIncref(py_dict);
using (var dict = new PyDict(py_dict))
using (PyObject keys = dict.Keys())
{
foreach (PyObject pyKey in keys)
{
using (PyObject value = dict[pyKey])
{
if (value.HasAttr("_clr_property_type_"))
{
string propertyName = pyKey.ToString();
pyProperties.Add(propertyName);
// Add the property to the type
AddPythonProperty(propertyName, value, typeBuilder);
}
}
}
}
}
// override any virtual methods not already overridden by the properties above
MethodInfo[] methods = baseType.GetMethods();
var virtualMethods = new HashSet<string>();
foreach (MethodInfo method in methods)
{
if (!method.Attributes.HasFlag(MethodAttributes.Virtual) |
method.Attributes.HasFlag(MethodAttributes.Final))
{
continue;
}
// skip if this property has already been overridden
if ((method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
&& pyProperties.Contains(method.Name.Substring(4)))
{
continue;
}
// keep track of the virtual methods redirected to the python instance
virtualMethods.Add(method.Name);
// override the virtual method to call out to the python method, if there is one.
AddVirtualMethod(method, baseType, typeBuilder);
}
// Add any additional methods and properties explicitly exposed from Python.
if (py_dict != IntPtr.Zero && Runtime.PyDict_Check(py_dict))
{
Runtime.XIncref(py_dict);
using (var dict = new PyDict(py_dict))
using (PyObject keys = dict.Keys())
{
foreach (PyObject pyKey in keys)
{
using (PyObject value = dict[pyKey])
{
if (value.HasAttr("_clr_return_type_") && value.HasAttr("_clr_arg_types_"))
{
string methodName = pyKey.ToString();
// if this method has already been redirected to the python method skip it
if (virtualMethods.Contains(methodName))
{
continue;
}
// Add the method to the type
AddPythonMethod(methodName, value, typeBuilder);
}
}
}
}
}
// add the destructor so the python object created in the constructor gets destroyed
MethodBuilder methodBuilder = typeBuilder.DefineMethod("Finalize",
MethodAttributes.Family |
MethodAttributes.Virtual |
MethodAttributes.HideBySig,
CallingConventions.Standard,
typeof(void),
Type.EmptyTypes);
ILGenerator il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, typeof(PythonDerivedType).GetMethod("Finalize"));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, baseClass.GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance));
il.Emit(OpCodes.Ret);
Type type = typeBuilder.CreateType();
// scan the assembly so the newly added class can be imported
Assembly assembly = Assembly.GetAssembly(type);
AssemblyManager.ScanAssembly(assembly);
// FIXME: assemblyBuilder not used
AssemblyBuilder assemblyBuilder = assemblyBuilders[assemblyName];
return type;
}
/// <summary>
/// Add a constructor override that calls the python ctor after calling the base type constructor.
/// </summary>
/// <param name="ctor">constructor to be called before calling the python ctor</param>
/// <param name="baseType">Python callable object</param>
/// <param name="typeBuilder">TypeBuilder for the new type the ctor is to be added to</param>
private static void AddConstructor(ConstructorInfo ctor, Type baseType, TypeBuilder typeBuilder)
{
ParameterInfo[] parameters = ctor.GetParameters();
Type[] parameterTypes = (from param in parameters select param.ParameterType).ToArray();
// create a method for calling the original constructor
string baseCtorName = "_" + baseType.Name + "__cinit__";
MethodBuilder methodBuilder = typeBuilder.DefineMethod(baseCtorName,
MethodAttributes.Public |
MethodAttributes.Final |
MethodAttributes.HideBySig,
typeof(void),
parameterTypes);
// emit the assembly for calling the original method using call instead of callvirt
ILGenerator il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
for (var i = 0; i < parameters.Length; ++i)
{
il.Emit(OpCodes.Ldarg, i + 1);
}
il.Emit(OpCodes.Call, ctor);
il.Emit(OpCodes.Ret);
// override the original method with a new one that dispatches to python
ConstructorBuilder cb = typeBuilder.DefineConstructor(MethodAttributes.Public |
MethodAttributes.ReuseSlot |
MethodAttributes.HideBySig,
ctor.CallingConvention,
parameterTypes);
il = cb.GetILGenerator();
il.DeclareLocal(typeof(object[]));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, baseCtorName);
il.Emit(OpCodes.Ldc_I4, parameters.Length);
il.Emit(OpCodes.Newarr, typeof(object));
il.Emit(OpCodes.Stloc_0);
for (var i = 0; i < parameters.Length; ++i)
{
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldarg, i + 1);
if (parameterTypes[i].IsValueType)
{
il.Emit(OpCodes.Box, parameterTypes[i]);
}
il.Emit(OpCodes.Stelem, typeof(object));
}
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Call, typeof(PythonDerivedType).GetMethod("InvokeCtor"));
il.Emit(OpCodes.Ret);
}
/// <summary>
/// Add a virtual method override that checks for an override on the python instance
/// and calls it, otherwise fall back to the base class method.
/// </summary>
/// <param name="method">virtual method to be overridden</param>
/// <param name="baseType">Python callable object</param>
/// <param name="typeBuilder">TypeBuilder for the new type the method is to be added to</param>
private static void AddVirtualMethod(MethodInfo method, Type baseType, TypeBuilder typeBuilder)
{
ParameterInfo[] parameters = method.GetParameters();
Type[] parameterTypes = (from param in parameters select param.ParameterType).ToArray();
// If the method isn't abstract create a method for calling the original method
string baseMethodName = null;
if (!method.IsAbstract)
{
baseMethodName = "_" + baseType.Name + "__" + method.Name;
MethodBuilder baseMethodBuilder = typeBuilder.DefineMethod(baseMethodName,
MethodAttributes.Public |
MethodAttributes.Final |
MethodAttributes.HideBySig,
method.ReturnType,
parameterTypes);
// emit the assembly for calling the original method using call instead of callvirt
ILGenerator baseIl = baseMethodBuilder.GetILGenerator();
baseIl.Emit(OpCodes.Ldarg_0);
for (var i = 0; i < parameters.Length; ++i)
{
baseIl.Emit(OpCodes.Ldarg, i + 1);
}
baseIl.Emit(OpCodes.Call, method);
baseIl.Emit(OpCodes.Ret);
}
// override the original method with a new one that dispatches to python
MethodBuilder methodBuilder = typeBuilder.DefineMethod(method.Name,
MethodAttributes.Public |
MethodAttributes.ReuseSlot |
MethodAttributes.Virtual |
MethodAttributes.HideBySig,
method.CallingConvention,
method.ReturnType,
parameterTypes);
ILGenerator il = methodBuilder.GetILGenerator();
il.DeclareLocal(typeof(object[]));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, method.Name);
// don't fall back to the base type's method if it's abstract
if (null != baseMethodName)
{
il.Emit(OpCodes.Ldstr, baseMethodName);
}
else
{
il.Emit(OpCodes.Ldnull);
}
il.Emit(OpCodes.Ldc_I4, parameters.Length);
il.Emit(OpCodes.Newarr, typeof(object));
il.Emit(OpCodes.Stloc_0);
for (var i = 0; i < parameters.Length; ++i)
{
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldarg, i + 1);
if (parameterTypes[i].IsValueType)
{
il.Emit(OpCodes.Box, parameterTypes[i]);
}
il.Emit(OpCodes.Stelem, typeof(object));
}
il.Emit(OpCodes.Ldloc_0);
if (method.ReturnType == typeof(void))
{
il.Emit(OpCodes.Call, typeof(PythonDerivedType).GetMethod("InvokeMethodVoid"));
}
else
{
il.Emit(OpCodes.Call,
typeof(PythonDerivedType).GetMethod("InvokeMethod").MakeGenericMethod(method.ReturnType));
}
il.Emit(OpCodes.Ret);
}
/// <summary>
/// Python method may have the following function attributes set to control how they're exposed:
/// - _clr_return_type_ - method return type (required)
/// - _clr_arg_types_ - list of method argument types (required)
/// - _clr_method_name_ - method name, if different from the python method name (optional)
/// </summary>
/// <param name="methodName">Method name to add to the type</param>
/// <param name="func">Python callable object</param>
/// <param name="typeBuilder">TypeBuilder for the new type the method/property is to be added to</param>
private static void AddPythonMethod(string methodName, PyObject func, TypeBuilder typeBuilder)
{
if (func.HasAttr("_clr_method_name_"))
{
using (PyObject pyMethodName = func.GetAttr("_clr_method_name_"))
{
methodName = pyMethodName.ToString();
}
}
using (PyObject pyReturnType = func.GetAttr("_clr_return_type_"))
using (PyObject pyArgTypes = func.GetAttr("_clr_arg_types_"))
{
var returnType = pyReturnType.AsManagedObject(typeof(Type)) as Type;
if (returnType == null)
{
returnType = typeof(void);
}
if (!pyArgTypes.IsIterable())
{
throw new ArgumentException("_clr_arg_types_ must be a list or tuple of CLR types");
}
var argTypes = new List<Type>();
foreach (PyObject pyArgType in pyArgTypes)
{
var argType = pyArgType.AsManagedObject(typeof(Type)) as Type;
if (argType == null)
{
throw new ArgumentException("_clr_arg_types_ must be a list or tuple of CLR types");
}
argTypes.Add(argType);
}
// add the method to call back into python
MethodAttributes methodAttribs = MethodAttributes.Public |
MethodAttributes.Virtual |
MethodAttributes.ReuseSlot |
MethodAttributes.HideBySig;
MethodBuilder methodBuilder = typeBuilder.DefineMethod(methodName,
methodAttribs,
returnType,
argTypes.ToArray());
ILGenerator il = methodBuilder.GetILGenerator();
il.DeclareLocal(typeof(object[]));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, methodName);
il.Emit(OpCodes.Ldnull); // don't fall back to the base type's method
il.Emit(OpCodes.Ldc_I4, argTypes.Count);
il.Emit(OpCodes.Newarr, typeof(object));
il.Emit(OpCodes.Stloc_0);
for (var i = 0; i < argTypes.Count; ++i)
{
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldarg, i + 1);
if (argTypes[i].IsValueType)
{
il.Emit(OpCodes.Box, argTypes[i]);
}
il.Emit(OpCodes.Stelem, typeof(object));
}
il.Emit(OpCodes.Ldloc_0);
if (returnType == typeof(void))
{
il.Emit(OpCodes.Call, typeof(PythonDerivedType).GetMethod("InvokeMethodVoid"));
}
else
{
il.Emit(OpCodes.Call,
typeof(PythonDerivedType).GetMethod("InvokeMethod").MakeGenericMethod(returnType));
}
il.Emit(OpCodes.Ret);
}
}
/// <summary>
/// Python properties may have the following function attributes set to control how they're exposed:
/// - _clr_property_type_ - property type (required)
/// </summary>
/// <param name="propertyName">Property name to add to the type</param>
/// <param name="func">Python property object</param>
/// <param name="typeBuilder">TypeBuilder for the new type the method/property is to be added to</param>
private static void AddPythonProperty(string propertyName, PyObject func, TypeBuilder typeBuilder)
{
// add the method to call back into python
MethodAttributes methodAttribs = MethodAttributes.Public |
MethodAttributes.Virtual |
MethodAttributes.ReuseSlot |
MethodAttributes.HideBySig |
MethodAttributes.SpecialName;
using (PyObject pyPropertyType = func.GetAttr("_clr_property_type_"))
{
var propertyType = pyPropertyType.AsManagedObject(typeof(Type)) as Type;
if (propertyType == null)
{
throw new ArgumentException("_clr_property_type must be a CLR type");
}
PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyName,
PropertyAttributes.None,
propertyType,
null);
if (func.HasAttr("fget"))
{
using (PyObject pyfget = func.GetAttr("fget"))
{
if (pyfget.IsTrue())
{
MethodBuilder methodBuilder = typeBuilder.DefineMethod("get_" + propertyName,
methodAttribs,
propertyType,
null);
ILGenerator il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, propertyName);
il.Emit(OpCodes.Call,
typeof(PythonDerivedType).GetMethod("InvokeGetProperty").MakeGenericMethod(propertyType));
il.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(methodBuilder);
}
}
}
if (func.HasAttr("fset"))
{
using (PyObject pyset = func.GetAttr("fset"))
{
if (pyset.IsTrue())
{
MethodBuilder methodBuilder = typeBuilder.DefineMethod("set_" + propertyName,
methodAttribs,
null,
new[] { propertyType });
ILGenerator il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, propertyName);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Call,
typeof(PythonDerivedType).GetMethod("InvokeSetProperty").MakeGenericMethod(propertyType));
il.Emit(OpCodes.Ret);
propertyBuilder.SetSetMethod(methodBuilder);
}
}
}
}
}
private static ModuleBuilder GetModuleBuilder(string assemblyName, string moduleName)
{
// find or create a dynamic assembly and module
AppDomain domain = AppDomain.CurrentDomain;
ModuleBuilder moduleBuilder;
if (moduleBuilders.ContainsKey(Tuple.Create(assemblyName, moduleName)))
{
moduleBuilder = moduleBuilders[Tuple.Create(assemblyName, moduleName)];
}
else
{
AssemblyBuilder assemblyBuilder;
if (assemblyBuilders.ContainsKey(assemblyName))
{
assemblyBuilder = assemblyBuilders[assemblyName];
}
else
{
assemblyBuilder = domain.DefineDynamicAssembly(new AssemblyName(assemblyName),
AssemblyBuilderAccess.Run);
assemblyBuilders[assemblyName] = assemblyBuilder;
}
moduleBuilder = assemblyBuilder.DefineDynamicModule(moduleName);
moduleBuilders[Tuple.Create(assemblyName, moduleName)] = moduleBuilder;
}
return moduleBuilder;
}
}
/// <summary>
/// PythonDerivedType contains static methods used by the dynamically created
/// derived type that allow it to call back into python from overridden virtual
/// methods, and also handle the construction and destruction of the python
/// object.
/// </summary>
/// <remarks>
/// This has to be public as it's called from methods on dynamically built classes
/// potentially in other assemblies.
/// </remarks>
public class PythonDerivedType
{
/// <summary>
/// This is the implementation of the overridden methods in the derived
/// type. It looks for a python method with the same name as the method
/// on the managed base class and if it exists and isn't the managed
/// method binding (i.e. it has been overridden in the derived python
/// class) it calls it, otherwise it calls the base method.
/// </summary>
public static T InvokeMethod<T>(IPythonDerivedType obj, string methodName, string origMethodName, object[] args)
{
FieldInfo fi = obj.GetType().GetField("__pyobj__");
var self = (CLRObject)fi.GetValue(obj);
if (null != self)
{
var disposeList = new List<PyObject>();
IntPtr gs = Runtime.PyGILState_Ensure();
try
{
Runtime.XIncref(self.pyHandle);
var pyself = new PyObject(self.pyHandle);
disposeList.Add(pyself);
Runtime.XIncref(Runtime.PyNone);
var pynone = new PyObject(Runtime.PyNone);
disposeList.Add(pynone);
PyObject method = pyself.GetAttr(methodName, pynone);
disposeList.Add(method);
if (method.Handle != Runtime.PyNone)
{
// if the method hasn't been overridden then it will be a managed object
var managedMethod = ManagedType.GetManagedObject(method.Handle);
if (null == managedMethod)
{
var pyargs = new PyObject[args.Length];
for (var i = 0; i < args.Length; ++i)
{
pyargs[i] = new PyObject(Converter.ToPythonImplicit(args[i]));
disposeList.Add(pyargs[i]);
}
PyObject py_result = method.Invoke(pyargs);
disposeList.Add(py_result);
return (T)py_result.AsManagedObject(typeof(T));
}
}
}
finally
{
foreach (PyObject x in disposeList)
{
x?.Dispose();
}
Runtime.PyGILState_Release(gs);
}
}
if (origMethodName == null)
{
throw new NotImplementedException("Python object does not have a '" + methodName + "' method");
}
return (T)obj.GetType().InvokeMember(origMethodName,
BindingFlags.InvokeMethod,
null,
obj,
args);
}
public static void InvokeMethodVoid(IPythonDerivedType obj, string methodName, string origMethodName,
object[] args)
{
FieldInfo fi = obj.GetType().GetField("__pyobj__");
var self = (CLRObject)fi.GetValue(obj);
if (null != self)
{
var disposeList = new List<PyObject>();
IntPtr gs = Runtime.PyGILState_Ensure();
try
{
Runtime.XIncref(self.pyHandle);
var pyself = new PyObject(self.pyHandle);
disposeList.Add(pyself);
Runtime.XIncref(Runtime.PyNone);
var pynone = new PyObject(Runtime.PyNone);
disposeList.Add(pynone);
PyObject method = pyself.GetAttr(methodName, pynone);
disposeList.Add(method);
if (method.Handle != Runtime.PyNone)
{
// if the method hasn't been overridden then it will be a managed object
var managedMethod = ManagedType.GetManagedObject(method.Handle);
if (null == managedMethod)
{
var pyargs = new PyObject[args.Length];
for (var i = 0; i < args.Length; ++i)
{
pyargs[i] = new PyObject(Converter.ToPythonImplicit(args[i]));
disposeList.Add(pyargs[i]);
}
PyObject py_result = method.Invoke(pyargs);
disposeList.Add(py_result);
return;
}
}
}
finally
{
foreach (PyObject x in disposeList)
{
x?.Dispose();
}
Runtime.PyGILState_Release(gs);
}
}
if (origMethodName == null)
{
throw new NotImplementedException($"Python object does not have a '{methodName}' method");
}
obj.GetType().InvokeMember(origMethodName,
BindingFlags.InvokeMethod,
null,
obj,
args);
}
public static T InvokeGetProperty<T>(IPythonDerivedType obj, string propertyName)
{
FieldInfo fi = obj.GetType().GetField("__pyobj__");
var self = (CLRObject)fi.GetValue(obj);
if (null == self)
{
throw new NullReferenceException("Instance must be specified when getting a property");
}
IntPtr gs = Runtime.PyGILState_Ensure();
try
{
Runtime.XIncref(self.pyHandle);
using (var pyself = new PyObject(self.pyHandle))
using (PyObject pyvalue = pyself.GetAttr(propertyName))
{
return (T)pyvalue.AsManagedObject(typeof(T));
}
}
finally
{
Runtime.PyGILState_Release(gs);
}
}
public static void InvokeSetProperty<T>(IPythonDerivedType obj, string propertyName, T value)
{
FieldInfo fi = obj.GetType().GetField("__pyobj__");
var self = (CLRObject)fi.GetValue(obj);
if (null == self)
{
throw new NullReferenceException("Instance must be specified when setting a property");
}
IntPtr gs = Runtime.PyGILState_Ensure();
try
{
Runtime.XIncref(self.pyHandle);
using (var pyself = new PyObject(self.pyHandle))
using (var pyvalue = new PyObject(Converter.ToPythonImplicit(value)))
{
pyself.SetAttr(propertyName, pyvalue);
}
}
finally
{
Runtime.PyGILState_Release(gs);
}
}
public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, object[] args)
{
// call the base constructor
obj.GetType().InvokeMember(origCtorName,
BindingFlags.InvokeMethod,
null,
obj,
args);
CLRObject self = null;
IntPtr gs = Runtime.PyGILState_Ensure();
try
{
// create the python object
IntPtr type = TypeManager.GetTypeHandle(obj.GetType());
self = new CLRObject(obj, type);
// set __pyobj__ to self and deref the python object which will allow this
// object to be collected.
FieldInfo fi = obj.GetType().GetField("__pyobj__");
fi.SetValue(obj, self);
}
finally
{
// Decrement the python object's reference count.
// This doesn't actually destroy the object, it just sets the reference to this object
// to be a weak reference and it will be destroyed when the C# object is destroyed.
if (null != self)
{
Runtime.XDecref(self.pyHandle);
}
Runtime.PyGILState_Release(gs);
}
}
public static void Finalize(IPythonDerivedType obj)
{
FieldInfo fi = obj.GetType().GetField("__pyobj__");
var self = (CLRObject)fi.GetValue(obj);
// If python's been terminated then just free the gchandle.
lock (Runtime.IsFinalizingLock)
{
if (0 == Runtime.Py_IsInitialized() || Runtime.IsFinalizing)
{
if (self.gcHandle.IsAllocated) self.gcHandle.Free();
return;
}
}
// delete the python object in an async task as we may not be able to acquire
// the GIL immediately and we don't want to block the GC thread.
// FIXME: t isn't used
Task t = Task.Factory.StartNew(() =>
{
lock (Runtime.IsFinalizingLock)
{
// If python's been terminated then just free the gchandle.
if (0 == Runtime.Py_IsInitialized() || Runtime.IsFinalizing)
{
if (self.gcHandle.IsAllocated) self.gcHandle.Free();
return;
}
IntPtr gs = Runtime.PyGILState_Ensure();
try
{
// the C# object is being destroyed which must mean there are no more
// references to the Python object as well so now we can dealloc the
// python object.
IntPtr dict = Marshal.ReadIntPtr(self.pyHandle, ObjectOffset.TypeDictOffset(self.tpHandle));
if (dict != IntPtr.Zero)
{
Runtime.XDecref(dict);
}
Runtime.PyObject_GC_Del(self.pyHandle);
self.gcHandle.Free();
}
finally
{
Runtime.PyGILState_Release(gs);
}
}
});
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.IO;
namespace Vestris.ResourceLib
{
/// <summary>
/// VS_VERSIONINFO
/// This structure depicts the organization of data in a file-version resource. It is the root structure
/// that contains all other file-version information structures.
/// http://msdn.microsoft.com/en-us/library/aa914916.aspx
/// </summary>
public class VersionResource : Resource
{
ResourceTableHeader _header = new ResourceTableHeader("VS_VERSION_INFO");
FixedFileInfo _fixedfileinfo = new FixedFileInfo();
private OrderedDictionary _resources = new OrderedDictionary();
/// <summary>
/// The resource header.
/// </summary>
public ResourceTableHeader Header
{
get
{
return _header;
}
}
/// <summary>
/// A dictionary of resource tables.
/// </summary>
public OrderedDictionary Resources
{
get
{
return _resources;
}
}
/// <summary>
/// An existing version resource.
/// </summary>
/// <param name="hModule">Module handle.</param>
/// <param name="hResource">Resource ID.</param>
/// <param name="type">Resource type.</param>
/// <param name="name">Resource name.</param>
/// <param name="language">Language ID.</param>
/// <param name="size">Resource size.</param>
public VersionResource(IntPtr hModule, IntPtr hResource, ResourceId type, ResourceId name, UInt16 language, int size)
: base(hModule, hResource, type, name, language, size)
{
}
/// <summary>
/// A new language-netural version resource.
/// </summary>
public VersionResource()
: base(IntPtr.Zero,
IntPtr.Zero,
new ResourceId(Kernel32.ResourceTypes.RT_VERSION),
new ResourceId(1),
ResourceUtil.USENGLISHLANGID,
0)
{
_header.Header = new Kernel32.RESOURCE_HEADER(_fixedfileinfo.Size);
}
/// <summary>
/// Read a version resource from a previously loaded module.
/// </summary>
/// <param name="hModule">Module handle.</param>
/// <param name="lpRes">Pointer to the beginning of the resource.</param>
/// <returns>Pointer to the end of the resource.</returns>
internal override IntPtr Read(IntPtr hModule, IntPtr lpRes)
{
_resources.Clear();
IntPtr pFixedFileInfo = _header.Read(lpRes);
if (_header.Header.wValueLength != 0)
{
_fixedfileinfo = new FixedFileInfo();
_fixedfileinfo.Read(pFixedFileInfo);
}
IntPtr pChild = ResourceUtil.Align(pFixedFileInfo.ToInt64() + _header.Header.wValueLength);
while (pChild.ToInt64() < (lpRes.ToInt64() + _header.Header.wLength))
{
ResourceTableHeader rc = new ResourceTableHeader(pChild);
switch (rc.Key)
{
case "StringFileInfo":
StringFileInfo sr = new StringFileInfo(pChild);
rc = sr;
break;
default:
rc = new VarFileInfo(pChild);
break;
}
_resources.Add(rc.Key, rc);
pChild = ResourceUtil.Align(pChild.ToInt64() + rc.Header.wLength);
}
return new IntPtr(lpRes.ToInt64() + _header.Header.wLength);
}
/// <summary>
/// String representation of the file version.
/// </summary>
public string FileVersion
{
get
{
return _fixedfileinfo.FileVersion;
}
set
{
_fixedfileinfo.FileVersion = value;
}
}
/// <summary>
/// Gets or sets a bitmask that specifies the Boolean attributes of the file.
/// </summary>
public uint FileFlags
{
get
{
return this._fixedfileinfo.FileFlags;
}
set
{
this._fixedfileinfo.FileFlags = value;
}
}
/// <summary>
/// String representation of the protect version.
/// </summary>
public string ProductVersion
{
get
{
return _fixedfileinfo.ProductVersion;
}
set
{
_fixedfileinfo.ProductVersion = value;
}
}
/// <summary>
/// Write this version resource to a binary stream.
/// </summary>
/// <param name="w">Binary stream.</param>
internal override void Write(BinaryWriter w)
{
long headerPos = w.BaseStream.Position;
_header.Write(w);
if (_fixedfileinfo != null)
{
_fixedfileinfo.Write(w);
}
foreach (DictionaryEntry dictionaryEntry in _resources)
{
((ResourceTableHeader)dictionaryEntry.Value).Write(w);
}
ResourceUtil.WriteAt(w, w.BaseStream.Position - headerPos, headerPos);
}
/// <summary>
/// Returns an entry within this resource table.
/// </summary>
/// <param name="key">Entry key.</param>
/// <returns>A resource table.</returns>
public ResourceTableHeader this[string key]
{
get
{
return (ResourceTableHeader)Resources[key];
}
set
{
Resources[key] = value;
}
}
/// <summary>
/// Returns an entry within this resource table.
/// </summary>
/// <param name="index">Entry index.</param>
/// <returns>A resource table.</returns>
public ResourceTableHeader this[int index]
{
get
{
return (ResourceTableHeader)Resources[index];
}
set
{
Resources[index] = value;
}
}
/// <summary>
/// Return string representation of the version resource.
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
if (_fixedfileinfo != null)
{
sb.Append(_fixedfileinfo.ToString());
}
sb.AppendLine("BEGIN");
foreach (DictionaryEntry dictionaryEntry in _resources)
{
sb.Append(((ResourceTableHeader)dictionaryEntry.Value).ToString(1));
}
sb.AppendLine("END");
return sb.ToString();
}
}
}
| |
/*
* Copyright 2015-2015 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.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using Amazon.MobileAnalytics.Model;
using ThirdParty.Json.LitJson;
using Amazon.MobileAnalytics.MobileAnalyticsManager;
using Amazon.Util;
using Amazon.Runtime.Internal.Util;
using Amazon.Util.Internal;
using System.Globalization;
using SQLitePCL;
using PCLStorage;
namespace Amazon.MobileAnalytics.MobileAnalyticsManager.Internal
{
/// <summary>
/// Implementation of <see cref="Amazon.MobileAnalytics.MobileAnalyticsManager.Internal.IEventStore"/>.
/// The object stores Mobile Analytic events in SQLite database.
/// </summary>
public partial class SQLiteEventStore : IEventStore
{
static SQLiteEventStore()
{
_dbFileFullPath = System.IO.Path.Combine(PCLStorage.FileSystem.Current.LocalStorage.Path, dbFileName);
SetupSQLiteEventStore();
}
/// <summary>
/// Sets up SQLite database.
/// </summary>
private static void SetupSQLiteEventStore()
{
string vacuumCommand = "PRAGMA auto_vacuum = 1";
string sqlCommand = string.Format(CultureInfo.InvariantCulture, "CREATE TABLE IF NOT EXISTS {0} ({1} TEXT NOT NULL,{2} TEXT NOT NULL UNIQUE,{3} TEXT NOT NULL, {4} INTEGER NOT NULL DEFAULT 0 )",
TABLE_NAME, EVENT_COLUMN_NAME, EVENT_ID_COLUMN_NAME, MA_APP_ID_COLUMN_NAME, EVENT_DELIVERY_ATTEMPT_COUNT_COLUMN_NAME);
lock (_lock)
{
#if __IOS__
SQLitePCL.CurrentPlatform.Init();
#endif
using (var connection = new SQLiteConnection(_dbFileFullPath))
{
using (var statement = connection.Prepare(vacuumCommand))
{
statement.Step();
}
using (var createTableStmt = connection.Prepare(sqlCommand))
{
createTableStmt.Step();
}
}
}
}
/// <summary>
/// Add an event to the store.
/// </summary>
/// <param name="eventString">Amazon Mobile Analytics event in string.</param>
/// <param name="appID">Amazon Mobile Analytics App ID.</param>
[System.Security.SecuritySafeCritical]
public void PutEvent(string eventString, string appID)
{
long currentDatabaseSize = this.DatabaseSize;
if (currentDatabaseSize >= _maConfig.MaxDBSize)
{
InvalidOperationException e = new InvalidOperationException();
_logger.Error(e, "The database size has exceeded the threshold limit. Unable to insert any new events");
}
else if ((double)currentDatabaseSize / (double)_maConfig.MaxDBSize >= _maConfig.DBWarningThreshold)
{
_logger.InfoFormat("The database size is almost full");
}
else
{
string sqlCommand = string.Format(CultureInfo.InvariantCulture, "INSERT INTO {0} ({1},{2},{3}) values(?,?,?)", TABLE_NAME, EVENT_COLUMN_NAME, EVENT_ID_COLUMN_NAME, MA_APP_ID_COLUMN_NAME);
lock (_lock)
{
using (var connection = new SQLiteConnection(_dbFileFullPath))
{
using (var statement = connection.Prepare(sqlCommand))
{
statement.Bind(1, eventString);
statement.Bind(2, Guid.NewGuid().ToString());
statement.Bind(3, appID);
statement.Step();
}
}
}
}
}
/// <summary>
/// Deletes a list of events.
/// </summary>
/// <param name="rowIds">List of row identifiers.</param>
[System.Security.SecuritySafeCritical]
public void DeleteEvent(List<string> rowIds)
{
string ids = string.Format(CultureInfo.InvariantCulture, "'{0}'", string.Join("', '", rowIds.ToArray()));
string sqlCommand = string.Format(CultureInfo.InvariantCulture, "DELETE FROM {0} WHERE {1} IN ({2})", TABLE_NAME, EVENT_ID_COLUMN_NAME, ids);
lock (_lock)
{
using (var connection = new SQLiteConnection(_dbFileFullPath))
{
using (var statement = connection.Prepare(sqlCommand))
{
statement.Step();
}
}
}
}
/// <summary>
/// Get events from the Event Store
/// </summary>
/// <param name="appID">Amazon Mobile Analytics App Id.</param>
/// <param name="maxAllowed">Max number of events is allowed to return.</param>
/// <returns>The events as a List of <see cref="ThirdParty.Json.LitJson.JsonData"/>.</returns>
[System.Security.SecuritySafeCritical]
public List<JsonData> GetEvents(string appID, int maxAllowed)
{
List<JsonData> eventList = new List<JsonData>();
string sqlCommand = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM {0} WHERE {1} = ? ORDER BY {2}, ROWID LIMIT {3} ", TABLE_NAME, MA_APP_ID_COLUMN_NAME, EVENT_DELIVERY_ATTEMPT_COUNT_COLUMN_NAME, maxAllowed);
lock (_lock)
{
using (var connection = new SQLiteConnection(_dbFileFullPath))
{
using (var statement = connection.Prepare(sqlCommand))
{
statement.Bind(1, appID);
while (statement.Step() == SQLiteResult.ROW)
{
JsonData data = new JsonData();
data["id"] = statement.GetText(EVENT_ID_COLUMN_NAME);
data["event"] = statement.GetText(EVENT_COLUMN_NAME.ToLower());
data["appID"] = statement.GetText(MA_APP_ID_COLUMN_NAME);
eventList.Add(data);
}
}
}
}
return eventList;
}
/// <summary>
/// Gets Numbers the of events.
/// </summary>
/// <param name="appID">Amazon Mobile Analytics App Identifier.</param>
/// <returns>The number of events.</returns>
[System.Security.SecuritySafeCritical]
public long NumberOfEvents(string appID)
{
long count = 0;
string sqlCommand = string.Format(CultureInfo.InvariantCulture, "SELECT COUNT(*) C FROM {0} where {1} = ?", TABLE_NAME, MA_APP_ID_COLUMN_NAME);
using (var connection = new SQLiteConnection(_dbFileFullPath))
{
using (var statement = connection.Prepare(sqlCommand))
{
statement.Bind(1, appID);
while (statement.Step() == SQLiteResult.ROW)
{
count = statement.GetInteger("C");
}
}
}
return count;
}
/// <summary>
/// Gets the size of the database.
/// </summary>
/// <returns>The database size.</returns>
public long DatabaseSize
{
get
{
string pageCountCommand = "PRAGMA page_count;";
string pageSizeCommand = "PRAGMA page_size;";
long pageCount = 0, pageSize = 0;
lock (_lock)
{
using (var connection = new SQLiteConnection(_dbFileFullPath))
{
using (var statement = connection.Prepare(pageCountCommand))
{
while (statement.Step() == SQLiteResult.ROW)
{
pageCount = statement.GetInteger(0);
}
}
using (var statement = connection.Prepare(pageSizeCommand))
{
while (statement.Step() == SQLiteResult.ROW)
{
pageSize = statement.GetInteger(0);
}
}
}
}
return pageCount * pageSize;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using EmergeTk.Model;
using EmergeTk.Model.Security;
using System.Text;
using System.Xml;
namespace EmergeTk.WebServices
{
public class XmlMessageWriter : IMessageWriter
{
protected Stack<XmlMessageWriterEntity> stack = new Stack<XmlMessageWriterEntity>();
protected Stream stm;
protected XmlWriter writer;
protected XmlMessageWriter()
{
}
static public XmlMessageWriter Create(Stream stm)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = UTF8Encoding.UTF8;
settings.CloseOutput = false;
settings.OmitXmlDeclaration = false;
settings.Indent = false;
settings.NewLineOnAttributes = false;
settings.CheckCharacters = true;
settings.NewLineHandling = NewLineHandling.None;
settings.ConformanceLevel = ConformanceLevel.Auto;
return XmlMessageWriter.Create(stm, settings);
}
static public XmlMessageWriter Create(Stream stm, XmlWriterSettings settings)
{
if (stm == null)
throw new ArgumentException("XmlMessageWriter.Create called with null stream");
XmlMessageWriter This = new XmlMessageWriter();
This.writer = XmlTextWriter.Create(stm, settings);
This.stm = stm;
return This;
}
protected String ListNameOnStack()
{
if (stack.Count > 0)
{
XmlMessageWriterEntity itemOnStack = stack.Peek();
if (itemOnStack.EntityType == XmlMessageWriterEntityType.List)
{
return itemOnStack.Name;
}
}
return String.Empty;
}
protected bool ListOnStack()
{
return stack.Count > 0 && stack.Peek().EntityType == XmlMessageWriterEntityType.List;
}
#region IMessageWriter Members
public void OpenRoot(string name)
{
writer.WriteStartElement(name);
}
public void CloseRoot()
{
writer.WriteFullEndElement();
writer.Close();
}
public void OpenObject()
{
#if false
if (stack.Count > 0)
writer.WriteStartElement(stack.Peek().Name);
#endif
}
public void CloseObject()
{
#if false
if (stack.Count > 0)
writer.WriteEndElement();
#endif
}
public void OpenList(string name)
{
if (stack.Count > 0)
writer.WriteAttributeString("type", "array");
stack.Push(XmlMessageWriterEntity.Create(name, XmlMessageWriterEntityType.List));
}
public void CloseList()
{
stack.Pop();
}
public void WriteScalar(string scalar)
{
WriteScalarHelper(scalar);
}
public void WriteScalar(int scalar)
{
WriteScalarHelper(JSON.Default.Encode(scalar));
}
public void WriteScalar(bool scalar)
{
WriteScalarHelper(JSON.Default.Encode(scalar));
}
public void WriteScalar(double scalar)
{
WriteScalarHelper(JSON.Default.Encode(scalar));
}
public void WriteScalar(DateTime scalar)
{
WriteScalarHelper(scalar.ToString());
}
public void WriteScalar(float scalar)
{
WriteScalarHelper(JSON.Default.Encode(scalar));
}
public void WriteScalar(Decimal scalar)
{
WriteScalarHelper(JSON.Default.Encode(scalar));
}
public void WriteScalar(Object scalar)
{
String val;
if (scalar == null || scalar is System.DBNull)
{
WriteScalarHelper((String)null);
return;
}
else if (scalar is string)
{
WriteScalarHelper(scalar.ToString());
return;
}
if (scalar is bool)
val = JSON.Default.Encode((bool)scalar);
else if (scalar is double)
val = JSON.Default.Encode((double)scalar);
else if (scalar is float)
val = JSON.Default.Encode((float)scalar);
else if (scalar is decimal)
val = JSON.Default.Encode((decimal)scalar);
else if (scalar is int)
val = JSON.Default.Encode((int)scalar);
else if (scalar is DateTime)
val = scalar.ToString();
else if (scalar.GetType().IsEnum)
val = scalar.ToString();
else
throw new InvalidOperationException(String.Format("XmlMsgWriter.WriteScalar can't handle type of {0}", scalar.GetType().ToString()));
WriteScalarHelper(val);
}
private void WriteScalarHelper(String scalar)
{
scalar = String.IsNullOrEmpty(scalar) ? "null" : scalar;
String listOnStack = ListNameOnStack();
if (!String.IsNullOrEmpty(listOnStack))
{
// if it's a list, we need to write out the entire <name>value</name> business
writer.WriteElementString(listOnStack, scalar);
}
else
{
// just write out the value - the element is already written.
System.Diagnostics.Debug.Assert(stack.Peek().EntityType == XmlMessageWriterEntityType.Property);
writer.WriteValue(scalar);
}
}
public void WriteRaw (string data)
{
byte[] bytes = UTF8Encoding.UTF8.GetBytes(data);
stm.Write (bytes, 0, bytes.Length);
}
public void OpenProperty(string name)
{
stack.Push(XmlMessageWriterEntity.Create(name, XmlMessageWriterEntityType.Property));
writer.WriteStartElement(name);
}
public void CloseProperty()
{
stack.Pop();
writer.WriteEndElement();
}
public void WriteProperty(string name, string scalarValue)
{
writer.WriteElementString(name, scalarValue);
}
public void WriteProperty(string name, int scalarValue)
{
writer.WriteElementString(name, scalarValue.ToString());
}
public void Flush()
{
writer.Flush();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Test.ModuleCore;
using System.IO;
using System.Reflection;
using Xunit;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeBuilderTests : XLinqTestCase
{
public partial class NamespacehandlingSaveOptions : XLinqTestCase
{
private string _mode;
private Type _type;
public override void Init()
{
_mode = Params[0] as string;
_type = Params[1] as Type;
}
#region helpers
private void DumpMethodInfo(MethodInfo mi)
{
TestLog.WriteLineIgnore("Method with the params found: " + mi.Name);
foreach (var pi in mi.GetParameters())
{
TestLog.WriteLineIgnore(" name: " + pi.Name + " Type: " + pi.ParameterType);
}
}
private string SaveXElement(object elem, SaveOptions so)
{
string retVal = null;
switch (_mode)
{
case "Save":
using (StringWriter sw = new StringWriter())
{
if (_type.Name == "XElement")
{
(elem as XElement).Save(sw, so);
}
else if (_type.Name == "XDocument")
{
(elem as XDocument).Save(sw, so);
}
retVal = sw.ToString();
}
break;
case "ToString":
if (_type.Name == "XElement")
{
retVal = (elem as XElement).ToString(so);
}
else if (_type.Name == "XDocument")
{
retVal = (elem as XDocument).ToString(so);
}
break;
default:
TestLog.Compare(false, "TEST FAILED: wrong mode");
break;
}
return retVal;
}
private string AppendXmlDecl(string xml)
{
return _mode == "Save" ? GetXmlStringWithXmlDecl(xml) : xml;
}
private static string GetXmlStringWithXmlDecl(string xml)
{
return @"<?xml version='1.0' encoding='utf-16'?>" + xml;
}
private object Parse(string xml)
{
object o = null;
if (_type.Name == "XElement")
{
o = XElement.Parse(xml);
}
else if (_type.Name == "XDocument")
{
o = XDocument.Parse(xml);
}
return o;
}
#endregion
//[Variation(Desc = "1 level down", Priority = 0, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></p:A>" })]
//[Variation(Desc = "1 level down II.", Priority = 0, Params = new object[] { "<A><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></A>" })] // start at not root node
//[Variation(Desc = "2 levels down", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></p:A>" })]
//[Variation(Desc = "2 levels down II.", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><C xmlns:p='nsp'/></B></p:A>" })]
//[Variation(Desc = "2 levels down III.", Priority = 1, Params = new object[] { "<A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></A>" })]
//[Variation(Desc = "Siblings", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'/><C xmlns:p='nsp'/><p:C xmlns:p='nsp'/></A>" })]
//[Variation(Desc = "Children", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'><C xmlns:p='nsp'><p:C xmlns:p='nsp'/></C></p:B></A>" })]
//[Variation(Desc = "Xml namespace I.", Priority = 3, Params = new object[] { "<A xmlns:xml='http://www.w3.org/XML/1998/namespace'/>" })]
//[Variation(Desc = "Xml namespace II.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })]
//[Variation(Desc = "Xml namespace III.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:xml='http://www.w3.org/XML/1998/namespace' xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })]
//[Variation(Desc = "Default namespaces", Priority = 1, Params = new object[] { "<A xmlns='nsp'><p:B xmlns:p='nsp'><C xmlns='nsp' /></p:B></A>" })]
//[Variation(Desc = "Not used NS declarations", Priority = 2, Params = new object[] { "<A xmlns='nsp' xmlns:u='not-used'><p:B xmlns:p='nsp'><C xmlns:u='not-used' xmlns='nsp' /></p:B></A>" })]
//[Variation(Desc = "SameNS, different prefix", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><B xmlns:q='nsp'><p:C xmlns:p='nsp'/></B></p:A>" })]
public void testFromTheRootNodeSimple()
{
string xml = CurrentChild.Params[0] as string;
Object elemObj = Parse(xml);
// Write using XmlWriter in duplicate namespace decl. removal mode
string removedByWriter = SaveXElement(elemObj, SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting);
XElement elem = (elemObj is XDocument) ? (elemObj as XDocument).Root : elemObj as XElement;
// Remove the namespace decl. duplicates from the Xlinq tree
(from a in elem.DescendantsAndSelf().Attributes()
where a.IsNamespaceDeclaration && ((a.Name.LocalName == "xml" && (string)a == XNamespace.Xml.NamespaceName) ||
(from parentDecls in a.Parent.Ancestors().Attributes(a.Name)
where parentDecls.IsNamespaceDeclaration && (string)parentDecls == (string)a
select parentDecls).Any()
)
select a).ToList().Remove();
// Write XElement using XmlWriter without omiting
string removedByManual = SaveXElement(elemObj, SaveOptions.DisableFormatting);
ReaderDiff.Compare(removedByWriter, removedByManual);
}
//[Variation(Desc = "Default ns parent autogenerated", Priority = 1)]
public void testFromTheRootNodeTricky()
{
object e = new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute("xmlns", "nsp")));
if (_type == typeof(XDocument))
{
XDocument d = new XDocument();
d.Add(e);
e = d;
}
string act = SaveXElement(e, SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting);
string exp = AppendXmlDecl("<A xmlns='nsp'><B/></A>");
ReaderDiff.Compare(act, exp);
}
//[Variation(Desc = "Conflicts: NS redefinition", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D xmlns:p='nsp'/></p:C></p:B></p:A>",
// "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D/></p:C></p:B></p:A>" })]
//[Variation(Desc = "Conflicts: NS redefinition, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
// "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D/></C></B></A>" })]
//[Variation(Desc = "Conflicts: NS redefinition, default NS II.", Priority = 2, Params = new object[] { "<A xmlns=''><B xmlns='ns-other'><C xmlns=''><D xmlns=''/></C></B></A>",
// "<A><B xmlns='ns-other'><C xmlns=''><D/></C></B></A>" })]
//[Variation(Desc = "Conflicts: NS undeclaration, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
// "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D/></C></B></A>" })]
public static object[][] ConFlictsNSRedefenitionParams = new object[][] {
new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D xmlns:p='nsp'/></p:C></p:B></p:A>",
"<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D/></p:C></p:B></p:A>" },
new object[] { "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
"<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D/></C></B></A>" },
new object[] { "<A xmlns=''><B xmlns='ns-other'><C xmlns=''><D xmlns=''/></C></B></A>",
"<A><B xmlns='ns-other'><C xmlns=''><D/></C></B></A>" },
new object[] { "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>",
"<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D/></C></B></A>" }
};
[Theory, MemberData("ConFlictsNSRedefenitionParams")]
public void XDocumentConflictsNSRedefinitionSaveToStringWriterAndGetContent(string xml1, string xml2)
{
XDocument doc = XDocument.Parse(xml1);
SaveOptions so = SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting;
using (StringWriter sw = new StringWriter())
{
doc.Save(sw, so);
ReaderDiff.Compare(GetXmlStringWithXmlDecl(xml2), sw.ToString());
}
}
[Theory, MemberData("ConFlictsNSRedefenitionParams")]
public void XDocumentConflictsNSRedefinitionToString(string xml1, string xml2)
{
XDocument doc = XDocument.Parse(xml1);
SaveOptions so = SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting;
ReaderDiff.Compare(xml2, doc.ToString(so));
}
[Theory, MemberData("ConFlictsNSRedefenitionParams")]
public void XElementConflictsNSRedefinitionSaveToStringWriterAndGetContent(string xml1, string xml2)
{
XElement el = XElement.Parse(xml1);
SaveOptions so = SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting;
using (StringWriter sw = new StringWriter())
{
el.Save(sw, so);
ReaderDiff.Compare(GetXmlStringWithXmlDecl(xml2), sw.ToString());
}
}
[Theory, MemberData("ConFlictsNSRedefenitionParams")]
public void XElementConflictsNSRedefinitionToString(string xml1, string xml2)
{
XElement el = XElement.Parse(xml1);
SaveOptions so = SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting;
ReaderDiff.Compare(xml2, el.ToString(so));
}
//[Variation(Desc = "Not from root", Priority = 1)]
public void testFromChildNode1()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute("xmlns", "nsp"))));
ReaderDiff.Compare(SaveXElement(e.Element("{nsp}A"), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:A xmlns:p1='nsp'><B xmlns='nsp'/></p1:A>"));
}
//[Variation(Desc = "Not from root II.", Priority = 1)]
public void testFromChildNode2()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"))));
ReaderDiff.Compare(SaveXElement(e.Element("{nsp}A"), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:A xmlns:p1='nsp'><p1:B/></p1:A>"));
}
//[Variation(Desc = "Not from root III.", Priority = 2)]
public void testFromChildNode3()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"))));
ReaderDiff.Compare(SaveXElement(e.Descendants("{nsp}B").FirstOrDefault(), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:B xmlns:p1='nsp'/>"));
}
//[Variation(Desc = "Not from root IV.", Priority = 2)]
public void testFromChildNode4()
{
if (_type == typeof(XDocument)) TestLog.Skip("Test not applicable");
XElement e = new XElement("root",
new XAttribute(XNamespace.Xmlns + "p1", "nsp"),
new XElement("{nsp}A",
new XElement("{nsp}B")));
ReaderDiff.Compare(SaveXElement(e.Descendants("{nsp}B").FirstOrDefault(), SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting), AppendXmlDecl("<p1:B xmlns:p1='nsp'/>"));
}
}
}
}
}
| |
/*
* 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.
*/
#pragma warning disable 618 // Ignore obsolete, we still need to test them.
namespace Apache.Ignite.Core.Tests
{
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity.Rendezvous;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Eviction;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Client.Cache;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Communication.Tcp;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.DataStructures.Configuration;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Multicast;
using Apache.Ignite.Core.Discovery.Tcp.Static;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.PersistentStore;
using Apache.Ignite.Core.Tests.Plugin;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
using WalMode = Apache.Ignite.Core.PersistentStore.WalMode;
/// <summary>
/// Tests code-based configuration.
/// </summary>
public class IgniteConfigurationTest
{
/// <summary>
/// Fixture tear down.
/// </summary>
[TestFixtureSetUp]
public void FixtureTearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Tests the default configuration properties.
/// </summary>
[Test]
public void TestDefaultConfigurationProperties()
{
CheckDefaultProperties(new IgniteConfiguration());
CheckDefaultProperties(new PersistentStoreConfiguration());
CheckDefaultProperties(new DataStorageConfiguration());
CheckDefaultProperties(new DataRegionConfiguration());
CheckDefaultProperties(new ClientConnectorConfiguration());
CheckDefaultProperties(new SqlConnectorConfiguration());
}
/// <summary>
/// Tests the default value attributes.
/// </summary>
[Test]
public void TestDefaultValueAttributes()
{
CheckDefaultValueAttributes(new IgniteConfiguration());
CheckDefaultValueAttributes(new BinaryConfiguration());
CheckDefaultValueAttributes(new TcpDiscoverySpi());
CheckDefaultValueAttributes(new CacheConfiguration());
CheckDefaultValueAttributes(new TcpDiscoveryMulticastIpFinder());
CheckDefaultValueAttributes(new TcpCommunicationSpi());
CheckDefaultValueAttributes(new RendezvousAffinityFunction());
CheckDefaultValueAttributes(new NearCacheConfiguration());
CheckDefaultValueAttributes(new FifoEvictionPolicy());
CheckDefaultValueAttributes(new LruEvictionPolicy());
CheckDefaultValueAttributes(new AtomicConfiguration());
CheckDefaultValueAttributes(new TransactionConfiguration());
CheckDefaultValueAttributes(new MemoryEventStorageSpi());
CheckDefaultValueAttributes(new MemoryConfiguration());
CheckDefaultValueAttributes(new MemoryPolicyConfiguration());
CheckDefaultValueAttributes(new SqlConnectorConfiguration());
CheckDefaultValueAttributes(new ClientConnectorConfiguration());
CheckDefaultValueAttributes(new PersistentStoreConfiguration());
CheckDefaultValueAttributes(new IgniteClientConfiguration());
CheckDefaultValueAttributes(new QueryIndex());
CheckDefaultValueAttributes(new DataStorageConfiguration());
CheckDefaultValueAttributes(new DataRegionConfiguration());
CheckDefaultValueAttributes(new CacheClientConfiguration());
}
/// <summary>
/// Tests all configuration properties.
/// </summary>
[Test]
public void TestAllConfigurationProperties()
{
var cfg = new IgniteConfiguration(GetCustomConfig());
using (var ignite = Ignition.Start(cfg))
{
var resCfg = ignite.GetConfiguration();
var disco = (TcpDiscoverySpi) cfg.DiscoverySpi;
var resDisco = (TcpDiscoverySpi) resCfg.DiscoverySpi;
Assert.AreEqual(disco.NetworkTimeout, resDisco.NetworkTimeout);
Assert.AreEqual(disco.AckTimeout, resDisco.AckTimeout);
Assert.AreEqual(disco.MaxAckTimeout, resDisco.MaxAckTimeout);
Assert.AreEqual(disco.SocketTimeout, resDisco.SocketTimeout);
Assert.AreEqual(disco.JoinTimeout, resDisco.JoinTimeout);
Assert.AreEqual(disco.LocalAddress, resDisco.LocalAddress);
Assert.AreEqual(disco.LocalPort, resDisco.LocalPort);
Assert.AreEqual(disco.LocalPortRange, resDisco.LocalPortRange);
Assert.AreEqual(disco.ReconnectCount, resDisco.ReconnectCount);
Assert.AreEqual(disco.StatisticsPrintFrequency, resDisco.StatisticsPrintFrequency);
Assert.AreEqual(disco.ThreadPriority, resDisco.ThreadPriority);
Assert.AreEqual(disco.TopologyHistorySize, resDisco.TopologyHistorySize);
var ip = (TcpDiscoveryStaticIpFinder) disco.IpFinder;
var resIp = (TcpDiscoveryStaticIpFinder) resDisco.IpFinder;
// There can be extra IPv6 endpoints
Assert.AreEqual(ip.Endpoints, resIp.Endpoints.Take(2).Select(x => x.Trim('/')).ToArray());
Assert.AreEqual(cfg.IgniteInstanceName, resCfg.IgniteInstanceName);
Assert.AreEqual(cfg.IgniteHome, resCfg.IgniteHome);
Assert.AreEqual(cfg.IncludedEventTypes, resCfg.IncludedEventTypes);
Assert.AreEqual(cfg.MetricsExpireTime, resCfg.MetricsExpireTime);
Assert.AreEqual(cfg.MetricsHistorySize, resCfg.MetricsHistorySize);
Assert.AreEqual(cfg.MetricsLogFrequency, resCfg.MetricsLogFrequency);
Assert.AreEqual(cfg.MetricsUpdateFrequency, resCfg.MetricsUpdateFrequency);
Assert.AreEqual(cfg.NetworkSendRetryCount, resCfg.NetworkSendRetryCount);
Assert.AreEqual(cfg.NetworkTimeout, resCfg.NetworkTimeout);
Assert.AreEqual(cfg.NetworkSendRetryDelay, resCfg.NetworkSendRetryDelay);
Assert.AreEqual(cfg.WorkDirectory.Trim(Path.DirectorySeparatorChar),
resCfg.WorkDirectory.Trim(Path.DirectorySeparatorChar));
Assert.AreEqual(cfg.JvmClasspath, resCfg.JvmClasspath);
Assert.AreEqual(cfg.JvmOptions, resCfg.JvmOptions);
Assert.AreEqual(cfg.JvmDllPath, resCfg.JvmDllPath);
Assert.AreEqual(cfg.Localhost, resCfg.Localhost);
Assert.AreEqual(cfg.IsDaemon, resCfg.IsDaemon);
Assert.AreEqual(IgniteConfiguration.DefaultIsLateAffinityAssignment, resCfg.IsLateAffinityAssignment);
Assert.AreEqual(cfg.UserAttributes, resCfg.UserAttributes);
var atm = cfg.AtomicConfiguration;
var resAtm = resCfg.AtomicConfiguration;
Assert.AreEqual(atm.AtomicSequenceReserveSize, resAtm.AtomicSequenceReserveSize);
Assert.AreEqual(atm.Backups, resAtm.Backups);
Assert.AreEqual(atm.CacheMode, resAtm.CacheMode);
var tx = cfg.TransactionConfiguration;
var resTx = resCfg.TransactionConfiguration;
Assert.AreEqual(tx.DefaultTimeout, resTx.DefaultTimeout);
Assert.AreEqual(tx.DefaultTransactionConcurrency, resTx.DefaultTransactionConcurrency);
Assert.AreEqual(tx.DefaultTransactionIsolation, resTx.DefaultTransactionIsolation);
Assert.AreEqual(tx.PessimisticTransactionLogLinger, resTx.PessimisticTransactionLogLinger);
Assert.AreEqual(tx.PessimisticTransactionLogSize, resTx.PessimisticTransactionLogSize);
var com = (TcpCommunicationSpi) cfg.CommunicationSpi;
var resCom = (TcpCommunicationSpi) resCfg.CommunicationSpi;
Assert.AreEqual(com.AckSendThreshold, resCom.AckSendThreshold);
Assert.AreEqual(com.ConnectTimeout, resCom.ConnectTimeout);
Assert.AreEqual(com.DirectBuffer, resCom.DirectBuffer);
Assert.AreEqual(com.DirectSendBuffer, resCom.DirectSendBuffer);
Assert.AreEqual(com.IdleConnectionTimeout, resCom.IdleConnectionTimeout);
Assert.AreEqual(com.LocalAddress, resCom.LocalAddress);
Assert.AreEqual(com.LocalPort, resCom.LocalPort);
Assert.AreEqual(com.LocalPortRange, resCom.LocalPortRange);
Assert.AreEqual(com.MaxConnectTimeout, resCom.MaxConnectTimeout);
Assert.AreEqual(com.MessageQueueLimit, resCom.MessageQueueLimit);
Assert.AreEqual(com.ReconnectCount, resCom.ReconnectCount);
Assert.AreEqual(com.SelectorsCount, resCom.SelectorsCount);
Assert.AreEqual(com.SlowClientQueueLimit, resCom.SlowClientQueueLimit);
Assert.AreEqual(com.SocketReceiveBufferSize, resCom.SocketReceiveBufferSize);
Assert.AreEqual(com.SocketSendBufferSize, resCom.SocketSendBufferSize);
Assert.AreEqual(com.TcpNoDelay, resCom.TcpNoDelay);
Assert.AreEqual(com.UnacknowledgedMessagesBufferSize, resCom.UnacknowledgedMessagesBufferSize);
Assert.AreEqual(cfg.FailureDetectionTimeout, resCfg.FailureDetectionTimeout);
Assert.AreEqual(cfg.ClientFailureDetectionTimeout, resCfg.ClientFailureDetectionTimeout);
Assert.AreEqual(cfg.LongQueryWarningTimeout, resCfg.LongQueryWarningTimeout);
Assert.AreEqual(cfg.PublicThreadPoolSize, resCfg.PublicThreadPoolSize);
Assert.AreEqual(cfg.StripedThreadPoolSize, resCfg.StripedThreadPoolSize);
Assert.AreEqual(cfg.ServiceThreadPoolSize, resCfg.ServiceThreadPoolSize);
Assert.AreEqual(cfg.SystemThreadPoolSize, resCfg.SystemThreadPoolSize);
Assert.AreEqual(cfg.AsyncCallbackThreadPoolSize, resCfg.AsyncCallbackThreadPoolSize);
Assert.AreEqual(cfg.ManagementThreadPoolSize, resCfg.ManagementThreadPoolSize);
Assert.AreEqual(cfg.DataStreamerThreadPoolSize, resCfg.DataStreamerThreadPoolSize);
Assert.AreEqual(cfg.UtilityCacheThreadPoolSize, resCfg.UtilityCacheThreadPoolSize);
Assert.AreEqual(cfg.QueryThreadPoolSize, resCfg.QueryThreadPoolSize);
Assert.AreEqual(cfg.ConsistentId, resCfg.ConsistentId);
var binCfg = cfg.BinaryConfiguration;
Assert.IsFalse(binCfg.CompactFooter);
var typ = binCfg.TypeConfigurations.Single();
Assert.AreEqual("myType", typ.TypeName);
Assert.IsTrue(typ.IsEnum);
Assert.AreEqual("affKey", typ.AffinityKeyFieldName);
Assert.AreEqual(false, typ.KeepDeserialized);
Assert.IsNotNull(resCfg.PluginConfigurations);
Assert.AreEqual(cfg.PluginConfigurations, resCfg.PluginConfigurations);
var eventCfg = cfg.EventStorageSpi as MemoryEventStorageSpi;
var resEventCfg = resCfg.EventStorageSpi as MemoryEventStorageSpi;
Assert.IsNotNull(eventCfg);
Assert.IsNotNull(resEventCfg);
Assert.AreEqual(eventCfg.ExpirationTimeout, resEventCfg.ExpirationTimeout);
Assert.AreEqual(eventCfg.MaxEventCount, resEventCfg.MaxEventCount);
var sql = cfg.SqlConnectorConfiguration;
var resSql = resCfg.SqlConnectorConfiguration;
Assert.AreEqual(sql.Host, resSql.Host);
Assert.AreEqual(sql.Port, resSql.Port);
Assert.AreEqual(sql.PortRange, resSql.PortRange);
Assert.AreEqual(sql.MaxOpenCursorsPerConnection, resSql.MaxOpenCursorsPerConnection);
Assert.AreEqual(sql.SocketReceiveBufferSize, resSql.SocketReceiveBufferSize);
Assert.AreEqual(sql.SocketSendBufferSize, resSql.SocketSendBufferSize);
Assert.AreEqual(sql.TcpNoDelay, resSql.TcpNoDelay);
Assert.AreEqual(sql.ThreadPoolSize, resSql.ThreadPoolSize);
AssertExtensions.ReflectionEqual(cfg.DataStorageConfiguration, resCfg.DataStorageConfiguration);
}
}
/// <summary>
/// Tests the spring XML.
/// </summary>
[Test]
public void TestSpringXml()
{
// When Spring XML is used, .NET overrides Spring.
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DataStorageConfiguration = null,
SpringConfigUrl = Path.Combine("Config", "spring-test.xml"),
NetworkSendRetryDelay = TimeSpan.FromSeconds(45),
MetricsHistorySize = 57
};
using (var ignite = Ignition.Start(cfg))
{
var resCfg = ignite.GetConfiguration();
Assert.AreEqual(45, resCfg.NetworkSendRetryDelay.TotalSeconds); // .NET overrides XML
Assert.AreEqual(2999, resCfg.NetworkTimeout.TotalMilliseconds); // Not set in .NET -> comes from XML
Assert.AreEqual(57, resCfg.MetricsHistorySize); // Only set in .NET
var disco = resCfg.DiscoverySpi as TcpDiscoverySpi;
Assert.IsNotNull(disco);
Assert.AreEqual(TimeSpan.FromMilliseconds(300), disco.SocketTimeout);
// DataStorage defaults.
CheckDefaultProperties(resCfg.DataStorageConfiguration);
CheckDefaultProperties(resCfg.DataStorageConfiguration.DefaultDataRegionConfiguration);
// Connector defaults.
CheckDefaultProperties(resCfg.ClientConnectorConfiguration);
}
}
/// <summary>
/// Tests the client mode.
/// </summary>
[Test]
public void TestClientMode()
{
using (var ignite = Ignition.Start(new IgniteConfiguration
{
Localhost = "127.0.0.1",
DiscoverySpi = TestUtils.GetStaticDiscovery()
}))
using (var ignite2 = Ignition.Start(new IgniteConfiguration
{
Localhost = "127.0.0.1",
DiscoverySpi = TestUtils.GetStaticDiscovery(),
IgniteInstanceName = "client",
ClientMode = true
}))
{
const string cacheName = "cache";
ignite.CreateCache<int, int>(cacheName);
Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count);
Assert.AreEqual(1, ignite.GetCluster().ForCacheNodes(cacheName).GetNodes().Count);
Assert.AreEqual(false, ignite.GetConfiguration().ClientMode);
Assert.AreEqual(true, ignite2.GetConfiguration().ClientMode);
}
}
/// <summary>
/// Tests the default spi.
/// </summary>
[Test]
public void TestDefaultSpi()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi =
new TcpDiscoverySpi
{
AckTimeout = TimeSpan.FromDays(2),
MaxAckTimeout = TimeSpan.MaxValue,
JoinTimeout = TimeSpan.MaxValue,
NetworkTimeout = TimeSpan.MaxValue,
SocketTimeout = TimeSpan.MaxValue
}
};
using (var ignite = Ignition.Start(cfg))
{
cfg.IgniteInstanceName = "ignite2";
using (var ignite2 = Ignition.Start(cfg))
{
Assert.AreEqual(2, ignite.GetCluster().GetNodes().Count);
Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count);
}
}
}
/// <summary>
/// Tests the invalid timeouts.
/// </summary>
[Test]
public void TestInvalidTimeouts()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi =
new TcpDiscoverySpi
{
AckTimeout = TimeSpan.FromMilliseconds(-5),
JoinTimeout = TimeSpan.MinValue
}
};
Assert.Throws<IgniteException>(() => Ignition.Start(cfg));
}
/// <summary>
/// Tests the static ip finder.
/// </summary>
[Test]
public void TestStaticIpFinder()
{
TestIpFinders(new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] {"127.0.0.1:47500"}
}, new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] {"127.0.0.1:47501"}
});
}
/// <summary>
/// Tests the multicast ip finder.
/// </summary>
[Test]
public void TestMulticastIpFinder()
{
TestIpFinders(
new TcpDiscoveryMulticastIpFinder {MulticastGroup = "228.111.111.222", MulticastPort = 54522},
new TcpDiscoveryMulticastIpFinder {MulticastGroup = "228.111.111.223", MulticastPort = 54522});
}
/// <summary>
/// Tests the work directory.
/// </summary>
[Test]
public void TestWorkDirectory()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
WorkDirectory = TestUtils.GetTempDirectoryName()
};
using (Ignition.Start(cfg))
{
var marshDir = Path.Combine(cfg.WorkDirectory, "marshaller");
Assert.IsTrue(Directory.Exists(marshDir));
}
Directory.Delete(cfg.WorkDirectory, true);
}
/// <summary>
/// Tests the consistent id.
/// </summary>
[Test]
[NUnit.Framework.Category(TestUtils.CategoryIntensive)]
public void TestConsistentId()
{
var ids = new object[]
{
null, new MyConsistentId {Data = "foo"}, "str", 1, 1.1, DateTime.Now, Guid.NewGuid()
};
var cfg = TestUtils.GetTestConfiguration();
foreach (var id in ids)
{
cfg.ConsistentId = id;
using (var ignite = Ignition.Start(cfg))
{
Assert.AreEqual(id, ignite.GetConfiguration().ConsistentId);
Assert.AreEqual(id ?? "127.0.0.1:47500", ignite.GetCluster().GetLocalNode().ConsistentId);
}
}
}
/// <summary>
/// Tests the ip finders.
/// </summary>
/// <param name="ipFinder">The ip finder.</param>
/// <param name="ipFinder2">The ip finder2.</param>
private static void TestIpFinders(TcpDiscoveryIpFinderBase ipFinder, TcpDiscoveryIpFinderBase ipFinder2)
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi =
new TcpDiscoverySpi
{
IpFinder = ipFinder
}
};
using (var ignite = Ignition.Start(cfg))
{
// Start with the same endpoint
cfg.IgniteInstanceName = "ignite2";
using (var ignite2 = Ignition.Start(cfg))
{
Assert.AreEqual(2, ignite.GetCluster().GetNodes().Count);
Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count);
}
// Start with incompatible endpoint and check that there are 2 topologies
((TcpDiscoverySpi) cfg.DiscoverySpi).IpFinder = ipFinder2;
using (var ignite2 = Ignition.Start(cfg))
{
Assert.AreEqual(1, ignite.GetCluster().GetNodes().Count);
Assert.AreEqual(1, ignite2.GetCluster().GetNodes().Count);
}
}
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">The CFG.</param>
private static void CheckDefaultProperties(IgniteConfiguration cfg)
{
Assert.AreEqual(IgniteConfiguration.DefaultMetricsExpireTime, cfg.MetricsExpireTime);
Assert.AreEqual(IgniteConfiguration.DefaultMetricsHistorySize, cfg.MetricsHistorySize);
Assert.AreEqual(IgniteConfiguration.DefaultMetricsLogFrequency, cfg.MetricsLogFrequency);
Assert.AreEqual(IgniteConfiguration.DefaultMetricsUpdateFrequency, cfg.MetricsUpdateFrequency);
Assert.AreEqual(IgniteConfiguration.DefaultNetworkTimeout, cfg.NetworkTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultNetworkSendRetryCount, cfg.NetworkSendRetryCount);
Assert.AreEqual(IgniteConfiguration.DefaultNetworkSendRetryDelay, cfg.NetworkSendRetryDelay);
Assert.AreEqual(IgniteConfiguration.DefaultFailureDetectionTimeout, cfg.FailureDetectionTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultClientFailureDetectionTimeout,
cfg.ClientFailureDetectionTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultLongQueryWarningTimeout, cfg.LongQueryWarningTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultIsLateAffinityAssignment, cfg.IsLateAffinityAssignment);
Assert.AreEqual(IgniteConfiguration.DefaultIsActiveOnStart, cfg.IsActiveOnStart);
Assert.AreEqual(IgniteConfiguration.DefaultClientConnectorConfigurationEnabled,
cfg.ClientConnectorConfigurationEnabled);
Assert.AreEqual(IgniteConfiguration.DefaultRedirectJavaConsoleOutput, cfg.RedirectJavaConsoleOutput);
// Thread pools.
Assert.AreEqual(IgniteConfiguration.DefaultManagementThreadPoolSize, cfg.ManagementThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.PublicThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.StripedThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.ServiceThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.SystemThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.AsyncCallbackThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.DataStreamerThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.UtilityCacheThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.QueryThreadPoolSize);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(PersistentStoreConfiguration cfg)
{
Assert.AreEqual(PersistentStoreConfiguration.DefaultTlbSize, cfg.TlbSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointingFrequency, cfg.CheckpointingFrequency);
Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointingThreads, cfg.CheckpointingThreads);
Assert.AreEqual(default(long), cfg.CheckpointingPageBufferSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultLockWaitTime, cfg.LockWaitTime);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalFlushFrequency, cfg.WalFlushFrequency);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalFsyncDelayNanos, cfg.WalFsyncDelayNanos);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalHistorySize, cfg.WalHistorySize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalRecordIteratorBufferSize,
cfg.WalRecordIteratorBufferSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalSegmentSize, cfg.WalSegmentSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalSegments, cfg.WalSegments);
Assert.AreEqual(WalMode.Default, cfg.WalMode);
Assert.IsFalse(cfg.MetricsEnabled);
Assert.AreEqual(PersistentStoreConfiguration.DefaultSubIntervals, cfg.SubIntervals);
Assert.AreEqual(PersistentStoreConfiguration.DefaultRateTimeInterval, cfg.RateTimeInterval);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalStorePath, cfg.WalStorePath);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalArchivePath, cfg.WalArchivePath);
Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointWriteOrder, cfg.CheckpointWriteOrder);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWriteThrottlingEnabled, cfg.WriteThrottlingEnabled);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(DataStorageConfiguration cfg)
{
Assert.AreEqual(DataStorageConfiguration.DefaultTlbSize, cfg.WalThreadLocalBufferSize);
Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointFrequency, cfg.CheckpointFrequency);
Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointThreads, cfg.CheckpointThreads);
Assert.AreEqual(DataStorageConfiguration.DefaultLockWaitTime, cfg.LockWaitTime);
Assert.AreEqual(DataStorageConfiguration.DefaultWalFlushFrequency, cfg.WalFlushFrequency);
Assert.AreEqual(DataStorageConfiguration.DefaultWalFsyncDelayNanos, cfg.WalFsyncDelayNanos);
Assert.AreEqual(DataStorageConfiguration.DefaultWalHistorySize, cfg.WalHistorySize);
Assert.AreEqual(DataStorageConfiguration.DefaultWalRecordIteratorBufferSize,
cfg.WalRecordIteratorBufferSize);
Assert.AreEqual(DataStorageConfiguration.DefaultWalSegmentSize, cfg.WalSegmentSize);
Assert.AreEqual(DataStorageConfiguration.DefaultWalSegments, cfg.WalSegments);
Assert.AreEqual(DataStorageConfiguration.DefaultWalMode, cfg.WalMode);
Assert.IsFalse(cfg.MetricsEnabled);
Assert.AreEqual(DataStorageConfiguration.DefaultMetricsSubIntervalCount, cfg.MetricsSubIntervalCount);
Assert.AreEqual(DataStorageConfiguration.DefaultMetricsRateTimeInterval, cfg.MetricsRateTimeInterval);
Assert.AreEqual(DataStorageConfiguration.DefaultWalPath, cfg.WalPath);
Assert.AreEqual(DataStorageConfiguration.DefaultWalArchivePath, cfg.WalArchivePath);
Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointWriteOrder, cfg.CheckpointWriteOrder);
Assert.AreEqual(DataStorageConfiguration.DefaultWriteThrottlingEnabled, cfg.WriteThrottlingEnabled);
Assert.AreEqual(DataStorageConfiguration.DefaultSystemRegionInitialSize, cfg.SystemRegionInitialSize);
Assert.AreEqual(DataStorageConfiguration.DefaultSystemRegionMaxSize, cfg.SystemRegionMaxSize);
Assert.AreEqual(DataStorageConfiguration.DefaultPageSize, cfg.PageSize);
Assert.AreEqual(DataStorageConfiguration.DefaultConcurrencyLevel, cfg.ConcurrencyLevel);
Assert.AreEqual(DataStorageConfiguration.DefaultWalAutoArchiveAfterInactivity,
cfg.WalAutoArchiveAfterInactivity);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(DataRegionConfiguration cfg)
{
Assert.AreEqual(DataRegionConfiguration.DefaultEmptyPagesPoolSize, cfg.EmptyPagesPoolSize);
Assert.AreEqual(DataRegionConfiguration.DefaultEvictionThreshold, cfg.EvictionThreshold);
Assert.AreEqual(DataRegionConfiguration.DefaultInitialSize, cfg.InitialSize);
Assert.AreEqual(DataRegionConfiguration.DefaultMaxSize, cfg.MaxSize);
Assert.AreEqual(DataRegionConfiguration.DefaultPersistenceEnabled, cfg.PersistenceEnabled);
Assert.AreEqual(DataRegionConfiguration.DefaultMetricsRateTimeInterval, cfg.MetricsRateTimeInterval);
Assert.AreEqual(DataRegionConfiguration.DefaultMetricsSubIntervalCount, cfg.MetricsSubIntervalCount);
Assert.AreEqual(default(long), cfg.CheckpointPageBufferSize);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(ClientConnectorConfiguration cfg)
{
Assert.AreEqual(ClientConnectorConfiguration.DefaultPort, cfg.Port);
Assert.AreEqual(ClientConnectorConfiguration.DefaultPortRange, cfg.PortRange);
Assert.AreEqual(ClientConnectorConfiguration.DefaultMaxOpenCursorsPerConnection,
cfg.MaxOpenCursorsPerConnection);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketReceiveBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketSendBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultTcpNoDelay, cfg.TcpNoDelay);
Assert.AreEqual(ClientConnectorConfiguration.DefaultThreadPoolSize, cfg.ThreadPoolSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultIdleTimeout, cfg.IdleTimeout);
Assert.AreEqual(ClientConnectorConfiguration.DefaultThinClientEnabled, cfg.ThinClientEnabled);
Assert.AreEqual(ClientConnectorConfiguration.DefaultJdbcEnabled, cfg.JdbcEnabled);
Assert.AreEqual(ClientConnectorConfiguration.DefaultOdbcEnabled, cfg.OdbcEnabled);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(SqlConnectorConfiguration cfg)
{
Assert.AreEqual(ClientConnectorConfiguration.DefaultPort, cfg.Port);
Assert.AreEqual(ClientConnectorConfiguration.DefaultPortRange, cfg.PortRange);
Assert.AreEqual(ClientConnectorConfiguration.DefaultMaxOpenCursorsPerConnection,
cfg.MaxOpenCursorsPerConnection);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketReceiveBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketSendBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultTcpNoDelay, cfg.TcpNoDelay);
Assert.AreEqual(ClientConnectorConfiguration.DefaultThreadPoolSize, cfg.ThreadPoolSize);
}
/// <summary>
/// Checks the default value attributes.
/// </summary>
/// <param name="obj">The object.</param>
private static void CheckDefaultValueAttributes(object obj)
{
var props = obj.GetType().GetProperties();
foreach (var prop in props.Where(p => p.Name != "SelectorsCount" && p.Name != "ReadStripesNumber" &&
!p.Name.Contains("ThreadPoolSize") &&
p.Name != "MaxSize"))
{
var attr = prop.GetCustomAttributes(true).OfType<DefaultValueAttribute>().FirstOrDefault();
var propValue = prop.GetValue(obj, null);
if (attr != null)
Assert.AreEqual(attr.Value, propValue, string.Format("{0}.{1}", obj.GetType(), prop.Name));
else if (prop.PropertyType.IsValueType)
Assert.AreEqual(Activator.CreateInstance(prop.PropertyType), propValue, prop.Name);
else
Assert.IsNull(propValue);
}
}
/// <summary>
/// Gets the custom configuration.
/// </summary>
private static IgniteConfiguration GetCustomConfig()
{
// CacheConfiguration is not tested here - see CacheConfigurationTest
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi = new TcpDiscoverySpi
{
NetworkTimeout = TimeSpan.FromSeconds(1),
AckTimeout = TimeSpan.FromSeconds(2),
MaxAckTimeout = TimeSpan.FromSeconds(3),
SocketTimeout = TimeSpan.FromSeconds(4),
JoinTimeout = TimeSpan.FromSeconds(5),
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] {"127.0.0.1:49900", "127.0.0.1:49901"}
},
ClientReconnectDisabled = true,
ForceServerMode = true,
IpFinderCleanFrequency = TimeSpan.FromMinutes(7),
LocalAddress = "127.0.0.1",
LocalPort = 49900,
LocalPortRange = 13,
ReconnectCount = 11,
StatisticsPrintFrequency = TimeSpan.FromSeconds(20),
ThreadPriority = 6,
TopologyHistorySize = 1234567
},
IgniteInstanceName = "gridName1",
IgniteHome = IgniteHome.Resolve(null),
IncludedEventTypes = EventType.DiscoveryAll,
MetricsExpireTime = TimeSpan.FromMinutes(7),
MetricsHistorySize = 125,
MetricsLogFrequency = TimeSpan.FromMinutes(8),
MetricsUpdateFrequency = TimeSpan.FromMinutes(9),
NetworkSendRetryCount = 54,
NetworkTimeout = TimeSpan.FromMinutes(10),
NetworkSendRetryDelay = TimeSpan.FromMinutes(11),
WorkDirectory = Path.GetTempPath(),
Localhost = "127.0.0.1",
IsDaemon = false,
IsLateAffinityAssignment = false,
UserAttributes = Enumerable.Range(1, 10).ToDictionary(x => x.ToString(), x => (object) x),
AtomicConfiguration = new AtomicConfiguration
{
CacheMode = CacheMode.Replicated,
Backups = 2,
AtomicSequenceReserveSize = 200
},
TransactionConfiguration = new TransactionConfiguration
{
DefaultTransactionConcurrency = TransactionConcurrency.Optimistic,
DefaultTimeout = TimeSpan.FromSeconds(25),
DefaultTransactionIsolation = TransactionIsolation.Serializable,
PessimisticTransactionLogLinger = TimeSpan.FromHours(1),
PessimisticTransactionLogSize = 240
},
CommunicationSpi = new TcpCommunicationSpi
{
LocalPort = 47501,
MaxConnectTimeout = TimeSpan.FromSeconds(34),
MessageQueueLimit = 15,
ConnectTimeout = TimeSpan.FromSeconds(17),
IdleConnectionTimeout = TimeSpan.FromSeconds(19),
SelectorsCount = 8,
ReconnectCount = 33,
SocketReceiveBufferSize = 512,
AckSendThreshold = 99,
DirectBuffer = false,
DirectSendBuffer = true,
LocalPortRange = 45,
LocalAddress = "127.0.0.1",
TcpNoDelay = false,
SlowClientQueueLimit = 98,
SocketSendBufferSize = 2045,
UnacknowledgedMessagesBufferSize = 3450
},
FailureDetectionTimeout = TimeSpan.FromSeconds(3.5),
ClientFailureDetectionTimeout = TimeSpan.FromMinutes(12.3),
LongQueryWarningTimeout = TimeSpan.FromMinutes(1.23),
IsActiveOnStart = true,
BinaryConfiguration = new BinaryConfiguration
{
CompactFooter = false,
TypeConfigurations = new[]
{
new BinaryTypeConfiguration
{
TypeName = "myType",
IsEnum = true,
AffinityKeyFieldName = "affKey",
KeepDeserialized = false
}
}
},
// Skip cache check because with persistence the grid is not active by default.
PluginConfigurations = new[] {new TestIgnitePluginConfiguration {SkipCacheCheck = true}},
EventStorageSpi = new MemoryEventStorageSpi
{
ExpirationTimeout = TimeSpan.FromSeconds(5),
MaxEventCount = 10
},
PublicThreadPoolSize = 3,
StripedThreadPoolSize = 5,
ServiceThreadPoolSize = 6,
SystemThreadPoolSize = 7,
AsyncCallbackThreadPoolSize = 8,
ManagementThreadPoolSize = 9,
DataStreamerThreadPoolSize = 10,
UtilityCacheThreadPoolSize = 11,
QueryThreadPoolSize = 12,
SqlConnectorConfiguration = new SqlConnectorConfiguration
{
Host = "127.0.0.2",
Port = 1081,
PortRange = 3,
SocketReceiveBufferSize = 2048,
MaxOpenCursorsPerConnection = 5,
ThreadPoolSize = 4,
TcpNoDelay = false,
SocketSendBufferSize = 4096
},
ConsistentId = new MyConsistentId {Data = "abc"},
DataStorageConfiguration = new DataStorageConfiguration
{
AlwaysWriteFullPages = true,
CheckpointFrequency = TimeSpan.FromSeconds(25),
CheckpointThreads = 2,
LockWaitTime = TimeSpan.FromSeconds(5),
StoragePath = Path.GetTempPath(),
WalThreadLocalBufferSize = 64 * 1024,
WalArchivePath = Path.GetTempPath(),
WalFlushFrequency = TimeSpan.FromSeconds(3),
WalFsyncDelayNanos = 3,
WalHistorySize = 10,
WalMode = Configuration.WalMode.LogOnly,
WalRecordIteratorBufferSize = 32 * 1024 * 1024,
WalSegments = 6,
WalSegmentSize = 5 * 1024 * 1024,
WalPath = Path.GetTempPath(),
MetricsEnabled = true,
MetricsSubIntervalCount = 7,
MetricsRateTimeInterval = TimeSpan.FromSeconds(9),
CheckpointWriteOrder = Configuration.CheckpointWriteOrder.Random,
WriteThrottlingEnabled = true,
SystemRegionInitialSize = 64 * 1024 * 1024,
SystemRegionMaxSize = 128 * 1024 * 1024,
ConcurrencyLevel = 1,
PageSize = 8 * 1024,
WalAutoArchiveAfterInactivity = TimeSpan.FromMinutes(5),
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
Name = "reg1",
EmptyPagesPoolSize = 50,
EvictionThreshold = 0.8,
InitialSize = 100 * 1024 * 1024,
MaxSize = 150 * 1024 * 1024,
MetricsEnabled = true,
PageEvictionMode = Configuration.DataPageEvictionMode.Random2Lru,
PersistenceEnabled = false,
MetricsRateTimeInterval = TimeSpan.FromMinutes(2),
MetricsSubIntervalCount = 6,
SwapPath = TestUtils.GetTempDirectoryName(),
CheckpointPageBufferSize = 28 * 1024 * 1024
},
DataRegionConfigurations = new[]
{
new DataRegionConfiguration
{
Name = "reg2",
EmptyPagesPoolSize = 51,
EvictionThreshold = 0.7,
InitialSize = 101 * 1024 * 1024,
MaxSize = 151 * 1024 * 1024,
MetricsEnabled = false,
PageEvictionMode = Configuration.DataPageEvictionMode.RandomLru,
PersistenceEnabled = false,
MetricsRateTimeInterval = TimeSpan.FromMinutes(3),
MetricsSubIntervalCount = 7,
SwapPath = TestUtils.GetTempDirectoryName()
}
}
}
};
}
private class MyConsistentId
{
public string Data { get; set; }
private bool Equals(MyConsistentId other)
{
return string.Equals(Data, other.Data);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((MyConsistentId) obj);
}
public override int GetHashCode()
{
return (Data != null ? Data.GetHashCode() : 0);
}
public static bool operator ==(MyConsistentId left, MyConsistentId right)
{
return Equals(left, right);
}
public static bool operator !=(MyConsistentId left, MyConsistentId right)
{
return !Equals(left, right);
}
}
}
}
| |
namespace PositionSetEditer
{
partial class LayersEditerForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LayersEditerForm));
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.saveToolStripButton = new System.Windows.Forms.ToolStripButton();
this.openToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.pointerToolStripButton = new System.Windows.Forms.ToolStripButton();
this.nodeToolStripButton = new System.Windows.Forms.ToolStripButton();
this.connectionToolStripButton = new System.Windows.Forms.ToolStripButton();
this.doubleConnectionToolStripButton = new System.Windows.Forms.ToolStripButton();
this.eraserToolStripButton = new System.Windows.Forms.ToolStripButton();
this.clearToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.startPositionToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem();
this.blockSizeToolStripTextBox = new System.Windows.Forms.ToolStripTextBox();
this.endPositionToolStripButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripSplitButton1 = new System.Windows.Forms.ToolStripSplitButton();
this.doubleSizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.halfSizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton2 = new System.Windows.Forms.ToolStripButton();
this.toolStripButton8 = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel();
this.PositionCoordinateLabel = new System.Windows.Forms.ToolStripLabel();
this.toolStrip1.SuspendLayout();
this.SuspendLayout();
//
// toolStrip1
//
this.toolStrip1.AllowDrop = true;
this.toolStrip1.BackColor = System.Drawing.SystemColors.Control;
this.toolStrip1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.saveToolStripButton,
this.openToolStripButton,
this.toolStripSeparator5,
this.pointerToolStripButton,
this.nodeToolStripButton,
this.connectionToolStripButton,
this.doubleConnectionToolStripButton,
this.eraserToolStripButton,
this.clearToolStripButton,
this.toolStripSeparator8,
this.startPositionToolStripButton,
this.toolStripDropDownButton1,
this.endPositionToolStripButton,
this.toolStripSeparator1,
this.toolStripSplitButton1,
this.toolStripSeparator6,
this.toolStripButton1,
this.toolStripButton2,
this.toolStripButton8,
this.toolStripSeparator2,
this.toolStripLabel3,
this.PositionCoordinateLabel});
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(723, 25);
this.toolStrip1.Stretch = true;
this.toolStrip1.TabIndex = 4;
this.toolStrip1.Text = "toolStrip1";
//
// saveToolStripButton
//
this.saveToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.saveToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripButton.Image")));
this.saveToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.saveToolStripButton.Name = "saveToolStripButton";
this.saveToolStripButton.Size = new System.Drawing.Size(23, 22);
this.saveToolStripButton.Text = "&Save";
this.saveToolStripButton.ToolTipText = "Save map to file";
//
// openToolStripButton
//
this.openToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.openToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripButton.Image")));
this.openToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.openToolStripButton.Name = "openToolStripButton";
this.openToolStripButton.Size = new System.Drawing.Size(23, 22);
this.openToolStripButton.Text = "&Open";
this.openToolStripButton.ToolTipText = "Load map from file";
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25);
//
// pointerToolStripButton
//
this.pointerToolStripButton.Checked = true;
this.pointerToolStripButton.CheckState = System.Windows.Forms.CheckState.Checked;
this.pointerToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.pointerToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("pointerToolStripButton.Image")));
this.pointerToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.pointerToolStripButton.Name = "pointerToolStripButton";
this.pointerToolStripButton.Size = new System.Drawing.Size(23, 22);
this.pointerToolStripButton.Text = "toolStripButton8";
this.pointerToolStripButton.ToolTipText = "Pointer";
//
// nodeToolStripButton
//
this.nodeToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.nodeToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("nodeToolStripButton.Image")));
this.nodeToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.nodeToolStripButton.Name = "nodeToolStripButton";
this.nodeToolStripButton.Size = new System.Drawing.Size(23, 22);
this.nodeToolStripButton.Text = "toolStripButton1";
this.nodeToolStripButton.ToolTipText = "Add Node";
//
// connectionToolStripButton
//
this.connectionToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.connectionToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("connectionToolStripButton.Image")));
this.connectionToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.connectionToolStripButton.Name = "connectionToolStripButton";
this.connectionToolStripButton.Size = new System.Drawing.Size(23, 22);
this.connectionToolStripButton.Text = "toolStripButton9";
this.connectionToolStripButton.ToolTipText = "Add Single Connection";
//
// doubleConnectionToolStripButton
//
this.doubleConnectionToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.doubleConnectionToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("doubleConnectionToolStripButton.Image")));
this.doubleConnectionToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.doubleConnectionToolStripButton.Name = "doubleConnectionToolStripButton";
this.doubleConnectionToolStripButton.Size = new System.Drawing.Size(23, 22);
this.doubleConnectionToolStripButton.Text = "toolStripButton10";
this.doubleConnectionToolStripButton.ToolTipText = "Add Double Connection";
//
// eraserToolStripButton
//
this.eraserToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.eraserToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("eraserToolStripButton.Image")));
this.eraserToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.eraserToolStripButton.Name = "eraserToolStripButton";
this.eraserToolStripButton.Size = new System.Drawing.Size(23, 22);
this.eraserToolStripButton.Text = "toolStripButton3";
this.eraserToolStripButton.ToolTipText = "Remove Node";
//
// clearToolStripButton
//
this.clearToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.clearToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("clearToolStripButton.Image")));
this.clearToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.clearToolStripButton.Name = "clearToolStripButton";
this.clearToolStripButton.Size = new System.Drawing.Size(23, 22);
this.clearToolStripButton.Text = "toolStripButton4";
this.clearToolStripButton.ToolTipText = "Clear Map";
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(6, 25);
//
// startPositionToolStripButton
//
this.startPositionToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.startPositionToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("startPositionToolStripButton.Image")));
this.startPositionToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.startPositionToolStripButton.Name = "startPositionToolStripButton";
this.startPositionToolStripButton.Size = new System.Drawing.Size(23, 22);
this.startPositionToolStripButton.Text = "toolStripButton2";
this.startPositionToolStripButton.ToolTipText = "Set Start Point";
//
// toolStripDropDownButton1
//
this.toolStripDropDownButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripDropDownButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem4,
this.toolStripMenuItem5,
this.blockSizeToolStripTextBox});
this.toolStripDropDownButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripDropDownButton1.Image")));
this.toolStripDropDownButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripDropDownButton1.Name = "toolStripDropDownButton1";
this.toolStripDropDownButton1.Size = new System.Drawing.Size(29, 22);
this.toolStripDropDownButton1.Text = "Zoom";
this.toolStripDropDownButton1.ToolTipText = "Block Size(in pixel)";
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem4.Image")));
this.toolStripMenuItem4.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(190, 22);
this.toolStripMenuItem4.Text = "Double Size(200%)(&D)";
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem5.Image")));
this.toolStripMenuItem5.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(190, 22);
this.toolStripMenuItem5.Text = "Half Size(50%)(&H)";
//
// blockSizeToolStripTextBox
//
this.blockSizeToolStripTextBox.Name = "blockSizeToolStripTextBox";
this.blockSizeToolStripTextBox.Size = new System.Drawing.Size(100, 21);
this.blockSizeToolStripTextBox.ToolTipText = "Input Block Size(in pixel)";
//
// endPositionToolStripButton
//
this.endPositionToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.endPositionToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("endPositionToolStripButton.Image")));
this.endPositionToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.endPositionToolStripButton.Name = "endPositionToolStripButton";
this.endPositionToolStripButton.Size = new System.Drawing.Size(23, 22);
this.endPositionToolStripButton.Text = "toolStripButton1";
this.endPositionToolStripButton.ToolTipText = "Set End Point";
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// toolStripSplitButton1
//
this.toolStripSplitButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolStripSplitButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.doubleSizeToolStripMenuItem,
this.halfSizeToolStripMenuItem});
this.toolStripSplitButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripSplitButton1.Image")));
this.toolStripSplitButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripSplitButton1.Name = "toolStripSplitButton1";
this.toolStripSplitButton1.Size = new System.Drawing.Size(32, 22);
this.toolStripSplitButton1.Text = "Change map size";
//
// doubleSizeToolStripMenuItem
//
this.doubleSizeToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("doubleSizeToolStripMenuItem.Image")));
this.doubleSizeToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.doubleSizeToolStripMenuItem.Name = "doubleSizeToolStripMenuItem";
this.doubleSizeToolStripMenuItem.Size = new System.Drawing.Size(190, 22);
this.doubleSizeToolStripMenuItem.Text = "Double Size(200%)(&D)";
//
// halfSizeToolStripMenuItem
//
this.halfSizeToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("halfSizeToolStripMenuItem.Image")));
this.halfSizeToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.Fuchsia;
this.halfSizeToolStripMenuItem.Name = "halfSizeToolStripMenuItem";
this.halfSizeToolStripMenuItem.Size = new System.Drawing.Size(190, 22);
this.halfSizeToolStripMenuItem.Text = "Half Size(50%)(&H)";
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(6, 25);
//
// toolStripButton1
//
this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Size = new System.Drawing.Size(73, 22);
this.toolStripButton1.Text = "Dijkstra";
this.toolStripButton1.ToolTipText = "Search for path";
//
// toolStripButton2
//
this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image")));
this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton2.Name = "toolStripButton2";
this.toolStripButton2.Size = new System.Drawing.Size(37, 22);
this.toolStripButton2.Text = "A*";
//
// toolStripButton8
//
this.toolStripButton8.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton8.Image")));
this.toolStripButton8.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolStripButton8.Name = "toolStripButton8";
this.toolStripButton8.Size = new System.Drawing.Size(61, 22);
this.toolStripButton8.Text = "Detail";
this.toolStripButton8.ToolTipText = "Show detail about the nodes and the path";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
//
// toolStripLabel3
//
this.toolStripLabel3.Name = "toolStripLabel3";
this.toolStripLabel3.Size = new System.Drawing.Size(59, 22);
this.toolStripLabel3.Text = "Position:";
//
// PositionCoordinateLabel
//
this.PositionCoordinateLabel.Name = "PositionCoordinateLabel";
this.PositionCoordinateLabel.Size = new System.Drawing.Size(11, 22);
this.PositionCoordinateLabel.Text = " ";
this.PositionCoordinateLabel.ToolTipText = "Mouse Position(row,column)(x,y)";
//
// LayersEditerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(723, 448);
this.Controls.Add(this.toolStrip1);
this.IsMdiContainer = true;
this.Name = "LayersEditerForm";
this.Text = "PositionSet Editer";
this.Load += new System.EventHandler(this.PositionSetEditerForm_Load);
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.ToolStripButton saveToolStripButton;
private System.Windows.Forms.ToolStripButton openToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripButton pointerToolStripButton;
private System.Windows.Forms.ToolStripButton nodeToolStripButton;
private System.Windows.Forms.ToolStripButton connectionToolStripButton;
private System.Windows.Forms.ToolStripButton doubleConnectionToolStripButton;
private System.Windows.Forms.ToolStripButton eraserToolStripButton;
private System.Windows.Forms.ToolStripButton clearToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripButton startPositionToolStripButton;
private System.Windows.Forms.ToolStripButton endPositionToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton1;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem4;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5;
private System.Windows.Forms.ToolStripTextBox blockSizeToolStripTextBox;
private System.Windows.Forms.ToolStripSplitButton toolStripSplitButton1;
private System.Windows.Forms.ToolStripMenuItem doubleSizeToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem halfSizeToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripButton toolStripButton1;
private System.Windows.Forms.ToolStripButton toolStripButton2;
private System.Windows.Forms.ToolStripButton toolStripButton8;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripLabel toolStripLabel3;
private System.Windows.Forms.ToolStripLabel PositionCoordinateLabel;
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Text;
namespace PlatformAPI.GDIPlus
{
//--------------------------------------------------------------------------
// Represents a dimension in a 2D coordinate system (floating-point coordinates)
//--------------------------------------------------------------------------
public struct GpSizeF
{
public GpSizeF(GpSizeF size)
{
Width = size.Width;
Height = size.Height;
}
public GpSizeF(float width,
float height)
{
Width = width;
Height = height;
}
public static GpSizeF operator +(GpSizeF sz1, GpSizeF sz2)
{
return new GpSizeF(sz1.Width + sz2.Width, sz1.Height + sz2.Height);
}
public static GpSizeF operator -(GpSizeF sz1, GpSizeF sz2)
{
return new GpSizeF(sz1.Width - sz2.Width, sz1.Height - sz2.Height);
}
public override bool Equals(object obj)
{
return (obj != null) &&
(obj is GpSizeF) &&
(Equals((GpSizeF)obj));
}
public bool Equals(GpSizeF sz)
{
return (Width == sz.Width) && (Height == sz.Height);
}
public bool Empty()
{
return (Width == 0.0f && Height == 0.0f);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public float Width;
public float Height;
}
//--------------------------------------------------------------------------
// Represents a dimension in a 2D coordinate system (integer coordinates)
//--------------------------------------------------------------------------
public struct GpSize
{
public GpSize(GpSize size)
{
Width = size.Width;
Height = size.Height;
}
public GpSize(int width,
int height)
{
Width = width;
Height = height;
}
public static GpSize operator +(GpSize sz1, GpSize sz2)
{
return new GpSize(sz1.Width + sz2.Width, sz1.Height + sz2.Height);
}
public static GpSize operator -(GpSize sz1, GpSize sz2)
{
return new GpSize(sz1.Width - sz2.Width, sz1.Height - sz2.Height);
}
public override bool Equals(object obj)
{
return (obj != null) &&
(obj is GpSize) &&
Equals((GpSize)obj);
}
public bool Equals(GpSize sz)
{
return (Width == sz.Width) && (Height == sz.Height);
}
public bool Empty()
{
return (Width == 0 && Height == 0);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public int Width;
public int Height;
}
//--------------------------------------------------------------------------
// Represents a location in a 2D coordinate system (floating-point coordinates)
//--------------------------------------------------------------------------
public struct GpPointF
{
public GpPointF(GpPointF point)
{
X = point.X;
Y = point.Y;
}
public GpPointF(GpSizeF size)
{
X = size.Width;
Y = size.Height;
}
public GpPointF(float x,
float y)
{
X = x;
Y = y;
}
public static GpPointF operator +(GpPointF point1, GpPointF point2)
{
return new GpPointF(point1.X + point2.X,
point1.Y + point2.Y);
}
public static GpPointF operator -(GpPointF point1, GpPointF point2)
{
return new GpPointF(point1.X - point2.X,
point1.Y - point2.Y);
}
public override bool Equals(object obj)
{
return (obj != null) &&
(obj is GpPointF) &&
Equals((GpPointF)obj);
}
public bool Equals(GpPointF point)
{
return (X == point.X) && (Y == point.Y);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public float X;
public float Y;
}
//--------------------------------------------------------------------------
// Represents a location in a 2D coordinate system (integer coordinates)
//--------------------------------------------------------------------------
public struct GpPoint
{
public GpPoint(GpPoint point)
{
X = point.X;
Y = point.Y;
}
public GpPoint(GpSize size)
{
X = size.Width;
Y = size.Height;
}
public GpPoint(int x,
int y)
{
X = x;
Y = y;
}
public static GpPoint operator +(GpPoint point1, GpPoint point2)
{
return new GpPoint(point1.X + point2.X,
point1.Y + point2.Y);
}
public static GpPoint operator -(GpPoint point1, GpPoint point2)
{
return new GpPoint(point1.X - point2.X,
point1.Y - point2.Y);
}
public override bool Equals(object obj)
{
return (obj != null) &&
(obj is GpPoint) &&
Equals((GpPoint)obj);
}
public bool Equals(GpPoint point)
{
return (X == point.X) && (Y == point.Y);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public int X;
public int Y;
}
//--------------------------------------------------------------------------
// Represents a rectangle in a 2D coordinate system (floating-point coordinates)
//--------------------------------------------------------------------------
[StructLayout(LayoutKind.Sequential)]
public struct GpRectF
{
public GpRectF(float x,
float y,
float width,
float height)
{
X = x;
Y = y;
Width = width;
Height = height;
}
public GpRectF(GpPointF location,
GpSizeF size)
{
X = location.X;
Y = location.Y;
Width = size.Width;
Height = size.Height;
}
public GpRectF Clone()
{
return new GpRectF(X, Y, Width, Height);
}
public void GetLocation(out GpPointF point)
{
point.X = X;
point.Y = Y;
}
public void GetGpSize(out GpSizeF size)
{
size.Width = Width;
size.Height = Height;
}
public void GetBounds(out GpRectF rect)
{
rect.X = X;
rect.Y = Y;
rect.Width = Width;
rect.Height = Height;
}
public float GetLeft()
{
return X;
}
public float GetTop()
{
return Y;
}
public float GetRight()
{
return X + Width;
}
public float GetBottom()
{
return Y + Height;
}
public bool IsEmptyArea()
{
return (Width <= float.Epsilon) || (Height <= float.Epsilon);
}
public override bool Equals(object obj)
{
if (obj == null || !(obj is GpRectF))
return false;
return Equals((GpRectF)obj);
}
public bool Equals(GpRectF rect)
{
return X == rect.X &&
Y == rect.Y &&
Width == rect.Width &&
Height == rect.Height;
}
public bool Contains(float x,
float y)
{
return x >= X && x < X + Width &&
y >= Y && y < Y + Height;
}
public bool Contains(GpPointF pt)
{
return Contains(pt.X, pt.Y);
}
public bool Contains(GpRectF rect)
{
return (X <= rect.X) && (rect.GetRight() <= GetRight()) &&
(Y <= rect.Y) && (rect.GetBottom() <= GetBottom());
}
public void Inflate(float dx,
float dy)
{
X -= dx;
Y -= dy;
Width += 2 * dx;
Height += 2 * dy;
}
public void Inflate(GpPointF point)
{
Inflate(point.X, point.Y);
}
public bool Intersect(GpRectF rect)
{
return Intersect(out this, this, rect);
}
static public bool Intersect(out GpRectF c,
GpRectF a,
GpRectF b)
{
float right = Math.Min(a.GetRight(), b.GetRight());
float bottom = Math.Min(a.GetBottom(), b.GetBottom());
float left = Math.Max(a.GetLeft(), b.GetLeft());
float top = Math.Max(a.GetTop(), b.GetTop());
c.X = left;
c.Y = top;
c.Width = right - left;
c.Height = bottom - top;
return !c.IsEmptyArea();
}
public bool IntersectsWith(GpRectF rect)
{
return (GetLeft() < rect.GetRight() &&
GetTop() < rect.GetBottom() &&
GetRight() > rect.GetLeft() &&
GetBottom() > rect.GetTop());
}
static public bool Union(out GpRectF c,
GpRectF a,
GpRectF b)
{
float right = Math.Max(a.GetRight(), b.GetRight());
float bottom = Math.Max(a.GetBottom(), b.GetBottom());
float left = Math.Min(a.GetLeft(), b.GetLeft());
float top = Math.Min(a.GetTop(), b.GetTop());
c.X = left;
c.Y = top;
c.Width = right - left;
c.Height = bottom - top;
return !c.IsEmptyArea();
}
public void Offset(GpPointF point)
{
Offset(point.X, point.Y);
}
public void Offset(float dx,
float dy)
{
X += dx;
Y += dy;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public float X;
public float Y;
public float Width;
public float Height;
}
//--------------------------------------------------------------------------
// Represents a rectangle in a 2D coordinate system (integer coordinates)
//--------------------------------------------------------------------------
public struct GpRect
{
public GpRect(int x,
int y,
int width,
int height)
{
X = x;
Y = y;
Width = width;
Height = height;
}
public GpRect(GpPoint location,
GpSize size)
{
X = location.X;
Y = location.Y;
Width = size.Width;
Height = size.Height;
}
public GpRect Clone()
{
return new GpRect(X, Y, Width, Height);
}
public void GetLocation(out GpPoint point)
{
point.X = X;
point.Y = Y;
}
public void GetGpSize(out GpSize size)
{
size.Width = Width;
size.Height = Height;
}
public void GetBounds(out GpRect rect)
{
rect.X = X;
rect.Y = Y;
rect.Width = Width;
rect.Height = Height;
}
public int GetLeft()
{
return X;
}
public int GetTop()
{
return Y;
}
public int GetRight()
{
return X + Width;
}
public int GetBottom()
{
return Y + Height;
}
public bool IsEmptyArea()
{
return (Width <= 0) || (Height <= 0);
}
public override bool Equals(object obj)
{
if (obj == null || !(obj is GpRect))
return false;
return Equals((GpRect)obj);
}
public bool Equals(GpRect rect)
{
return X == rect.X &&
Y == rect.Y &&
Width == rect.Width &&
Height == rect.Height;
}
public bool Contains(int x,
int y)
{
return x >= X && x < X + Width &&
y >= Y && y < Y + Height;
}
public bool Contains(GpPoint pt)
{
return Contains(pt.X, pt.Y);
}
public bool Contains(GpRect rect)
{
return (X <= rect.X) && (rect.GetRight() <= GetRight()) &&
(Y <= rect.Y) && (rect.GetBottom() <= GetBottom());
}
public void Inflate(int dx,
int dy)
{
X -= dx;
Y -= dy;
Width += 2 * dx;
Height += 2 * dy;
}
public void Inflate(GpPoint point)
{
Inflate(point.X, point.Y);
}
public bool Intersect(GpRect rect)
{
return Intersect(out this, this, rect);
}
static public bool Intersect(out GpRect c,
GpRect a,
GpRect b)
{
int right = Math.Min(a.GetRight(), b.GetRight());
int bottom = Math.Min(a.GetBottom(), b.GetBottom());
int left = Math.Max(a.GetLeft(), b.GetLeft());
int top = Math.Max(a.GetTop(), b.GetTop());
c.X = left;
c.Y = top;
c.Width = right - left;
c.Height = bottom - top;
return !c.IsEmptyArea();
}
public bool IntersectsWith(GpRect rect)
{
return (GetLeft() < rect.GetRight() &&
GetTop() < rect.GetBottom() &&
GetRight() > rect.GetLeft() &&
GetBottom() > rect.GetTop());
}
static public bool Union(out GpRect c,
GpRect a,
GpRect b)
{
int right = Math.Max(a.GetRight(), b.GetRight());
int bottom = Math.Max(a.GetBottom(), b.GetBottom());
int left = Math.Min(a.GetLeft(), b.GetLeft());
int top = Math.Min(a.GetTop(), b.GetTop());
c.X = left;
c.Y = top;
c.Width = right - left;
c.Height = bottom - top;
return !c.IsEmptyArea();
}
public void Offset(GpPoint point)
{
Offset(point.X, point.Y);
}
public void Offset(int dx,
int dy)
{
X += dx;
Y += dy;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public int X;
public int Y;
public int Width;
public int Height;
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using GraphQL.Introspection;
using GraphQL.Reflection;
using GraphQL.Resolvers;
using GraphQL.Types;
using GraphQLParser;
using GraphQLParser.AST;
using OperationType = GraphQLParser.AST.OperationType;
namespace GraphQL.Utilities
{
/// <summary>
/// Builds schema from string.
/// </summary>
public class SchemaBuilder
{
protected readonly Dictionary<string, IGraphType> _types = new Dictionary<string, IGraphType>();
private GraphQLSchemaDefinition? _schemaDef;
/// <summary>
/// This <see cref="IServiceProvider"/> is used to create required objects during building schema.
/// <br/><br/>
/// By default equals to <see cref="DefaultServiceProvider"/>.
/// </summary>
public IServiceProvider ServiceProvider { get; set; } = new DefaultServiceProvider();
/// <summary>
/// Specifies whether to ignore comments when parsing GraphQL document.
/// By default, all comments are ignored
/// </summary>
public bool IgnoreComments { get; set; } = true;
/// <summary>
/// Allows to successfully build the schema even if types are found that are not registered int <see cref="Types"/>.
/// <br/>
/// By default <see langword="true"/>.
/// </summary>
public bool AllowUnknownTypes { get; set; } = true;
/// <summary>
/// Allows to successfully build the schema even if fields are found that have no resolvers.
/// <br/>
/// By default <see langword="true"/>.
/// </summary>
public bool AllowUnknownFields { get; set; } = true;
/// <inheritdoc cref="TypeSettings" />
public TypeSettings Types { get; } = new TypeSettings();
/// <summary>
/// Builds schema from string.
/// </summary>
/// <param name="typeDefinitions">A textual description of the schema in SDL (Schema Definition Language) format.</param>
/// <returns>Created schema.</returns>
public virtual Schema Build(string typeDefinitions)
{
var document = Parser.Parse(typeDefinitions, new ParserOptions { Ignore = IgnoreComments ? IgnoreOptions.IgnoreComments : IgnoreOptions.None });
Validate(document);
return BuildSchemaFrom(document);
}
protected virtual void Validate(GraphQLDocument document)
{
var definitionsByName = document.Definitions.OfType<GraphQLTypeDefinition>().Where(def => !(def is GraphQLTypeExtensionDefinition)).ToLookup(def => def.Name!.Value);
var duplicates = definitionsByName.Where(grouping => grouping.Count() > 1).ToArray();
if (duplicates.Length > 0)
{
throw new ArgumentException(@$"All types within a GraphQL schema must have unique names. No two provided types may have the same name.
Schema contains a redefinition of these types: {string.Join(", ", duplicates.Select(item => item.Key))}", nameof(document));
}
//TODO: checks for parsed SDL may be expanded in the future, see https://github.com/graphql/graphql-spec/issues/653
// Also see Schema.Validate
}
private Schema BuildSchemaFrom(GraphQLDocument document)
{
var schema = new Schema(ServiceProvider);
PreConfigure(schema);
var directives = new List<DirectiveGraphType>();
foreach (var def in document.Definitions!)
{
switch (def.Kind)
{
case ASTNodeKind.SchemaDefinition:
{
_schemaDef = def.As<GraphQLSchemaDefinition>();
schema.SetAstType(_schemaDef);
break;
}
case ASTNodeKind.ObjectTypeDefinition:
{
var type = ToObjectGraphType(def.As<GraphQLObjectTypeDefinition>());
_types[type.Name] = type;
break;
}
case ASTNodeKind.TypeExtensionDefinition:
{
var type = ToObjectGraphType(def.As<GraphQLTypeExtensionDefinition>().Definition!, true);
_types[type.Name] = type;
break;
}
case ASTNodeKind.InterfaceTypeDefinition:
{
var type = ToInterfaceType(def.As<GraphQLInterfaceTypeDefinition>());
_types[type.Name] = type;
break;
}
case ASTNodeKind.EnumTypeDefinition:
{
var type = ToEnumerationType(def.As<GraphQLEnumTypeDefinition>());
_types[type.Name] = type;
break;
}
case ASTNodeKind.UnionTypeDefinition:
{
var type = ToUnionType(def.As<GraphQLUnionTypeDefinition>());
_types[type.Name] = type;
break;
}
case ASTNodeKind.InputObjectTypeDefinition:
{
var type = ToInputObjectType(def.As<GraphQLInputObjectTypeDefinition>());
_types[type.Name] = type;
break;
}
case ASTNodeKind.DirectiveDefinition:
{
var directive = ToDirective(def.As<GraphQLDirectiveDefinition>());
directives.Add(directive);
break;
}
}
}
if (_schemaDef != null)
{
schema.Description = _schemaDef.Comment?.Text.ToString();
foreach (var operationTypeDef in _schemaDef.OperationTypes!)
{
var typeName = (string)operationTypeDef.Type!.Name!.Value;
var type = GetType(typeName) as IObjectGraphType;
switch (operationTypeDef.Operation)
{
case OperationType.Query:
schema.Query = type!;
break;
case OperationType.Mutation:
schema.Mutation = type;
break;
case OperationType.Subscription:
schema.Subscription = type;
break;
default:
throw new ArgumentOutOfRangeException($"Unknown operation type {operationTypeDef.Operation}");
}
}
}
else
{
schema.Query = (GetType("Query") as IObjectGraphType)!;
schema.Mutation = GetType("Mutation") as IObjectGraphType;
schema.Subscription = GetType("Subscription") as IObjectGraphType;
}
foreach (var type in _types)
schema.RegisterType(type.Value);
foreach (var directive in directives)
schema.Directives.Register(directive);
Debug.Assert(schema.Initialized == false);
return schema;
}
protected virtual void PreConfigure(Schema schema)
{
}
protected virtual IGraphType GetType(string name)
{
_types.TryGetValue(name, out IGraphType type);
return type;
}
private bool IsSubscriptionType(ObjectGraphType type)
{
var operationDefinition = _schemaDef?.OperationTypes?.FirstOrDefault(o => o.Operation == OperationType.Subscription);
return operationDefinition == null
? type.Name == "Subscription"
: type.Name == operationDefinition.Type!.Name!.Value;
}
private void AssertKnownType(TypeConfig typeConfig)
{
if (typeConfig.Type == null && !AllowUnknownTypes)
throw new InvalidOperationException($"Unknown type '{typeConfig.Name}'. Verify that you have configured SchemaBuilder correctly.");
}
private void AssertKnownField(FieldConfig fieldConfig, TypeConfig typeConfig)
{
if (fieldConfig.Resolver == null && !AllowUnknownFields)
throw new InvalidOperationException($"Unknown field '{typeConfig.Name}.{fieldConfig.Name}' has no resolver. Verify that you have configured SchemaBuilder correctly.");
}
private void OverrideDeprecationReason(IProvideDeprecationReason element, string? reason)
{
if (reason != null)
element.DeprecationReason = reason;
}
protected virtual IObjectGraphType ToObjectGraphType(GraphQLObjectTypeDefinition astType, bool isExtensionType = false)
{
var name = (string)astType.Name!.Value;
var typeConfig = Types.For(name);
AssertKnownType(typeConfig);
var type = _types.TryGetValue(name, out var t)
? t as ObjectGraphType ?? throw new InvalidOperationException($"Type '{name} should be ObjectGraphType")
: new ObjectGraphType { Name = name };
if (!isExtensionType)
{
type.Description = typeConfig.Description ?? astType.Description?.Value.ToString() ?? astType.Comment?.Text.ToString();
type.IsTypeOf = typeConfig.IsTypeOfFunc;
}
typeConfig.CopyMetadataTo(type);
Func<string, GraphQLFieldDefinition, FieldType> constructFieldType = IsSubscriptionType(type)
? ToSubscriptionFieldType
: ToFieldType;
if (astType.Fields != null)
{
foreach (var f in astType.Fields)
type.AddField(constructFieldType(type.Name, f));
}
if (astType.Interfaces != null)
{
foreach (var i in astType.Interfaces)
type.AddResolvedInterface(new GraphQLTypeReference((string)i.Name!.Value));
}
if (isExtensionType)
{
type.AddExtensionAstType(astType);
}
else
{
type.SetAstType(astType);
OverrideDeprecationReason(type, typeConfig.DeprecationReason);
}
return type;
}
private void InitializeField(FieldConfig config, Type? parentType)
{
config.ResolverAccessor ??= parentType.ToAccessor(config.Name, ResolverType.Resolver);
if (config.ResolverAccessor != null)
{
config.Resolver = new AccessorFieldResolver(config.ResolverAccessor, ServiceProvider);
var attrs = config.ResolverAccessor.GetAttributes<GraphQLAttribute>();
if (attrs != null)
{
foreach (var a in attrs)
a.Modify(config);
}
}
}
private void InitializeSubscriptionField(FieldConfig config, Type? parentType)
{
config.ResolverAccessor ??= parentType.ToAccessor(config.Name, ResolverType.Resolver);
config.SubscriberAccessor ??= parentType.ToAccessor(config.Name, ResolverType.Subscriber);
if (config.ResolverAccessor != null && config.SubscriberAccessor != null)
{
config.Resolver = new AccessorFieldResolver(config.ResolverAccessor, ServiceProvider);
var attrs = config.ResolverAccessor.GetAttributes<GraphQLAttribute>();
if (attrs != null)
{
foreach (var a in attrs)
a.Modify(config);
}
if (config.SubscriberAccessor.MethodInfo.ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
{
config.AsyncSubscriber = new AsyncEventStreamResolver(config.SubscriberAccessor, ServiceProvider);
}
else
{
config.Subscriber = new EventStreamResolver(config.SubscriberAccessor, ServiceProvider);
}
}
}
protected virtual FieldType ToFieldType(string parentTypeName, GraphQLFieldDefinition fieldDef)
{
var typeConfig = Types.For(parentTypeName);
AssertKnownType(typeConfig);
var fieldConfig = typeConfig.FieldFor((string)fieldDef.Name!.Value);
InitializeField(fieldConfig, typeConfig.Type);
AssertKnownField(fieldConfig, typeConfig);
var field = new FieldType
{
Name = fieldConfig.Name,
Description = fieldConfig.Description ?? fieldDef.Description?.Value.ToString() ?? fieldDef.Comment?.Text.ToString(),
ResolvedType = ToGraphType(fieldDef.Type!),
Resolver = fieldConfig.Resolver
};
fieldConfig.CopyMetadataTo(field);
field.Arguments = ToQueryArguments(fieldConfig, fieldDef.Arguments);
field.SetAstType(fieldDef);
OverrideDeprecationReason(field, fieldConfig.DeprecationReason);
return field;
}
protected virtual FieldType ToSubscriptionFieldType(string parentTypeName, GraphQLFieldDefinition fieldDef)
{
var typeConfig = Types.For(parentTypeName);
AssertKnownType(typeConfig);
var fieldConfig = typeConfig.FieldFor((string)fieldDef.Name!.Value);
InitializeSubscriptionField(fieldConfig, typeConfig.Type);
AssertKnownField(fieldConfig, typeConfig);
var field = new EventStreamFieldType
{
Name = fieldConfig.Name,
Description = fieldConfig.Description ?? fieldDef.Description?.Value.ToString() ?? fieldDef.Comment?.Text.ToString(),
ResolvedType = ToGraphType(fieldDef.Type!),
Resolver = fieldConfig.Resolver,
Subscriber = fieldConfig.Subscriber,
AsyncSubscriber = fieldConfig.AsyncSubscriber,
};
fieldConfig.CopyMetadataTo(field);
field.Arguments = ToQueryArguments(fieldConfig, fieldDef.Arguments);
field.SetAstType(fieldDef);
OverrideDeprecationReason(field, fieldConfig.DeprecationReason);
return field;
}
protected virtual FieldType ToFieldType(string parentTypeName, GraphQLInputValueDefinition inputDef)
{
var typeConfig = Types.For(parentTypeName);
AssertKnownType(typeConfig);
var fieldConfig = typeConfig.FieldFor((string)inputDef.Name!.Value);
InitializeField(fieldConfig, typeConfig.Type);
AssertKnownField(fieldConfig, typeConfig);
var field = new FieldType
{
Name = fieldConfig.Name,
Description = fieldConfig.Description ?? inputDef.Description?.Value.ToString() ?? inputDef.Comment?.Text.ToString(),
ResolvedType = ToGraphType(inputDef.Type!),
DefaultValue = fieldConfig.DefaultValue ?? inputDef.DefaultValue
}.SetAstType(inputDef);
OverrideDeprecationReason(field, fieldConfig.DeprecationReason);
return field;
}
protected virtual InterfaceGraphType ToInterfaceType(GraphQLInterfaceTypeDefinition interfaceDef)
{
var name = (string)interfaceDef.Name!.Value;
var typeConfig = Types.For(name);
AssertKnownType(typeConfig);
var type = new InterfaceGraphType
{
Name = name,
Description = typeConfig.Description ?? interfaceDef.Description?.Value.ToString() ?? interfaceDef.Comment?.Text.ToString(),
ResolveType = typeConfig.ResolveType,
}.SetAstType(interfaceDef);
OverrideDeprecationReason(type, typeConfig.DeprecationReason);
typeConfig.CopyMetadataTo(type);
if (interfaceDef.Fields != null)
{
foreach (var f in interfaceDef.Fields)
type.AddField(ToFieldType(type.Name, f));
}
return type;
}
protected virtual UnionGraphType ToUnionType(GraphQLUnionTypeDefinition unionDef)
{
var name = (string)unionDef.Name!.Value;
var typeConfig = Types.For(name);
AssertKnownType(typeConfig);
var type = new UnionGraphType
{
Name = name,
Description = typeConfig.Description ?? unionDef.Description?.Value.ToString() ?? unionDef.Comment?.Text.ToString(),
ResolveType = typeConfig.ResolveType,
}.SetAstType(unionDef);
OverrideDeprecationReason(type, typeConfig.DeprecationReason);
typeConfig.CopyMetadataTo(type);
if (unionDef.Types?.Count > 0) // just in case
{
foreach (var x in unionDef.Types)
{
string n = (string)x.Name!.Value;
type.AddPossibleType(((GetType(n) ?? new GraphQLTypeReference(n)) as IObjectGraphType)!);
}
}
return type;
}
protected virtual InputObjectGraphType ToInputObjectType(GraphQLInputObjectTypeDefinition inputDef)
{
var name = (string)inputDef.Name!.Value;
var typeConfig = Types.For(name);
AssertKnownType(typeConfig);
var type = new InputObjectGraphType
{
Name = name,
Description = typeConfig.Description ?? inputDef.Description?.Value.ToString() ?? inputDef.Comment?.Text.ToString(),
}.SetAstType(inputDef);
OverrideDeprecationReason(type, typeConfig.DeprecationReason);
typeConfig.CopyMetadataTo(type);
if (inputDef.Fields != null)
{
foreach (var f in inputDef.Fields)
type.AddField(ToFieldType(type.Name, f));
}
return type;
}
protected virtual EnumerationGraphType ToEnumerationType(GraphQLEnumTypeDefinition enumDef)
{
var name = (string)enumDef.Name!.Value;
var typeConfig = Types.For(name);
AssertKnownType(typeConfig);
var type = new EnumerationGraphType
{
Name = name,
Description = typeConfig.Description ?? enumDef.Description?.Value.ToString() ?? enumDef.Comment?.Text.ToString(),
}.SetAstType(enumDef);
OverrideDeprecationReason(type, typeConfig.DeprecationReason);
if (enumDef.Values?.Count > 0) // just in case
{
foreach (var value in enumDef.Values)
type.AddValue(ToEnumValue(value, typeConfig.Type!));
}
return type;
}
protected virtual DirectiveGraphType ToDirective(GraphQLDirectiveDefinition directiveDef)
{
var result = new DirectiveGraphType((string)directiveDef.Name!.Value)
{
Description = directiveDef.Description?.Value.ToString() ?? directiveDef.Comment?.Text.ToString(),
Repeatable = directiveDef.Repeatable,
Arguments = ToQueryArguments(directiveDef.Arguments)
};
if (directiveDef.Locations?.Count > 0) // just in case
{
foreach (var location in directiveDef.Locations)
{
if (__DirectiveLocation.Instance.Values.FindByName(location.Value)?.Value is DirectiveLocation l)
result.Locations.Add(l);
else
throw new InvalidOperationException($"Directive '{result.Name}' has an unknown directive location '{location.Value}'.");
}
}
return result;
}
private EnumValueDefinition ToEnumValue(GraphQLEnumValueDefinition valDef, Type enumType)
{
var name = (string)valDef.Name!.Value;
return new EnumValueDefinition
{
Value = enumType == null ? name : Enum.Parse(enumType, name, true),
Name = name,
Description = valDef.Description?.Value.ToString() ?? valDef.Comment?.Text.ToString()
// TODO: SchemaFirst configuration (TypeConfig/FieldConfig) does not allow to specify DeprecationReason for enum values
//DeprecationReason = ???
}.SetAstType(valDef);
}
protected virtual QueryArgument ToArgument(ArgumentConfig argumentConfig, GraphQLInputValueDefinition inputDef)
{
var argument = new QueryArgument(ToGraphType(inputDef.Type!))
{
Name = argumentConfig.Name,
DefaultValue = argumentConfig.DefaultValue ?? inputDef.DefaultValue,
Description = argumentConfig.Description ?? inputDef.Description?.Value.ToString() ?? inputDef.Comment?.Text.ToString()
}.SetAstType(inputDef);
argumentConfig.CopyMetadataTo(argument);
return argument;
}
private IGraphType ToGraphType(GraphQLType astType)
{
switch (astType.Kind)
{
case ASTNodeKind.NonNullType:
{
var type = ToGraphType(((GraphQLNonNullType)astType).Type!);
return new NonNullGraphType(type);
}
case ASTNodeKind.ListType:
{
var type = ToGraphType(((GraphQLListType)astType).Type!);
return new ListGraphType(type);
}
case ASTNodeKind.NamedType:
{
var namedType = (GraphQLNamedType)astType;
var name = (string)namedType.Name!.Value;
var type = GetType(name);
return type ?? new GraphQLTypeReference(name);
}
default:
throw new ArgumentOutOfRangeException($"Unknown GraphQL type {astType.Kind}");
}
}
//TODO: add support for directive arguments
private QueryArguments ToQueryArguments(List<GraphQLInputValueDefinition>? arguments)
{
return arguments == null ? new QueryArguments() : new QueryArguments(arguments.Select(a => ToArgument(new ArgumentConfig((string)a.Name!.Value), a)));
}
private QueryArguments ToQueryArguments(FieldConfig fieldConfig, List<GraphQLInputValueDefinition>? arguments)
{
return arguments == null ? new QueryArguments() : new QueryArguments(arguments.Select(a => ToArgument(fieldConfig.ArgumentFor((string)a.Name!.Value), a)));
}
}
internal static class Extensions
{
public static TNode As<TNode>(this ASTNode node) where TNode : ASTNode
{
return node as TNode ?? throw new InvalidOperationException($"Node should be of type '{typeof(TNode).Name}' but it is of type '{node?.GetType().Name}'.");
}
public static object? ToValue(this GraphQLValue source)
{
if (source == null)
{
return null;
}
switch (source.Kind)
{
case ASTNodeKind.NullValue:
{
return null;
}
case ASTNodeKind.StringValue:
{
var str = source as GraphQLScalarValue;
Debug.Assert(str != null, nameof(str) + " != null");
return (string)str!.Value;
}
case ASTNodeKind.IntValue:
{
var str = source as GraphQLScalarValue;
Debug.Assert(str != null, nameof(str) + " != null");
if (Int.TryParse(str!.Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int intResult))
{
return intResult;
}
// If the value doesn't fit in an integer, revert to using long...
if (Long.TryParse(str.Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out long longResult))
{
return longResult;
}
// If the value doesn't fit in an long, revert to using decimal...
if (Decimal.TryParse(str.Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out decimal decimalResult))
{
return decimalResult;
}
// If the value doesn't fit in an decimal, revert to using BigInteger...
if (BigInt.TryParse(str.Value, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var bigIntegerResult))
{
return bigIntegerResult;
}
throw new InvalidOperationException($"Invalid number {str.Value}");
}
case ASTNodeKind.FloatValue:
{
var str = source as GraphQLScalarValue;
Debug.Assert(str != null, nameof(str) + " != null");
// the idea is to see if there is a loss of accuracy of value
// for example, 12.1 or 12.11 is double but 12.10 is decimal
if (!Double.TryParse(
str!.Value,
NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
CultureInfo.InvariantCulture,
out double dbl))
{
dbl = str.Value.Span[0] == '-' ? double.NegativeInfinity : double.PositiveInfinity;
}
//it is possible for a FloatValue to overflow a decimal; however, with a double, it just returns Infinity or -Infinity
if (Decimal.TryParse(
str.Value,
NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
CultureInfo.InvariantCulture,
out decimal dec))
{
// Cast the decimal to our struct to avoid the decimal.GetBits allocations.
var decBits = System.Runtime.CompilerServices.Unsafe.As<decimal, DecimalData>(ref dec);
decimal temp = new decimal(dbl);
var dblAsDecBits = System.Runtime.CompilerServices.Unsafe.As<decimal, DecimalData>(ref temp);
if (!decBits.Equals(dblAsDecBits))
return dec;
}
return dbl;
}
case ASTNodeKind.BooleanValue:
{
var str = source as GraphQLScalarValue;
Debug.Assert(str != null, nameof(str) + " != null");
return (str!.Value.Length == 4).Boxed(); /*true.Length=4*/
}
case ASTNodeKind.EnumValue:
{
var str = source as GraphQLScalarValue;
Debug.Assert(str != null, nameof(str) + " != null");
return (string)str!.Value;
}
case ASTNodeKind.ObjectValue:
{
var obj = source as GraphQLObjectValue;
var values = new Dictionary<string, object?>();
Debug.Assert(obj != null, nameof(obj) + " != null");
if (obj!.Fields != null)
{
foreach (var f in obj.Fields)
values[(string)f.Name!.Value] = ToValue(f.Value!);
}
return values;
}
case ASTNodeKind.ListValue:
{
var list = source as GraphQLListValue;
Debug.Assert(list != null, nameof(list) + " != null");
if (list!.Values == null)
return Array.Empty<object>();
object?[] values = list.Values.Select(ToValue).ToArray();
return values;
}
default:
throw new InvalidOperationException($"Unsupported value type {source.Kind}");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Box.V2.Auth;
using Box.V2.Config;
using Box.V2.Converter;
using Box.V2.Extensions;
using Box.V2.Models;
using Box.V2.Models.Request;
using Box.V2.Services;
using Box.V2.Utility;
namespace Box.V2.Managers
{
/// <summary>
/// The class managing the Box API's Retention Policies endpoint.
/// Retention Management is a feature of the Box Governance package, which can be added on to any Business Plus or Enterprise account.
/// To use this feature, you must have the manage retention policies scope enabled for your API key via your application management console.
/// </summary>
public class BoxRetentionPoliciesManager : BoxResourceManager, IBoxRetentionPoliciesManager
{
public BoxRetentionPoliciesManager(IBoxConfig config, IBoxService service, IBoxConverter converter, IAuthRepository auth, string asUser = null, bool? suppressNotifications = null)
: base(config, service, converter, auth, asUser, suppressNotifications) { }
/// <summary>
/// Used to create a new retention policy.
/// </summary>
/// <param name="retentionPolicyRequest">BoxRetentionPolicyRequest object.</param>
/// <returns>A new retention policy object will be returned upon success.</returns>
public async Task<BoxRetentionPolicy> CreateRetentionPolicyAsync(BoxRetentionPolicyRequest retentionPolicyRequest)
{
BoxRequest request = new BoxRequest(_config.RetentionPoliciesEndpointUri)
.Method(RequestMethod.Post)
.Payload(_converter.Serialize(retentionPolicyRequest));
IBoxResponse<BoxRetentionPolicy> response = await ToResponseAsync<BoxRetentionPolicy>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Used to retrieve information about a retention policy.
/// </summary>
/// <param name="id">ID of the retention policy.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <returns>The specified retention policy will be returned upon success.</returns>
public async Task<BoxRetentionPolicy> GetRetentionPolicyAsync(string id, IEnumerable<string> fields = null)
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.RetentionPoliciesEndpointUri, id)
.Param(ParamFields, fields);
IBoxResponse<BoxRetentionPolicy> response = await ToResponseAsync<BoxRetentionPolicy>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Used to update a retention policy.
/// </summary>
/// <param name="id">ID of the retention policy.</param>
/// <param name="retentionPolicyRequest">BoxRetentionPolicyRequest object.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <returns>An updated retention policy object will be returned upon success.</returns>
public async Task<BoxRetentionPolicy> UpdateRetentionPolicyAsync(string id, BoxRetentionPolicyRequest retentionPolicyRequest, IEnumerable<string> fields = null)
{
id.ThrowIfNullOrWhiteSpace("id");
BoxRequest request = new BoxRequest(_config.RetentionPoliciesEndpointUri, id)
.Method(RequestMethod.Put)
.Param(ParamFields, fields)
.Payload(_converter.Serialize<BoxRetentionPolicyRequest>(retentionPolicyRequest));
IBoxResponse<BoxRetentionPolicy> response = await ToResponseAsync<BoxRetentionPolicy>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Retrieves all of the retention policies for the given enterprise.
/// </summary>
/// <param name="policyName">A name to filter the retention policies by. A trailing partial match search is performed.</param>
/// <param name="policyType">A policy type to filter the retention policies by.</param>
/// <param name="createdByUserId">A user id to filter the retention policies by.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <param name="limit">Limit result size to this number. Defaults to 100, maximum is 1,000.</param>
/// <param name="marker">Take from "next_marker" column of a prior call to get the next page.</param>
/// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
/// <returns>Returns the list of all retention policies for the enterprise.</returns>
public async Task<BoxCollectionMarkerBased<BoxRetentionPolicy>> GetRetentionPoliciesAsync(string policyName = null, string policyType = null, string createdByUserId = null, IEnumerable<string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false)
{
BoxRequest request = new BoxRequest(_config.RetentionPoliciesEndpointUri)
.Param("policy_name", policyName)
.Param("policy_type", policyType)
.Param("created_by_user_id", createdByUserId)
.Param(ParamFields, fields)
.Param("limit", limit.ToString())
.Param("marker", marker);
if (autoPaginate)
{
return await AutoPaginateMarker<BoxRetentionPolicy>(request, limit).ConfigureAwait(false);
}
else
{
IBoxResponse<BoxCollectionMarkerBased<BoxRetentionPolicy>> response = await ToResponseAsync<BoxCollectionMarkerBased<BoxRetentionPolicy>>(request).ConfigureAwait(false);
return response.ResponseObject;
}
}
/// <summary>
/// Returns a list of all retention policy assignments associated with a specified retention policy.
/// </summary>
/// <param name="retentionPolicyId">ID of the retention policy.</param>
/// <param name="type">The type of the retention policy assignment to retrieve. Can either be folder or enterprise.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <param name="limit">Limit result size to this number. Defaults to 100, maximum is 1,000.</param>
/// <param name="marker">Take from "next_marker" column of a prior call to get the next page.</param>
/// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
/// <returns>Returns a list of the retention policy assignments associated with the specified retention policy.</returns>
public async Task<BoxCollectionMarkerBased<BoxRetentionPolicyAssignment>> GetRetentionPolicyAssignmentsAsync(string retentionPolicyId, string type = null, IEnumerable<string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false)
{
BoxRequest request = new BoxRequest(_config.RetentionPoliciesEndpointUri, string.Format(Constants.RetentionPolicyAssignmentsEndpointString, retentionPolicyId))
.Param("type", type)
.Param(ParamFields, fields)
.Param("limit", limit.ToString())
.Param("marker", marker);
if (autoPaginate)
{
return await AutoPaginateMarker<BoxRetentionPolicyAssignment>(request, limit).ConfigureAwait(false);
}
else
{
IBoxResponse<BoxCollectionMarkerBased<BoxRetentionPolicyAssignment>> response = await ToResponseAsync<BoxCollectionMarkerBased<BoxRetentionPolicyAssignment>>(request).ConfigureAwait(false);
return response.ResponseObject;
}
}
/// <summary>
/// Creates a retention policy assignment that associates a retention policy with either a folder or an enterprise
/// </summary>
/// <param name="policyAssignmentRequest"></param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <returns>A new retention policy assignment will be returned upon success.</returns>
public async Task<BoxRetentionPolicyAssignment> CreateRetentionPolicyAssignmentAsync(BoxRetentionPolicyAssignmentRequest policyAssignmentRequest, IEnumerable<string> fields = null)
{
BoxRequest request = new BoxRequest(_config.RetentionPolicyAssignmentsUri)
.Method(RequestMethod.Post)
.Param(ParamFields, fields)
.Payload(_converter.Serialize<BoxRetentionPolicyAssignmentRequest>(policyAssignmentRequest));
IBoxResponse<BoxRetentionPolicyAssignment> response = await ToResponseAsync<BoxRetentionPolicyAssignment>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Used to retrieve information about a retention policy assignment.
/// </summary>
/// <param name="retentionPolicyAssignmentId">ID of the retention policy assignment.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <returns>The specified retention policy assignment will be returned upon success.</returns>
public async Task<BoxRetentionPolicyAssignment> GetRetentionPolicyAssignmentAsync(string retentionPolicyAssignmentId, IEnumerable<string> fields = null)
{
BoxRequest request = new BoxRequest(_config.RetentionPolicyAssignmentsUri, retentionPolicyAssignmentId)
.Param(ParamFields, fields);
IBoxResponse<BoxRetentionPolicyAssignment> response = await ToResponseAsync<BoxRetentionPolicyAssignment>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Retrieves all file version retentions for the given enterprise.
/// </summary>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <param name="limit">Limit result size to this number. Defaults to 100, maximum is 1,000.</param>
/// <param name="marker">Take from "next_marker" column of a prior call to get the next page.</param>
/// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
/// <param name="fileId">Filters results by files with this ID.</param>
/// <param name="fileVersionId">Filters results by file versions with this ID.</param>
/// <param name="policyId">Filters results by the retention policy with this ID.</param>
/// <param name="dispositionBefore">Filters results by files that will have their disposition come into effect before this date.</param>
/// <param name="dispositionAfter">Filters results by files that will have their disposition come into effect after this date.</param>
/// <param name="dispositionAction">Filters results by the retention policy with this disposition action.</param>
/// <returns>The specified file version retention will be returned upon success.</returns>
[Obsolete("This method will be deprecated in the future. Please use GetFilesUnderRetentionForAssignmentAsync() and GetFileVersionsUnderRetentionForAssignmentAsync() instead.")]
public async Task<BoxCollectionMarkerBased<BoxFileVersionRetention>> GetFileVersionRetentionsAsync(IEnumerable<string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false, string fileId = null, string fileVersionId = null, string policyId = null, DateTimeOffset? dispositionBefore = null, DateTimeOffset? dispositionAfter = null, DispositionAction? dispositionAction = null)
{
BoxRequest request = new BoxRequest(_config.FileVersionRetentionsUri)
.Param(ParamFields, fields)
.Param("limit", limit.ToString())
.Param("marker", marker)
.Param("file_id", fileId)
.Param("file_version_id", fileVersionId)
.Param("policy_id", policyId)
.Param("disposition_before", Helper.ConvertToRFCString(dispositionBefore))
.Param("disposition_after", Helper.ConvertToRFCString(dispositionAfter))
.Param("disposition_action", dispositionAction.ToString());
if (autoPaginate)
{
return await AutoPaginateMarker<BoxFileVersionRetention>(request, limit).ConfigureAwait(false);
}
else
{
var response = await ToResponseAsync<BoxCollectionMarkerBased<BoxFileVersionRetention>>(request).ConfigureAwait(false);
return response.ResponseObject;
}
}
/// <summary>
/// Used to retrieve information about a file version retention.
/// </summary>
/// <param name="fileVersionRetentionId">ID of the file version retention policy.</param>
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <returns>Returns the list of all file version retentions for the enterprise.</returns>
public async Task<BoxFileVersionRetention> GetFileVersionRetentionAsync(string fileVersionRetentionId, IEnumerable<string> fields = null)
{
BoxRequest request = new BoxRequest(_config.FileVersionRetentionsUri, fileVersionRetentionId)
.Param(ParamFields, fields);
var response = await ToResponseAsync<BoxFileVersionRetention>(request).ConfigureAwait(false);
return response.ResponseObject;
}
/// <summary>
/// Used to retrieve files under retention by each assignment
/// To use this feature, you must have the manage retention policies scope enabled
/// for your API key via your application management console.
/// </summary>
/// <param name="retentionPolicyAssignmentId">The Box ID of the policy assignment object to fetch
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <param name="limit">Limit result size to this number. Defaults to 100, maximum is 1,000.</param>
/// <param name="marker">Take from "next_marker" column of a prior call to get the next page.</param>
/// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
/// <returns>Returns the list of all files under retentions for the assignment.</returns>
public async Task<BoxCollectionMarkerBased<BoxFile>> GetFilesUnderRetentionForAssignmentAsync(string retentionPolicyAssignmentId, IEnumerable<string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false)
{
BoxRequest request = new BoxRequest(_config.RetentionPolicyAssignmentsUri, string.Format(Constants.FilesUnderRetentionEndpointString, retentionPolicyAssignmentId))
.Param("retention_policy_assignment_id", retentionPolicyAssignmentId)
.Param(ParamFields, fields)
.Param("limit", limit.ToString())
.Param("marker", marker);
if (autoPaginate)
{
return await AutoPaginateMarker<BoxFile>(request, limit).ConfigureAwait(false);
}
else
{
var response = await ToResponseAsync<BoxCollectionMarkerBased<BoxFile>>(request).ConfigureAwait(false);
return response.ResponseObject;
}
}
/// <summary>
/// Used to retrieve file versions under retention by each assignment
/// To use this feature, you must have the manage retention policies scope enabled
/// for your API key via your application management console.
/// </summary>
/// <param name="retentionPolicyAssignmentId">The Box ID of the policy assignment object to fetch
/// <param name="fields">Attribute(s) to include in the response.</param>
/// <param name="limit">Limit result size to this number. Defaults to 100, maximum is 1,000.</param>
/// <param name="marker">Take from "next_marker" column of a prior call to get the next page.</param>
/// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
/// <returns>Returns the list of all file versions under retentions for the assignment.</returns>
public async Task<BoxCollectionMarkerBased<BoxFileVersion>> GetFileVersionsUnderRetentionForAssignmentAsync(string retentionPolicyAssignmentId, IEnumerable<string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false)
{
BoxRequest request = new BoxRequest(_config.RetentionPolicyAssignmentsUri, string.Format(Constants.FileVersionsUnderRetentionEndpointString, retentionPolicyAssignmentId))
.Param("retention_policy_assignment_id", retentionPolicyAssignmentId)
.Param(ParamFields, fields)
.Param("limit", limit.ToString())
.Param("marker", marker);
if (autoPaginate)
{
return await AutoPaginateMarker<BoxFileVersion>(request, limit).ConfigureAwait(false);
}
else
{
var response = await ToResponseAsync<BoxCollectionMarkerBased<BoxFileVersion>>(request).ConfigureAwait(false);
return response.ResponseObject;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using L10NSharp;
using SIL.Keyboarding;
using SIL.PlatformUtilities;
using SIL.Windows.Forms.Keyboarding;
namespace SIL.Windows.Forms.WritingSystems
{
public partial class WSKeyboardControl : UserControl
{
private class KeyboardDefinitionAdapter
{
private IKeyboardDefinition _descriptor;
public KeyboardDefinitionAdapter(IKeyboardDefinition descriptor)
{
_descriptor = descriptor;
}
public IKeyboardDefinition KeyboardDefinition
{
get { return _descriptor; }
}
public override string ToString()
{
return _descriptor.LocalizedName;
}
}
private WritingSystemSetupModel _model;
private string _defaultFontName;
private float _defaultFontSize;
public WSKeyboardControl()
{
InitializeComponent();
if (KeyboardController.IsInitialized)
KeyboardController.RegisterControl(_testArea);
_defaultFontSize = _testArea.Font.SizeInPoints;
_defaultFontName = _testArea.Font.Name;
_possibleKeyboardsList.ShowItemToolTips = true;
_keymanConfigurationLink.Visible &= KeyboardController.HasSecondaryKeyboardSetupApplication;
if (Platform.IsWindows)
return;
// Keyman is not supported, setup link should not say "Windows".
_keyboardSettingsLink.Text =
L10NSharp.LocalizationManager.GetString("WSKeyboardControl.SetupKeyboards",
"Set up keyboards");
// The sequence of Events in Mono dictate using GotFocus instead of Enter as the point
// when we want to assign keyboard and font to this textbox. (For some reason, using
// Enter works fine for the WSFontControl._testArea textbox control.)
this._testArea.Enter -= new System.EventHandler(this._testArea_Enter);
this._testArea.GotFocus += new System.EventHandler(this._testArea_Enter);
}
private bool _hookedToForm;
/// <summary>
/// This seems to be the best available hook to connect this control to the form's Activated event.
/// The control can't be visible until it is on a form!
/// It is tempting to unhook it when it is no longer visible, but unfortunately OnVisibleChanged
/// apparently doesn't work like that. According to http://memprofiler.com/articles/thecontrolvisiblechangedevent.aspx,
/// it is fired when visibility is gained because parent visibility changed, but not when visibility
/// is LOST because parent visibility changed.
/// </summary>
/// <param name="e"></param>
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
if (_hookedToForm || !(TopLevelControl is Form))
return;
_hookedToForm = true;
((Form) TopLevelControl).Activated += WSKeyboardControl_Activated;
}
// When the top-level form we are part of is activated, update our keyboard list,
// in case the user changed things using the control panel.
private void WSKeyboardControl_Activated(object sender, EventArgs e)
{
Keyboard.Controller.UpdateAvailableKeyboards(); // Enhance JohnT: would it be cleaner to have a Model method to do this?
PopulateKeyboardList();
UpdateFromModel(); // to restore selection.
}
public void BindToModel(WritingSystemSetupModel model)
{
if (_model != null)
{
_model.SelectionChanged -= ModelSelectionChanged;
_model.CurrentItemUpdated -= ModelCurrentItemUpdated;
}
_model = model;
Enabled = false;
if (_model != null)
{
_model.SelectionChanged += ModelSelectionChanged;
_model.CurrentItemUpdated += ModelCurrentItemUpdated;
PopulateKeyboardList();
UpdateFromModel();
}
Disposed += OnDisposed;
}
private void OnDisposed(object sender, EventArgs e)
{
if (_model != null)
_model.SelectionChanged -= ModelSelectionChanged;
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
// single column occupies whole list, leaving room for vertical scroll so we don't get a spurious
// horizontal one.
_keyboards.Width = _possibleKeyboardsList.ClientSize.Width - SystemInformation.VerticalScrollBarWidth;
}
private Color _unavailableColor = Color.FromKnownColor(KnownColor.DimGray);
private Color _labelColor = Color.LightCyan;
private ListViewItem MakeLabelItem(string text)
{
var label = new ListViewItem(text);
label.BackColor = _labelColor;
label.Font = new Font(_possibleKeyboardsList.Font, FontStyle.Bold);
return label;
}
private bool IsItemLabel(ListViewItem item)
{
return item.BackColor == _labelColor;
}
private void PopulateKeyboardList()
{
if (_model == null || !_model.HasCurrentSelection)
{
_possibleKeyboardsList.Items.Clear();
return;
}
_possibleKeyboardsList.BeginUpdate();
Rectangle originalBounds = _possibleKeyboardsList.Bounds;
_possibleKeyboardsList.Items.Clear();
_possibleKeyboardsList.Items.Add(MakeLabelItem(
LocalizationManager.GetString("WSKeyboardControl.KeyboardsPreviouslyUsed", "Previously used keyboards")));
var unavailableFont = new Font(_possibleKeyboardsList.Font, FontStyle.Italic);
foreach (var keyboard in _model.KnownKeyboards)
{
var adapter = new KeyboardDefinitionAdapter(keyboard);
var item = new ListViewItem(adapter.ToString());
item.Tag = adapter;
if (!keyboard.IsAvailable)
{
item.Font = unavailableFont;
item.ForeColor = _unavailableColor;
}
item.ToolTipText = adapter.ToString();
_possibleKeyboardsList.Items.Add(item);
if (keyboard == _model.CurrentKeyboard)
item.Selected = true;
}
_possibleKeyboardsList.Items.Add(MakeLabelItem(
LocalizationManager.GetString("WSKeyboardControl.KeyboardsAvailable", "Available keyboards")));
foreach (var keyboard in _model.OtherAvailableKeyboards)
{
var adapter = new KeyboardDefinitionAdapter(keyboard);
var item = new ListViewItem(adapter.ToString());
item.Tag = adapter;
item.ToolTipText = adapter.ToString();
_possibleKeyboardsList.Items.Add(item);
}
_possibleKeyboardsList.Bounds = originalBounds;
_possibleKeyboardsList.EndUpdate();
}
private void ModelCurrentItemUpdated(object sender, EventArgs e)
{
UpdateFromModel();
}
private void ModelSelectionChanged(object sender, EventArgs e)
{
PopulateKeyboardList(); // different writing system may have different current ones.
UpdateFromModel();
}
private string _selectKeyboardPattern;
private void UpdateFromModel()
{
if (_model == null || !_model.HasCurrentSelection)
{
Enabled = false;
_selectKeyboardLabel.Visible = false;
return;
}
Enabled = true;
_selectKeyboardLabel.Visible = true;
if (_selectKeyboardPattern == null)
_selectKeyboardPattern = _selectKeyboardLabel.Text;
_selectKeyboardLabel.Text = string.Format(_selectKeyboardPattern, _model.CurrentDefinition.ListLabel);
KeyboardDefinitionAdapter currentKeyboardDefinition = null;
if (_possibleKeyboardsList.SelectedItems.Count > 0)
currentKeyboardDefinition = _possibleKeyboardsList.SelectedItems[0].Tag as KeyboardDefinitionAdapter;
if (_model.CurrentKeyboard != null &&
(currentKeyboardDefinition == null || _model.CurrentKeyboard != currentKeyboardDefinition.KeyboardDefinition))
{
foreach (ListViewItem item in _possibleKeyboardsList.Items)
{
var keyboard = item.Tag as KeyboardDefinitionAdapter;
if (keyboard != null && keyboard.KeyboardDefinition == _model.CurrentKeyboard)
{
//_possibleKeyboardsList.SelectedItems.Clear();
// We're updating the display from the model, so we don't need to run the code that
// updates the model from the display.
_possibleKeyboardsList.SelectedIndexChanged -= _possibleKeyboardsList_SelectedIndexChanged;
item.Selected = true; // single select is true, so should clear any old one.
_possibleKeyboardsList.SelectedIndexChanged += _possibleKeyboardsList_SelectedIndexChanged;
break;
}
}
}
SetTestAreaFont();
}
private void SetTestAreaFont()
{
float fontSize = _model.CurrentDefaultFontSize;
if (fontSize <= 0 || float.IsNaN(fontSize) || float.IsInfinity(fontSize))
{
fontSize = _defaultFontSize;
}
string fontName = _model.CurrentDefaultFontName;
if (string.IsNullOrEmpty(fontName))
{
fontName = _defaultFontName;
}
_testArea.Font = new Font(fontName, fontSize);
_testArea.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No;
}
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
_possibleKeyboardsList.Focus(); // allows the user to use arrows to select, also makes selection more conspicuous
}
private int _previousTime;
private void _possibleKeyboardsList_SelectedIndexChanged(object sender, EventArgs e)
{
if (_possibleKeyboardsList.SelectedItems.Count != 0)
{
var item = _possibleKeyboardsList.SelectedItems[0];
if (IsItemLabel(item) || item.ForeColor == _unavailableColor)
{
item.Selected = false;
UpdateFromModel(); // back to whatever the model has
return;
}
}
if (Environment.TickCount - _previousTime < 1000 && _possibleKeyboardsList.SelectedItems.Count == 0)
{
_previousTime = Environment.TickCount;
}
_previousTime = Environment.TickCount;
if (_model == null)
{
return;
}
if (_possibleKeyboardsList.SelectedItems.Count != 0)
{
var currentKeyboard = (KeyboardDefinitionAdapter) _possibleKeyboardsList.SelectedItems[0].Tag;
if (_model.CurrentKeyboard == null ||
_model.CurrentKeyboard != currentKeyboard.KeyboardDefinition)
{
_model.CurrentKeyboard = currentKeyboard.KeyboardDefinition;
}
}
}
private void _testArea_Enter(object sender, EventArgs e)
{
if (_model == null)
{
return;
}
_model.ActivateCurrentKeyboard();
SetTestAreaFont();
}
private void _testArea_Leave(object sender, EventArgs e)
{
if (_model == null)
{
return;
}
Keyboard.Controller.ActivateDefaultKeyboard();
}
private void _windowsKeyboardSettingsLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string arguments;
string program = KeyboardController.GetKeyboardSetupApplication(out arguments);
if (string.IsNullOrEmpty(program))
{
MessageBox.Show("Cannot open keyboard setup program", "Information");
return;
}
var processInfo = new ProcessStartInfo(program, arguments);
using (Process.Start(processInfo))
{
}
}
private void _keymanConfigurationLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string arguments;
string program = KeyboardController.GetSecondaryKeyboardSetupApplication(out arguments);
if (string.IsNullOrEmpty(program))
{
MessageBox.Show(LocalizationManager.GetString("WSKeyboardControl.KeymanNotInstalled",
"Keyman 5.0 or later is not Installed."));
return;
}
var processInfo = new ProcessStartInfo(program, arguments);
using (Process.Start(processInfo))
{
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using System.Globalization;
namespace Newtonsoft.Json.Utilities
{
internal static class StringUtils
{
public const string CarriageReturnLineFeed = "\r\n";
public const string Empty = "";
public const char CarriageReturn = '\r';
public const char LineFeed = '\n';
public const char Tab = '\t';
//public static string FormatWith(this string format, params object[] args)
//{
// return FormatWith(format, null, args);
//}
public static string FormatWith(this string format, IFormatProvider provider, params object[] args)
{
ValidationUtils.ArgumentNotNull(format, "format");
return string.Format(provider, format, args);
}
/// <summary>
/// Determines whether the string contains white space.
/// </summary>
/// <param name="s">The string to test for white space.</param>
/// <returns>
/// <c>true</c> if the string contains white space; otherwise, <c>false</c>.
/// </returns>
public static bool ContainsWhiteSpace(string s)
{
if (s == null)
throw new ArgumentNullException("s");
for (int i = 0; i < s.Length; i++)
{
if (char.IsWhiteSpace(s[i]))
return true;
}
return false;
}
/// <summary>
/// Determines whether the string is all white space. Empty string will return false.
/// </summary>
/// <param name="s">The string to test whether it is all white space.</param>
/// <returns>
/// <c>true</c> if the string is all white space; otherwise, <c>false</c>.
/// </returns>
public static bool IsWhiteSpace(string s)
{
if (s == null)
throw new ArgumentNullException("s");
if (s.Length == 0)
return false;
for (int i = 0; i < s.Length; i++)
{
if (!char.IsWhiteSpace(s[i]))
return false;
}
return true;
}
/// <summary>
/// Ensures the target string ends with the specified string.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="value">The value.</param>
/// <returns>The target string with the value string at the end.</returns>
public static string EnsureEndsWith(string target, string value)
{
if (target == null)
throw new ArgumentNullException("target");
if (value == null)
throw new ArgumentNullException("value");
if (target.Length >= value.Length)
{
if (string.Compare(target, target.Length - value.Length, value, 0, value.Length, StringComparison.OrdinalIgnoreCase) ==
0)
return target;
string trimmedString = target.TrimEnd(null);
if (string.Compare(trimmedString, trimmedString.Length - value.Length, value, 0, value.Length,
StringComparison.OrdinalIgnoreCase) == 0)
return target;
}
return target + value;
}
public static bool IsNullOrEmptyOrWhiteSpace(string s)
{
if (string.IsNullOrEmpty(s))
return true;
else if (IsWhiteSpace(s))
return true;
else
return false;
}
/// <summary>
/// Perform an action if the string is not null or empty.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="action">The action to perform.</param>
public static void IfNotNullOrEmpty(string value, Action<string> action)
{
IfNotNullOrEmpty(value, action, null);
}
private static void IfNotNullOrEmpty(string value, Action<string> trueAction, Action<string> falseAction)
{
if (!string.IsNullOrEmpty(value))
{
if (trueAction != null)
trueAction(value);
}
else
{
if (falseAction != null)
falseAction(value);
}
}
/// <summary>
/// Indents the specified string.
/// </summary>
/// <param name="s">The string to indent.</param>
/// <param name="indentation">The number of characters to indent by.</param>
/// <returns></returns>
public static string Indent(string s, int indentation)
{
return Indent(s, indentation, ' ');
}
/// <summary>
/// Indents the specified string.
/// </summary>
/// <param name="s">The string to indent.</param>
/// <param name="indentation">The number of characters to indent by.</param>
/// <param name="indentChar">The indent character.</param>
/// <returns></returns>
public static string Indent(string s, int indentation, char indentChar)
{
if (s == null)
throw new ArgumentNullException("s");
if (indentation <= 0)
throw new ArgumentException("Must be greater than zero.", "indentation");
StringReader sr = new StringReader(s);
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line)
{
tw.Write(new string(indentChar, indentation));
tw.Write(line);
});
return sw.ToString();
}
private delegate void ActionLine(TextWriter textWriter, string line);
private static void ActionTextReaderLine(TextReader textReader, TextWriter textWriter, ActionLine lineAction)
{
string line;
bool firstLine = true;
while ((line = textReader.ReadLine()) != null)
{
if (!firstLine)
textWriter.WriteLine();
else
firstLine = false;
lineAction(textWriter, line);
}
}
/// <summary>
/// Numbers the lines.
/// </summary>
/// <param name="s">The string to number.</param>
/// <returns></returns>
public static string NumberLines(string s)
{
if (s == null)
throw new ArgumentNullException("s");
StringReader sr = new StringReader(s);
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
int lineNumber = 1;
ActionTextReaderLine(sr, sw, delegate(TextWriter tw, string line)
{
tw.Write(lineNumber.ToString(CultureInfo.InvariantCulture).PadLeft(4));
tw.Write(". ");
tw.Write(line);
lineNumber++;
});
return sw.ToString();
}
/// <summary>
/// Nulls an empty string.
/// </summary>
/// <param name="s">The string.</param>
/// <returns>Null if the string was null, otherwise the string unchanged.</returns>
public static string NullEmptyString(string s)
{
return (string.IsNullOrEmpty(s)) ? null : s;
}
public static string ReplaceNewLines(string s, string replacement)
{
StringReader sr = new StringReader(s);
StringBuilder sb = new StringBuilder();
bool first = true;
string line;
while ((line = sr.ReadLine()) != null)
{
if (first)
first = false;
else
sb.Append(replacement);
sb.Append(line);
}
return sb.ToString();
}
public static string Truncate(string s, int maximumLength)
{
return Truncate(s, maximumLength, "...");
}
public static string Truncate(string s, int maximumLength, string suffix)
{
if (suffix == null)
throw new ArgumentNullException("suffix");
if (maximumLength <= 0)
throw new ArgumentException("Maximum length must be greater than zero.", "maximumLength");
int subStringLength = maximumLength - suffix.Length;
if (subStringLength <= 0)
throw new ArgumentException("Length of suffix string is greater or equal to maximumLength");
if (s != null && s.Length > maximumLength)
{
string truncatedString = s.Substring(0, subStringLength);
// incase the last character is a space
truncatedString = truncatedString.Trim();
truncatedString += suffix;
return truncatedString;
}
else
{
return s;
}
}
public static StringWriter CreateStringWriter(int capacity)
{
StringBuilder sb = new StringBuilder(capacity);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
return sw;
}
public static int? GetLength(string value)
{
if (value == null)
return null;
else
return value.Length;
}
public static string ToCharAsUnicode(char c)
{
using (StringWriter w = new StringWriter(CultureInfo.InvariantCulture))
{
WriteCharAsUnicode(w, c);
return w.ToString();
}
}
public static void WriteCharAsUnicode(TextWriter writer, char c)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
char h1 = MathUtils.IntToHex((c >> 12) & '\x000f');
char h2 = MathUtils.IntToHex((c >> 8) & '\x000f');
char h3 = MathUtils.IntToHex((c >> 4) & '\x000f');
char h4 = MathUtils.IntToHex(c & '\x000f');
writer.Write('\\');
writer.Write('u');
writer.Write(h1);
writer.Write(h2);
writer.Write(h3);
writer.Write(h4);
}
public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue)
{
if (source == null)
throw new ArgumentNullException("source");
if (valueSelector == null)
throw new ArgumentNullException("valueSelector");
var caseInsensitiveResults = source.Where(s => string.Compare(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase) == 0);
if (caseInsensitiveResults.Count() <= 1)
{
return caseInsensitiveResults.SingleOrDefault();
}
else
{
// multiple results returned. now filter using case sensitivity
var caseSensitiveResults = source.Where(s => string.Compare(valueSelector(s), testValue, StringComparison.Ordinal) == 0);
return caseSensitiveResults.SingleOrDefault();
}
}
}
}
| |
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
using UMA;
using UMA.Integrations;
using UMACharacterSystem;
namespace UMAEditor
{
[CustomEditor(typeof(UMAWardrobeCollection), true)]
public partial class UMAWardrobeCollectionEditor : RecipeEditor {
static bool coverImagesIsExpanded = false;
protected override bool PreInspectorGUI()
{
hideToolBar = true;
hideRaceField = true;
return TextRecipeGUI();
}
/// <summary>
/// Impliment this method to output any extra GUI for any extra fields you have added to UMAWardrobeCollection before the main RecipeGUI
/// </summary>
partial void PreRecipeGUI(ref bool changed);
/// <summary>
/// Impliment this method to output any extra GUI for any extra fields you have added to UMAWardrobeCollection after the main RecipeGUI
/// </summary>
partial void PostRecipeGUI(ref bool changed);
protected override bool PostInspectorGUI()
{
bool changed = false;
PostRecipeGUI(ref changed);
return changed;
}
//draws the coverImages foldout
protected virtual bool DrawCoverImagesUI(Type TargetType)
{
bool doUpdate = false;
//FieldInfos
var CoverImagesField = TargetType.GetField("coverImages", BindingFlags.Public | BindingFlags.Instance);
//field values
List<Sprite> coverImages = (List<Sprite>)CoverImagesField.GetValue(target);
//drawUI
GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
GUILayout.Space(10);
coverImagesIsExpanded = EditorGUILayout.Foldout(coverImagesIsExpanded, new GUIContent("Cover Images"));
GUILayout.EndHorizontal();
if (coverImagesIsExpanded)
{
List<Sprite> prevCoverImages = coverImages;
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f));
EditorGUILayout.BeginHorizontal();
for (int i = 0; i < coverImages.Count; i++)
{
EditorGUI.BeginChangeCheck();
var thisImg = EditorGUILayout.ObjectField(coverImages[i], typeof(Sprite), false, GUILayout.Width(75), GUILayout.Height(75));
if (EditorGUI.EndChangeCheck())
{
if (thisImg != coverImages[i])
{
if (thisImg == null)
{
coverImages.RemoveAt(i);
}
else
{
coverImages[i] = (Sprite)thisImg;
}
doUpdate = true;
}
}
}
EditorGUILayout.EndHorizontal();
if (GUILayout.Button("Add"))
{
coverImages.Add(new Sprite());
}
if (!AreListsEqual<Sprite>(prevCoverImages, coverImages))
{
CoverImagesField.SetValue(target, coverImages);
}
GUIHelper.EndVerticalPadded(10);
}
GUILayout.Space(-5f);
return doUpdate;
}
/// <summary>
/// An editor for a WardrobeCollection. Wardrobe collections can have Shared Colors and multiple WardrobeSets, but dont need a standard Slot or DNA Editor
/// </summary>
public class WardrobeCollectionMasterEditor : SlotMasterEditor
{
private List<string> _compatibleRaces = new List<string>();
private WardrobeCollectionList _wardrobeCollection;
private List<string> _arbitraryRecipes = new List<string>();
private bool forceGUIUpdate = false;
private static string recipesAddErrMsg = "";
//int recipePickerID = -1; This is needed if we can make the recipe drop area work with 'Click To Pick'
public WardrobeCollectionMasterEditor(UMAData.UMARecipe recipe, List<string> compatibleRaces, WardrobeCollectionList wardrobeCollection, List<string> arbitraryRecipes) : base(recipe)
{
_compatibleRaces = compatibleRaces;
_wardrobeCollection = wardrobeCollection;
_arbitraryRecipes = arbitraryRecipes;
UpdateFoldouts();
recipesAddErrMsg = "";
}
public void UpdateVals(List<string> compatibleRaces, WardrobeCollectionList wardrobeCollection, List<string> arbitraryRecipes)
{
forceGUIUpdate = false;
_wardrobeCollection = wardrobeCollection;
_compatibleRaces = compatibleRaces;
forceGUIUpdate = UpdateCollectionRaces();
UpdateFoldouts();
}
private void UpdateFoldouts()
{
if (!OpenSlots.ContainsKey("wardrobeSets"))
OpenSlots.Add("wardrobeSets", true);
if (!OpenSlots.ContainsKey("arbitraryRecipes"))
OpenSlots.Add("arbitraryRecipes", true);
for (int i = 0; i < _compatibleRaces.Count; i++)
{
bool open = i == 0 ? true : false;
if (!OpenSlots.ContainsKey(_compatibleRaces[i]))
{
OpenSlots.Add(_compatibleRaces[i], open);
}
}
}
private bool UpdateCollectionRaces()
{
bool changed = false;
if (_compatibleRaces.Count == 0 && _wardrobeCollection.sets.Count > 0)
{
_wardrobeCollection.Clear();
changed = true;
}
else
{
for(int i = 0; i < _compatibleRaces.Count; i++)
{
if (!_wardrobeCollection.Contains(_compatibleRaces[i]))
{
_wardrobeCollection.Add(_compatibleRaces[i]);
changed = true;
}
}
var collectionNames = _wardrobeCollection.GetAllRacesInCollection();
for(int i = 0; i < collectionNames.Count; i++)
{
if (!_compatibleRaces.Contains(collectionNames[i]))
{
_wardrobeCollection.Remove(collectionNames[i]);
changed = true;
}
}
}
return changed;
}
public override bool OnGUI(ref bool _dnaDirty, ref bool _textureDirty, ref bool _meshDirty)
{
var context = UMAContext.FindInstance();
if (context == null)
{
var _errorMessage = "Editing a recipe requires a loaded scene with a valid UMAContext.";
Debug.LogWarning(_errorMessage);
return false;
}
bool changed = forceGUIUpdate;
//Make a foldout for WardrobeSets - the UI for an individual WardrobeSet is added for each compatible race in the collection
GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
GUILayout.Space(10);
bool wsfoldoutOpen = OpenSlots["wardrobeSets"];
wsfoldoutOpen = EditorGUILayout.Foldout(OpenSlots["wardrobeSets"], "Wardrobe Sets");
OpenSlots["wardrobeSets"] = wsfoldoutOpen;
GUILayout.EndHorizontal();
if (wsfoldoutOpen)
{
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f));
EditorGUILayout.HelpBox("Wardrobe Sets are added for each 'Compatible Race' assigned above. They can be assigned to an avatar of that race in its 'FullOutfit' slot. 'SharedColors' in this section will be applied to the Avatar when the 'FullOutfit' recipe is applied to the character", MessageType.Info);
if (_compatibleRaces.Count > 0)
{
//dont show shared colors unless there are 'FullOutfits' to apply them to
if (_sharedColorsEditor.OnGUI(_recipe))
{
changed = true;
_textureDirty = true;
}
for (int i = 0; i < _compatibleRaces.Count; i++)
{
var thisRace = context.raceLibrary.GetRace(_compatibleRaces[i]);
if (thisRace != null)
{
GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
GUILayout.Space(10);
bool foldoutOpen = OpenSlots[_compatibleRaces[i]];
foldoutOpen = EditorGUILayout.Foldout(OpenSlots[_compatibleRaces[i]], " Wardrobe Set: " + _compatibleRaces[i]);
OpenSlots[_compatibleRaces[i]] = foldoutOpen;
GUILayout.EndHorizontal();
if (foldoutOpen)
{
var thisSetEditor = new WardrobeSetEditor(thisRace, _wardrobeCollection[thisRace.raceName], _recipe, false);
if (thisSetEditor.OnGUI())
{
_wardrobeCollection[thisRace.raceName] = thisSetEditor.WardrobeSet;
changed = true;
}
}
}
else
{
//Do the foldout thing but show as 'missing'
GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
GUILayout.Space(10);
bool foldoutOpen = OpenSlots[_compatibleRaces[i]];
foldoutOpen = EditorGUILayout.Foldout(OpenSlots[_compatibleRaces[i]], _compatibleRaces[i] + " Wardrobe Set (Missing)");
OpenSlots[_compatibleRaces[i]] = foldoutOpen;
GUILayout.EndHorizontal();
if (foldoutOpen)
{
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f));
EditorGUILayout.HelpBox("_compatibleRaces[i] could not be located by the Dynamic Race Library", MessageType.Warning);
GUIHelper.EndVerticalPadded(10);
}
}
}
}
else
{
EditorGUILayout.HelpBox("Drag in compatible races at the top of this recipe and WardrobeSets for those races will show here", MessageType.Info);
}
GUIHelper.EndVerticalPadded(10);
}
GUILayout.Space(10);
//the Arbitrary Recipes section
GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
GUILayout.Space(10);
bool arbiOpen = OpenSlots["arbitraryRecipes"];
arbiOpen = EditorGUILayout.Foldout(OpenSlots["arbitraryRecipes"], "Arbitrary Recipes");
OpenSlots["arbitraryRecipes"] = arbiOpen;
Rect dropArea = new Rect();
GUILayout.EndHorizontal();
if (arbiOpen)
{
GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f));
EditorGUILayout.HelpBox("Drop recipes in to this area to create a collection that is not a full outfit or connected to any given race, for example a 'Hair Styles' pack or 'Tattoos' pack.", MessageType.Info);
dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
GUI.Box(dropArea, "Drag WardrobeRecipes here. " + recipesAddErrMsg);
if (_arbitraryRecipes.Count > 0)
{
for (int i = 0; i < _arbitraryRecipes.Count; i++)
{
GUILayout.Space(2f);
GUI.enabled = false; //we readonly to prevent typos
Rect crfRect = GUILayoutUtility.GetRect(0.0f, EditorGUIUtility.singleLineHeight, GUILayout.ExpandWidth(true));
Rect crfDelRect = crfRect;
crfRect.width = crfRect.width - 20f - 5f;
crfDelRect.width = 20f + 2f;
crfDelRect.x = crfRect.width + 20f + 10f;
EditorGUI.TextField(crfRect, _arbitraryRecipes[i]);
GUI.enabled = true;
if (GUI.Button(crfDelRect, "X"))
{
_arbitraryRecipes.RemoveAt(i);
changed = true;
}
}
}
GUIHelper.EndVerticalPadded(10);
if (AddRecipesDropAreaGUI(ref recipesAddErrMsg, dropArea, _arbitraryRecipes))
changed = true;
}
return changed;
}
// Drop area for Arbitrary Wardrobe recipes
private bool AddRecipesDropAreaGUI(ref string errorMsg, Rect dropArea, List<string> recipes)
{
Event evt = Event.current;
bool changed = false;
//make the box clickable so that the user can select raceData assets from the asset selection window
//TODO: cant make this work without layout errors. Anyone know how to fix?
/*if (evt.type == EventType.MouseUp)
{
if (dropArea.Contains(evt.mousePosition))
{
recipePickerID = EditorGUIUtility.GetControlID(new GUIContent("recipeObjectPicker"), FocusType.Passive);
EditorGUIUtility.ShowObjectPicker<UMARecipeBase>(null, false, "", recipePickerID);
}
}
if (evt.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == recipePickerID)
{
UMARecipeBase tempRecipeAsset = EditorGUIUtility.GetObjectPickerObject() as UMARecipeBase;
if (tempRecipeAsset)
{
if (AddIfWardrobeRecipe(tempRecipeAsset, recipes))
{
changed = true;
errorMsg = "";
}
else
errorMsg = "That recipe was not a Wardrobe recipe";
}
}*/
if (evt.type == EventType.DragUpdated)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
}
}
if (evt.type == EventType.DragPerform)
{
if (dropArea.Contains(evt.mousePosition))
{
DragAndDrop.AcceptDrag();
UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[];
bool allAdded = true;
for (int i = 0; i < draggedObjects.Length; i++)
{
if (draggedObjects[i])
{
UMARecipeBase tempRecipeAsset = draggedObjects[i] as UMARecipeBase;
if (tempRecipeAsset)
{
if (AddIfWardrobeRecipe(tempRecipeAsset, recipes))
changed = true;
else
{
allAdded = false;
}
continue;
}
var path = AssetDatabase.GetAssetPath(draggedObjects[i]);
if (System.IO.Directory.Exists(path))
{
RecursiveScanFoldersForAssets(path, recipes);
}
}
}
if (!allAdded)
errorMsg = "Some of the recipes you tried to add were not Wardrobe recipes";
else
errorMsg = "";
}
}
return changed;
}
private bool AddIfWardrobeRecipe(UnityEngine.Object tempRecipeAsset, List<string> recipes)
{
bool added = false;
if (!recipes.Contains(tempRecipeAsset.name))
{
Type TargetType = tempRecipeAsset.GetType();
if (TargetType.ToString() == "UMATextRecipe" || TargetType.ToString() == "UMAWardrobeRecipe")
{
FieldInfo RecipeTypeField = TargetType.GetField("recipeType", BindingFlags.Public | BindingFlags.Instance);
string recipeType = (string)RecipeTypeField.GetValue(tempRecipeAsset);
if (recipeType == "Wardrobe")
{
recipes.Add(tempRecipeAsset.name);
added = true;
}
}
}
return added;
}
private void RecursiveScanFoldersForAssets(string path, List<string> recipes)
{
var assetFiles = System.IO.Directory.GetFiles(path, "*.asset");
foreach (var assetFile in assetFiles)
{
var tempRecipeAsset = AssetDatabase.LoadAssetAtPath(assetFile, typeof(UMARecipeBase)) as UMARecipeBase;
if (tempRecipeAsset)
{
AddIfWardrobeRecipe(tempRecipeAsset, recipes);
}
}
foreach (var subFolder in System.IO.Directory.GetDirectories(path))
{
RecursiveScanFoldersForAssets(subFolder.Replace('\\', '/'), recipes);
}
}
}
protected virtual bool TextRecipeGUI()
{
Type TargetType = target.GetType();
bool doUpdate = false;
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.Popup("Recipe Type", 0, new string[] { "WardrobeCollection"});
EditorGUI.EndDisabledGroup();
PreRecipeGUI(ref doUpdate);
FieldInfo CompatibleRacesField = TargetType.GetField("compatibleRaces", BindingFlags.Public | BindingFlags.Instance);
List<string> compatibleRaces = (List<string>)CompatibleRacesField.GetValue(target);
//FieldInfos
FieldInfo WardrobeCollectionList = TargetType.GetField("wardrobeCollection", BindingFlags.Public | BindingFlags.Instance);
FieldInfo ArbitraryRecipesList = TargetType.GetField("arbitraryRecipes", BindingFlags.Public | BindingFlags.Instance);
//field values
WardrobeCollectionList wardrobeCollection = (WardrobeCollectionList)WardrobeCollectionList.GetValue(target);
List<string> arbitraryRecipes = (List<string>)ArbitraryRecipesList.GetValue(target);
if (slotEditor == null || slotEditor.GetType() != typeof(WardrobeCollectionMasterEditor))
{
slotEditor = new WardrobeCollectionMasterEditor(_recipe, compatibleRaces, wardrobeCollection, arbitraryRecipes);
}
else
{
(slotEditor as WardrobeCollectionMasterEditor).UpdateVals(compatibleRaces, wardrobeCollection, arbitraryRecipes);
}
//wardrobe collection also has a 'cover image' field
if (DrawCoverImagesUI(TargetType))
doUpdate = true;
//CompatibleRaces drop area
if (DrawCompatibleRacesUI(TargetType))
doUpdate = true;
EditorGUILayout.Space();
return doUpdate;
}
}
}
#endif
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - [email protected])
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1995
{
/// <summary>
/// Section 5.3.7.2. Handles designating operations
/// </summary>
[Serializable]
[XmlRoot]
[XmlInclude(typeof(EntityID))]
[XmlInclude(typeof(Vector3Float))]
[XmlInclude(typeof(Vector3Double))]
public partial class DesignatorPdu : DistributedEmissionsPdu, IEquatable<DesignatorPdu>
{
/// <summary>
/// ID of the entity designating
/// </summary>
private EntityID _designatingEntityID = new EntityID();
/// <summary>
/// This field shall specify a unique emitter database number assigned to differentiate between otherwise similar or identical emitter beams within an emitter system.
/// </summary>
private ushort _codeName;
/// <summary>
/// ID of the entity being designated
/// </summary>
private EntityID _designatedEntityID = new EntityID();
/// <summary>
/// This field shall identify the designator code being used by the designating entity
/// </summary>
private ushort _designatorCode;
/// <summary>
/// This field shall identify the designator output power in watts
/// </summary>
private float _designatorPower;
/// <summary>
/// This field shall identify the designator wavelength in units of microns
/// </summary>
private float _designatorWavelength;
/// <summary>
/// designtor spot wrt the designated entity
/// </summary>
private Vector3Float _designatorSpotWrtDesignated = new Vector3Float();
/// <summary>
/// designtor spot wrt the designated entity
/// </summary>
private Vector3Double _designatorSpotLocation = new Vector3Double();
/// <summary>
/// Dead reckoning algorithm
/// </summary>
private byte _deadReckoningAlgorithm;
/// <summary>
/// padding
/// </summary>
private ushort _padding1;
/// <summary>
/// padding
/// </summary>
private byte _padding2;
/// <summary>
/// linear accelleration of entity
/// </summary>
private Vector3Float _entityLinearAcceleration = new Vector3Float();
/// <summary>
/// Initializes a new instance of the <see cref="DesignatorPdu"/> class.
/// </summary>
public DesignatorPdu()
{
PduType = (byte)24;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(DesignatorPdu left, DesignatorPdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(DesignatorPdu left, DesignatorPdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += this._designatingEntityID.GetMarshalledSize(); // this._designatingEntityID
marshalSize += 2; // this._codeName
marshalSize += this._designatedEntityID.GetMarshalledSize(); // this._designatedEntityID
marshalSize += 2; // this._designatorCode
marshalSize += 4; // this._designatorPower
marshalSize += 4; // this._designatorWavelength
marshalSize += this._designatorSpotWrtDesignated.GetMarshalledSize(); // this._designatorSpotWrtDesignated
marshalSize += this._designatorSpotLocation.GetMarshalledSize(); // this._designatorSpotLocation
marshalSize += 1; // this._deadReckoningAlgorithm
marshalSize += 2; // this._padding1
marshalSize += 1; // this._padding2
marshalSize += this._entityLinearAcceleration.GetMarshalledSize(); // this._entityLinearAcceleration
return marshalSize;
}
/// <summary>
/// Gets or sets the ID of the entity designating
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "designatingEntityID")]
public EntityID DesignatingEntityID
{
get
{
return this._designatingEntityID;
}
set
{
this._designatingEntityID = value;
}
}
/// <summary>
/// Gets or sets the This field shall specify a unique emitter database number assigned to differentiate between otherwise similar or identical emitter beams within an emitter system.
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "codeName")]
public ushort CodeName
{
get
{
return this._codeName;
}
set
{
this._codeName = value;
}
}
/// <summary>
/// Gets or sets the ID of the entity being designated
/// </summary>
[XmlElement(Type = typeof(EntityID), ElementName = "designatedEntityID")]
public EntityID DesignatedEntityID
{
get
{
return this._designatedEntityID;
}
set
{
this._designatedEntityID = value;
}
}
/// <summary>
/// Gets or sets the This field shall identify the designator code being used by the designating entity
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "designatorCode")]
public ushort DesignatorCode
{
get
{
return this._designatorCode;
}
set
{
this._designatorCode = value;
}
}
/// <summary>
/// Gets or sets the This field shall identify the designator output power in watts
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "designatorPower")]
public float DesignatorPower
{
get
{
return this._designatorPower;
}
set
{
this._designatorPower = value;
}
}
/// <summary>
/// Gets or sets the This field shall identify the designator wavelength in units of microns
/// </summary>
[XmlElement(Type = typeof(float), ElementName = "designatorWavelength")]
public float DesignatorWavelength
{
get
{
return this._designatorWavelength;
}
set
{
this._designatorWavelength = value;
}
}
/// <summary>
/// Gets or sets the designtor spot wrt the designated entity
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "designatorSpotWrtDesignated")]
public Vector3Float DesignatorSpotWrtDesignated
{
get
{
return this._designatorSpotWrtDesignated;
}
set
{
this._designatorSpotWrtDesignated = value;
}
}
/// <summary>
/// Gets or sets the designtor spot wrt the designated entity
/// </summary>
[XmlElement(Type = typeof(Vector3Double), ElementName = "designatorSpotLocation")]
public Vector3Double DesignatorSpotLocation
{
get
{
return this._designatorSpotLocation;
}
set
{
this._designatorSpotLocation = value;
}
}
/// <summary>
/// Gets or sets the Dead reckoning algorithm
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "deadReckoningAlgorithm")]
public byte DeadReckoningAlgorithm
{
get
{
return this._deadReckoningAlgorithm;
}
set
{
this._deadReckoningAlgorithm = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "padding1")]
public ushort Padding1
{
get
{
return this._padding1;
}
set
{
this._padding1 = value;
}
}
/// <summary>
/// Gets or sets the padding
/// </summary>
[XmlElement(Type = typeof(byte), ElementName = "padding2")]
public byte Padding2
{
get
{
return this._padding2;
}
set
{
this._padding2 = value;
}
}
/// <summary>
/// Gets or sets the linear accelleration of entity
/// </summary>
[XmlElement(Type = typeof(Vector3Float), ElementName = "entityLinearAcceleration")]
public Vector3Float EntityLinearAcceleration
{
get
{
return this._entityLinearAcceleration;
}
set
{
this._entityLinearAcceleration = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
this._designatingEntityID.Marshal(dos);
dos.WriteUnsignedShort((ushort)this._codeName);
this._designatedEntityID.Marshal(dos);
dos.WriteUnsignedShort((ushort)this._designatorCode);
dos.WriteFloat((float)this._designatorPower);
dos.WriteFloat((float)this._designatorWavelength);
this._designatorSpotWrtDesignated.Marshal(dos);
this._designatorSpotLocation.Marshal(dos);
dos.WriteByte((byte)this._deadReckoningAlgorithm);
dos.WriteUnsignedShort((ushort)this._padding1);
dos.WriteByte((byte)this._padding2);
this._entityLinearAcceleration.Marshal(dos);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._designatingEntityID.Unmarshal(dis);
this._codeName = dis.ReadUnsignedShort();
this._designatedEntityID.Unmarshal(dis);
this._designatorCode = dis.ReadUnsignedShort();
this._designatorPower = dis.ReadFloat();
this._designatorWavelength = dis.ReadFloat();
this._designatorSpotWrtDesignated.Unmarshal(dis);
this._designatorSpotLocation.Unmarshal(dis);
this._deadReckoningAlgorithm = dis.ReadByte();
this._padding1 = dis.ReadUnsignedShort();
this._padding2 = dis.ReadByte();
this._entityLinearAcceleration.Unmarshal(dis);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<DesignatorPdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<designatingEntityID>");
this._designatingEntityID.Reflection(sb);
sb.AppendLine("</designatingEntityID>");
sb.AppendLine("<codeName type=\"ushort\">" + this._codeName.ToString(CultureInfo.InvariantCulture) + "</codeName>");
sb.AppendLine("<designatedEntityID>");
this._designatedEntityID.Reflection(sb);
sb.AppendLine("</designatedEntityID>");
sb.AppendLine("<designatorCode type=\"ushort\">" + this._designatorCode.ToString(CultureInfo.InvariantCulture) + "</designatorCode>");
sb.AppendLine("<designatorPower type=\"float\">" + this._designatorPower.ToString(CultureInfo.InvariantCulture) + "</designatorPower>");
sb.AppendLine("<designatorWavelength type=\"float\">" + this._designatorWavelength.ToString(CultureInfo.InvariantCulture) + "</designatorWavelength>");
sb.AppendLine("<designatorSpotWrtDesignated>");
this._designatorSpotWrtDesignated.Reflection(sb);
sb.AppendLine("</designatorSpotWrtDesignated>");
sb.AppendLine("<designatorSpotLocation>");
this._designatorSpotLocation.Reflection(sb);
sb.AppendLine("</designatorSpotLocation>");
sb.AppendLine("<deadReckoningAlgorithm type=\"byte\">" + this._deadReckoningAlgorithm.ToString(CultureInfo.InvariantCulture) + "</deadReckoningAlgorithm>");
sb.AppendLine("<padding1 type=\"ushort\">" + this._padding1.ToString(CultureInfo.InvariantCulture) + "</padding1>");
sb.AppendLine("<padding2 type=\"byte\">" + this._padding2.ToString(CultureInfo.InvariantCulture) + "</padding2>");
sb.AppendLine("<entityLinearAcceleration>");
this._entityLinearAcceleration.Reflection(sb);
sb.AppendLine("</entityLinearAcceleration>");
sb.AppendLine("</DesignatorPdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as DesignatorPdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(DesignatorPdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (!this._designatingEntityID.Equals(obj._designatingEntityID))
{
ivarsEqual = false;
}
if (this._codeName != obj._codeName)
{
ivarsEqual = false;
}
if (!this._designatedEntityID.Equals(obj._designatedEntityID))
{
ivarsEqual = false;
}
if (this._designatorCode != obj._designatorCode)
{
ivarsEqual = false;
}
if (this._designatorPower != obj._designatorPower)
{
ivarsEqual = false;
}
if (this._designatorWavelength != obj._designatorWavelength)
{
ivarsEqual = false;
}
if (!this._designatorSpotWrtDesignated.Equals(obj._designatorSpotWrtDesignated))
{
ivarsEqual = false;
}
if (!this._designatorSpotLocation.Equals(obj._designatorSpotLocation))
{
ivarsEqual = false;
}
if (this._deadReckoningAlgorithm != obj._deadReckoningAlgorithm)
{
ivarsEqual = false;
}
if (this._padding1 != obj._padding1)
{
ivarsEqual = false;
}
if (this._padding2 != obj._padding2)
{
ivarsEqual = false;
}
if (!this._entityLinearAcceleration.Equals(obj._entityLinearAcceleration))
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._designatingEntityID.GetHashCode();
result = GenerateHash(result) ^ this._codeName.GetHashCode();
result = GenerateHash(result) ^ this._designatedEntityID.GetHashCode();
result = GenerateHash(result) ^ this._designatorCode.GetHashCode();
result = GenerateHash(result) ^ this._designatorPower.GetHashCode();
result = GenerateHash(result) ^ this._designatorWavelength.GetHashCode();
result = GenerateHash(result) ^ this._designatorSpotWrtDesignated.GetHashCode();
result = GenerateHash(result) ^ this._designatorSpotLocation.GetHashCode();
result = GenerateHash(result) ^ this._deadReckoningAlgorithm.GetHashCode();
result = GenerateHash(result) ^ this._padding1.GetHashCode();
result = GenerateHash(result) ^ this._padding2.GetHashCode();
result = GenerateHash(result) ^ this._entityLinearAcceleration.GetHashCode();
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Utilities;
using Signum.Engine.Maps;
using Signum.Engine.Authorization;
using Signum.Engine;
using System.Xml.Linq;
using Signum.Engine.Basics;
using Signum.Entities.Basics;
using System.Reflection;
using Signum.Entities.Reflection;
namespace Signum.Entities.Authorization
{
class TypeAuthCache : IManualAuth<Type, TypeAllowedAndConditions>
{
readonly ResetLazy<Dictionary<Lite<RoleEntity>, RoleAllowedCache>> runtimeRules;
IMerger<Type, TypeAllowedAndConditions> merger;
public TypeAuthCache(SchemaBuilder sb, IMerger<Type, TypeAllowedAndConditions> merger)
{
this.merger = merger;
sb.Include<RuleTypeEntity>();
sb.AddUniqueIndex<RuleTypeEntity>(rt => new { rt.Resource, rt.Role });
runtimeRules = sb.GlobalLazy(NewCache,
new InvalidateWith(typeof(RuleTypeEntity), typeof(RoleEntity)), AuthLogic.NotifyRulesChanged);
sb.Schema.EntityEvents<RoleEntity>().PreUnsafeDelete += query => { Database.Query<RuleTypeEntity>().Where(r => query.Contains(r.Role.Entity)).UnsafeDelete(); return null; };
sb.Schema.Table<TypeEntity>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand?>(AuthCache_PreDeleteSqlSync_Type);
sb.Schema.Table<TypeConditionSymbol>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand?>(AuthCache_PreDeleteSqlSync_Condition);
Validator.PropertyValidator((RuleTypeEntity r) => r.Conditions).StaticPropertyValidation += TypeAuthCache_StaticPropertyValidation;
}
string? TypeAuthCache_StaticPropertyValidation(ModifiableEntity sender, PropertyInfo pi)
{
RuleTypeEntity rt = (RuleTypeEntity)sender;
if (rt.Resource == null)
{
if (rt.Conditions.Any())
return "Default {0} should not have conditions".FormatWith(typeof(RuleTypeEntity).NiceName());
return null;
}
try
{
Type type = TypeLogic.EntityToType.GetOrThrow(rt.Resource);
var conditions = rt.Conditions.Where(a =>
a.Condition.FieldInfo != null && /*Not 100% Sync*/
!TypeConditionLogic.IsDefined(type, a.Condition));
if (conditions.IsEmpty())
return null;
return "Type {0} has no definitions for the conditions: {1}".FormatWith(type.Name, conditions.CommaAnd(a => a.Condition.Key));
}
catch (Exception ex) when (StartParameters.IgnoredDatabaseMismatches != null)
{
//This try { throw } catch is here to alert developers.
//In production, in some cases its OK to attempt starting an application with a slightly different schema (dynamic entities, green-blue deployments).
//In development, consider synchronize.
StartParameters.IgnoredDatabaseMismatches.Add(ex);
return null;
}
}
static SqlPreCommand? AuthCache_PreDeleteSqlSync_Type(Entity arg)
{
TypeEntity type = (TypeEntity)arg;
var command = Administrator.UnsafeDeletePreCommand(Database.Query<RuleTypeEntity>().Where(a => a.Resource == type));
return command;
}
static SqlPreCommand? AuthCache_PreDeleteSqlSync_Condition(Entity arg)
{
TypeConditionSymbol condition = (TypeConditionSymbol)arg;
var command = Administrator.UnsafeDeletePreCommandMList((RuleTypeEntity rt)=>rt.Conditions, Database.MListQuery((RuleTypeEntity rt) => rt.Conditions).Where(mle => mle.Element.Condition == condition));
return command;
}
TypeAllowedAndConditions IManualAuth<Type, TypeAllowedAndConditions>.GetAllowed(Lite<RoleEntity> role, Type key)
{
TypeEntity resource = TypeLogic.TypeToEntity.GetOrThrow(key);
ManualResourceCache miniCache = new ManualResourceCache(resource, merger);
return miniCache.GetAllowed(role);
}
void IManualAuth<Type, TypeAllowedAndConditions>.SetAllowed(Lite<RoleEntity> role, Type key, TypeAllowedAndConditions allowed)
{
TypeEntity resource = TypeLogic.TypeToEntity.GetOrThrow(key);
ManualResourceCache miniCache = new ManualResourceCache(resource, merger);
if (miniCache.GetAllowed(role).Equals(allowed))
return;
IQueryable<RuleTypeEntity> query = Database.Query<RuleTypeEntity>().Where(a => a.Resource == resource && a.Role == role);
if (miniCache.GetAllowedBase(role).Equals(allowed))
{
if (query.UnsafeDelete() == 0)
throw new InvalidOperationException("Inconsistency in the data");
}
else
{
query.UnsafeDelete();
allowed.ToRuleType(role, resource).Save();
}
}
public class ManualResourceCache
{
readonly Dictionary<Lite<RoleEntity>, TypeAllowedAndConditions> rules;
readonly IMerger<Type, TypeAllowedAndConditions> merger;
readonly TypeEntity resource;
public ManualResourceCache(TypeEntity resource, IMerger<Type, TypeAllowedAndConditions> merger)
{
this.resource = resource;
var list = Database.Query<RuleTypeEntity>().Where(r => r.Resource == resource || r.Resource == null).ToList();
rules = list.Where(a => a.Resource != null).ToDictionary(a => a.Role, a => a.ToTypeAllowedAndConditions());
this.merger = merger;
}
public TypeAllowedAndConditions GetAllowed(Lite<RoleEntity> role)
{
if (rules.TryGetValue(role, out var result))
return result;
return GetAllowedBase(role);
}
public TypeAllowedAndConditions GetAllowedBase(Lite<RoleEntity> role)
{
IEnumerable<Lite<RoleEntity>> related = AuthLogic.RelatedTo(role);
return merger.Merge(resource.ToType(), role, related.Select(r => KeyValuePair.Create(r, GetAllowed(r))));
}
}
Dictionary<Lite<RoleEntity>, RoleAllowedCache> NewCache()
{
using (AuthLogic.Disable())
using (new EntityCache(EntityCacheType.ForceNewSealed))
{
List<Lite<RoleEntity>> roles = AuthLogic.RolesInOrder().ToList();
var rules = Database.Query<RuleTypeEntity>().ToList();
var errors = GraphExplorer.FullIntegrityCheck(GraphExplorer.FromRoots(rules));
if (errors != null)
throw new IntegrityCheckException(errors);
Dictionary<Lite<RoleEntity>, Dictionary<Type, TypeAllowedAndConditions>> realRules =
rules.AgGroupToDictionary(ru => ru.Role, gr => gr
.SelectCatch(ru => KeyValuePair.Create(TypeLogic.EntityToType.GetOrThrow(ru.Resource), ru.ToTypeAllowedAndConditions()))
.ToDictionaryEx());
Dictionary<Lite<RoleEntity>, RoleAllowedCache> newRules = new Dictionary<Lite<RoleEntity>, RoleAllowedCache>();
foreach (var role in roles)
{
var related = AuthLogic.RelatedTo(role);
newRules.Add(role, new RoleAllowedCache(role, merger, related.Select(r => newRules.GetOrThrow(r)).ToList(), realRules.TryGetC(role)));
}
return newRules;
}
}
internal void GetRules(BaseRulePack<TypeAllowedRule> rules, IEnumerable<TypeEntity> resources)
{
RoleAllowedCache cache = runtimeRules.Value.GetOrThrow(rules.Role);
rules.MergeStrategy = AuthLogic.GetMergeStrategy(rules.Role);
rules.SubRoles = AuthLogic.RelatedTo(rules.Role).ToMList();
rules.Rules = (from r in resources
let type = TypeLogic.EntityToType.GetOrThrow(r)
select new TypeAllowedRule()
{
Resource = r,
AllowedBase = cache.GetAllowedBase(type),
Allowed = cache.GetAllowed(type),
AvailableConditions = TypeConditionLogic.ConditionsFor(type).ToReadOnly()
}).ToMList();
}
internal void SetRules(BaseRulePack<TypeAllowedRule> rules)
{
using (AuthLogic.Disable())
{
var current = Database.Query<RuleTypeEntity>().Where(r => r.Role == rules.Role && r.Resource != null).ToDictionary(a => a.Resource);
var should = rules.Rules.Where(a => a.Overriden).ToDictionary(r => r.Resource);
Synchronizer.Synchronize(should, current,
(type, ar) => ar.Allowed.ToRuleType(rules.Role, type).Save(),
(type, pr) => pr.Delete(),
(type, ar, pr) =>
{
pr.Allowed = ar.Allowed.Fallback!.Value;
var shouldConditions = ar.Allowed.Conditions.Select(a => new RuleTypeConditionEmbedded
{
Allowed = a.Allowed,
Condition = a.TypeCondition,
}).ToMList();
if (!pr.Conditions.SequenceEqual(shouldConditions))
pr.Conditions = shouldConditions;
if (pr.IsGraphModified)
pr.Save();
});
}
}
internal TypeAllowedAndConditions GetAllowed(Lite<RoleEntity> role, Type key)
{
return runtimeRules.Value.GetOrThrow(role).GetAllowed(key);
}
internal TypeAllowedAndConditions GetAllowedBase(Lite<RoleEntity> role, Type key)
{
return runtimeRules.Value.GetOrThrow(role).GetAllowedBase(key);
}
internal DefaultDictionary<Type, TypeAllowedAndConditions> GetDefaultDictionary()
{
return runtimeRules.Value.GetOrThrow(RoleEntity.Current).DefaultDictionary();
}
public class RoleAllowedCache
{
readonly IMerger<Type, TypeAllowedAndConditions> merger;
readonly DefaultDictionary<Type, TypeAllowedAndConditions> rules;
readonly List<RoleAllowedCache> baseCaches;
readonly Lite<RoleEntity> role;
public RoleAllowedCache(Lite<RoleEntity> role, IMerger<Type, TypeAllowedAndConditions> merger, List<RoleAllowedCache> baseCaches, Dictionary<Type, TypeAllowedAndConditions>? newValues)
{
this.role = role;
this.merger = merger;
this.baseCaches = baseCaches;
Func<Type, TypeAllowedAndConditions> defaultAllowed = merger.MergeDefault(role);
Func<Type, TypeAllowedAndConditions> baseAllowed = k => merger.Merge(k, role, baseCaches.Select(b => KeyValuePair.Create(b.role, b.GetAllowed(k))));
var keys = baseCaches
.Where(b => b.rules.OverrideDictionary != null)
.SelectMany(a => a.rules.OverrideDictionary!.Keys)
.ToHashSet();
Dictionary<Type, TypeAllowedAndConditions>? tmpRules = keys.ToDictionary(k => k, baseAllowed);
if (newValues != null)
tmpRules.SetRange(newValues);
tmpRules = Simplify(tmpRules, defaultAllowed, baseAllowed);
rules = new DefaultDictionary<Type, TypeAllowedAndConditions>(defaultAllowed, tmpRules);
}
internal static Dictionary<Type, TypeAllowedAndConditions>? Simplify(Dictionary<Type, TypeAllowedAndConditions> dictionary,
Func<Type, TypeAllowedAndConditions> defaultAllowed,
Func<Type, TypeAllowedAndConditions> baseAllowed)
{
if (dictionary == null || dictionary.Count == 0)
return null;
dictionary.RemoveRange(dictionary.Where(p =>
p.Value.Equals(defaultAllowed(p.Key)) &&
p.Value.Equals(baseAllowed(p.Key))).Select(p => p.Key).ToList());
if (dictionary.Count == 0)
return null;
return dictionary;
}
public TypeAllowedAndConditions GetAllowed(Type k)
{
return rules.GetAllowed(k);
}
public TypeAllowedAndConditions GetAllowedBase(Type k)
{
return merger.Merge(k, role, baseCaches.Select(b => KeyValuePair.Create(b.role, b.GetAllowed(k))));
}
internal DefaultDictionary<Type, TypeAllowedAndConditions> DefaultDictionary()
{
return this.rules;
}
}
internal XElement ExportXml(List<Type>? allTypes)
{
var rules = runtimeRules.Value;
return new XElement("Types",
(from r in AuthLogic.RolesInOrder()
let rac = rules.GetOrThrow(r)
select new XElement("Role",
new XAttribute("Name", r.ToString()),
from k in allTypes ?? (rac.DefaultDictionary().OverrideDictionary?.Keys).EmptyIfNull()
let allowedBase = rac.GetAllowedBase(k)
let allowed = rac.GetAllowed(k)
where allTypes != null || !allowed.Equals(allowedBase)
let resource = TypeLogic.GetCleanName(k)
orderby resource
select new XElement("Type",
new XAttribute("Resource", resource),
new XAttribute("Allowed", allowed.Fallback.ToString()),
from c in allowed.Conditions
select new XElement("Condition",
new XAttribute("Name", c.TypeCondition.Key),
new XAttribute("Allowed", c.Allowed.ToString()))
)
)
));
}
internal static readonly string typeReplacementKey = "AuthRules:" + typeof(TypeEntity).Name;
internal static readonly string typeConditionReplacementKey = "AuthRules:" + typeof(TypeConditionSymbol).Name;
internal SqlPreCommand? ImportXml(XElement element, Dictionary<string, Lite<RoleEntity>> roles, Replacements replacements)
{
var current = Database.RetrieveAll<RuleTypeEntity>().GroupToDictionary(a => a.Role);
var xRoles = (element.Element("Types")?.Elements("Role")).EmptyIfNull();
var should = xRoles.ToDictionary(x => roles.GetOrThrow(x.Attribute("Name").Value));
Table table = Schema.Current.Table(typeof(RuleTypeEntity));
replacements.AskForReplacements(
xRoles.SelectMany(x => x.Elements("Type")).Select(x => x.Attribute("Resource").Value).ToHashSet(),
TypeLogic.NameToType.Where(a => !a.Value.IsEnumEntity()).Select(a => a.Key).ToHashSet(), typeReplacementKey);
replacements.AskForReplacements(
xRoles.SelectMany(x => x.Elements("Type")).SelectMany(t => t.Elements("Condition")).Select(x => x.Attribute("Name").Value).ToHashSet(),
SymbolLogic<TypeConditionSymbol>.AllUniqueKeys(),
typeConditionReplacementKey);
Func<string, TypeEntity?> getResource = s =>
{
Type? type = TypeLogic.NameToType.TryGetC(replacements.Apply(typeReplacementKey, s));
if (type == null)
return null;
return TypeLogic.TypeToEntity.GetOrThrow(type);
};
return Synchronizer.SynchronizeScript(Spacing.Double, should, current,
createNew: (role, x) =>
{
var dic = (from xr in x.Elements("Type")
let t = getResource(xr.Attribute("Resource").Value)
where t != null
select KeyValuePair.Create(t, new
{
Allowed = xr.Attribute("Allowed").Value.ToEnum<TypeAllowed>(),
Condition = Conditions(xr, replacements)
})).ToDictionaryEx("Type rules for {0}".FormatWith(role));
SqlPreCommand? restSql = dic.Select(kvp => table.InsertSqlSync(new RuleTypeEntity
{
Resource = kvp.Key,
Role = role,
Allowed = kvp.Value.Allowed,
Conditions = kvp.Value.Condition! /*CSBUG*/
}, comment: Comment(role, kvp.Key, kvp.Value.Allowed))).Combine(Spacing.Simple)?.Do(p => p.GoBefore = true);
return restSql;
},
removeOld: (role, list) => list.Select(rt => table.DeleteSqlSync(rt, null)).Combine(Spacing.Simple)?.Do(p => p.GoBefore = true),
mergeBoth: (role, x, list) =>
{
var dic = (from xr in x.Elements("Type")
let t = getResource(xr.Attribute("Resource").Value)
where t != null && !t.ToType().IsEnumEntity()
select KeyValuePair.Create(t, xr)).ToDictionaryEx("Type rules for {0}".FormatWith(role));
SqlPreCommand? restSql = Synchronizer.SynchronizeScript(
Spacing.Simple,
dic,
list.Where(a => a.Resource != null).ToDictionary(a => a.Resource),
createNew: (r, xr) =>
{
var a = xr.Attribute("Allowed").Value.ToEnum<TypeAllowed>();
var conditions = Conditions(xr, replacements);
return table.InsertSqlSync(new RuleTypeEntity { Resource = r, Role = role, Allowed = a, Conditions = conditions }, comment: Comment(role, r, a));
},
removeOld: (r, rt) => table.DeleteSqlSync(rt, null, Comment(role, r, rt.Allowed)),
mergeBoth: (r, xr, pr) =>
{
var oldA = pr.Allowed;
pr.Allowed = xr.Attribute("Allowed").Value.ToEnum<TypeAllowed>();
var conditions = Conditions(xr, replacements);
if (!pr.Conditions.SequenceEqual(conditions))
pr.Conditions = conditions;
return table.UpdateSqlSync(pr, null, comment: Comment(role, r, oldA, pr.Allowed));
})?.Do(p => p.GoBefore = true);
return restSql;
});
}
private static MList<RuleTypeConditionEmbedded> Conditions(XElement xr, Replacements replacements)
{
return (from xc in xr.Elements("Condition")
let cn = SymbolLogic<TypeConditionSymbol>.TryToSymbol(replacements.Apply(typeConditionReplacementKey, xc.Attribute("Name").Value))
where cn != null
select new RuleTypeConditionEmbedded
{
Condition = cn,
Allowed = xc.Attribute("Allowed").Value.ToEnum<TypeAllowed>()
}).ToMList();
}
internal static string Comment(Lite<RoleEntity> role, TypeEntity resource, TypeAllowed allowed)
{
return "{0} {1} for {2} ({3})".FormatWith(typeof(TypeEntity).NiceName(), resource.ToString(), role, allowed);
}
internal static string Comment(Lite<RoleEntity> role, TypeEntity resource, TypeAllowed from, TypeAllowed to)
{
return "{0} {1} for {2} ({3} -> {4})".FormatWith(typeof(TypeEntity).NiceName(), resource.ToString(), role, from, to);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework.Skinning;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
namespace OpenLiveWriter.ApplicationFramework
{
/// <summary>
/// Provides a tab pane lightweight control similar to (but cooler than) TabControl.
/// </summary>
public class TabLightweightControl : LightweightControl
{
#region Private Member Variables & Declarations
/// <summary>
/// The number of pixels to scroll for each auto scroll.
/// </summary>
private const int AUTO_SCROLL_DELTA = 3;
/// <summary>
/// WHEEL_DELTA, as specified in WinUser.h. Somehow Microsoft forgot this in the
/// SystemInformation class in .NET...
/// </summary>
private const int WHEEL_DELTA = 120;
/// <summary>
/// The minimum tab width, below which the tab selector area will not be displayed.
/// </summary>
private const int MINIMUM_TAB_WIDTH = 12;
/// <summary>
/// Pad space, in pixels. This value is used to provide a bit of "air" around the visual
/// elements of the tab lightweight control.
/// </summary>
internal const int PAD = 2;
/// <summary>
/// The tab inset, in pixels.
/// </summary>
private const int TAB_INSET = 4;
/// <summary>
/// The drag-and-drop tab selection delay.
/// </summary>
private const int DRAG_DROP_SELECTION_DELAY = 500;
/// <summary>
/// Required designer variable.
/// </summary>
private IContainer components;
/// <summary>
/// A value indicating whether tabs should be small.
/// </summary>
private bool smallTabs = false;
/// <summary>
/// A value which indicates whether side and bottom tab page borders will be drawn.
/// </summary>
private bool drawSideAndBottomTabPageBorders = true;
/// <summary>
/// A value indicating whether the tab selecter area is scrollable.
/// </summary>
private bool scrollableTabSelectorArea = false;
/// <summary>
/// A value indicating whether the tab selecter area will allow tab text/bitmaps to be clipped.
/// </summary>
private bool allowTabClipping = false;
/// <summary>
/// The tab entry list, sorted by tab number.
/// </summary>
private SortedList tabEntryList = new SortedList();
/// <summary>
/// The selected tab entry.
/// </summary>
private TabEntry selectedTabEntry = null;
/// <summary>
/// The tab page container control. This control is used to contain all the TabPageControls
/// that are added by calls to the SetTab method. Note that it's important that each
/// TabPageControl is properly sized and contained in the TabPageContainerControl. We use
/// Z order to display the right TabPageControl.
/// </summary>
private TabPageContainerControl tabPageContainerControl;
/// <summary>
/// The left tab scroller button.
/// </summary>
private TabScrollerButtonLightweightControl tabScrollerButtonLightweightControlLeft;
/// <summary>
/// The right tab scroller button.
/// </summary>
private TabScrollerButtonLightweightControl tabScrollerButtonLightweightControlRight;
/// <summary>
/// The tab selector area size.
/// </summary>
private Size tabSelectorAreaSize;
/// <summary>
/// The tab scroller position.
/// </summary>
private int tabScrollerPosition = 0;
/// <summary>
/// The DateTime of the last DragInside event.
/// </summary>
private DateTime dragInsideTime;
#endregion Private Member Variables & Declarations
#region Public Events
/// <summary>
/// Occurs when the SelectedTabNumber property changes.
/// </summary>
[
Category("Property Changed"),
Description("Occurs when the SelectedTabNumber property changes.")
]
public event EventHandler SelectedTabNumberChanged;
#endregion Public Events
#region Class Initialization & Termination
/// <summary>
/// Initializes a new instance of the TabLightweightControl class.
/// </summary>
public TabLightweightControl(IContainer container)
{
/// <summary>
/// Required for Windows.Forms Class Composition Designer support
/// </summary>
container.Add(this);
InitializeComponent();
}
/// <summary>
/// Initializes a new instance of the TabLightweightControl class.
/// </summary>
public TabLightweightControl()
{
/// <summary>
/// Required for Windows.Forms Class Composition Designer support
/// </summary>
InitializeComponent();
}
/// <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 Class Initialization & Termination
#region 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();
this.tabScrollerButtonLightweightControlLeft = new OpenLiveWriter.ApplicationFramework.TabScrollerButtonLightweightControl(this.components);
this.tabScrollerButtonLightweightControlRight = new OpenLiveWriter.ApplicationFramework.TabScrollerButtonLightweightControl(this.components);
this.tabPageContainerControl = new OpenLiveWriter.ApplicationFramework.TabPageContainerControl();
((System.ComponentModel.ISupportInitialize)(this.tabScrollerButtonLightweightControlLeft)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tabScrollerButtonLightweightControlRight)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// tabScrollerButtonLightweightControlLeft
//
this.tabScrollerButtonLightweightControlLeft.LightweightControlContainerControl = this;
this.tabScrollerButtonLightweightControlLeft.Scroll += new System.EventHandler(this.tabScrollerButtonLightweightControlLeft_Scroll);
this.tabScrollerButtonLightweightControlLeft.AutoScroll += new System.EventHandler(this.tabScrollerButtonLightweightControlLeft_AutoScroll);
//
// tabScrollerButtonLightweightControlRight
//
this.tabScrollerButtonLightweightControlRight.LightweightControlContainerControl = this;
this.tabScrollerButtonLightweightControlRight.Scroll += new System.EventHandler(this.tabScrollerButtonLightweightControlRight_Scroll);
this.tabScrollerButtonLightweightControlRight.AutoScroll += new System.EventHandler(this.tabScrollerButtonLightweightControlRight_AutoScroll);
//
// tabPageContainerControl
//
this.tabPageContainerControl.Location = new System.Drawing.Point(524, 17);
this.tabPageContainerControl.Name = "tabPageContainerControl";
this.tabPageContainerControl.TabIndex = 0;
//
// TabLightweightControl
//
this.AllowMouseWheel = true;
((System.ComponentModel.ISupportInitialize)(this.tabScrollerButtonLightweightControlLeft)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tabScrollerButtonLightweightControlRight)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
#region Public Methods & Properties
public bool ColorizeBorder
{
get
{
return _colorizeBorder;
}
set
{
_colorizeBorder = value;
}
}
private bool _colorizeBorder = true;
/// <summary>
/// Gets or sets a value indicating whether tabs should be small.
/// </summary>
[
Category("Appearance"),
DefaultValue(false),
Description("Specifies whether whether side and bottom tab page borders will be drawn.")
]
public bool SmallTabs
{
get
{
return smallTabs;
}
set
{
if (smallTabs != value)
{
smallTabs = value;
PerformLayout();
Invalidate();
}
}
}
/// <summary>
/// Gets or sets a value which indicates whether side and bottom tab page borders will be drawn.
/// </summary>
[
Category("Appearance"),
DefaultValue(true),
Description("Specifies whether whether side and bottom tab page borders will be drawn.")
]
public bool DrawSideAndBottomTabPageBorders
{
get
{
return drawSideAndBottomTabPageBorders;
}
set
{
if (drawSideAndBottomTabPageBorders != value)
{
drawSideAndBottomTabPageBorders = value;
PerformLayout();
Invalidate();
}
}
}
public override Size MinimumVirtualSize
{
get
{
// Not bothering to calculate minimum width, YAGNI.
return new Size(0, tabPageContainerControl.Location.Y + SelectedTab.MinimumSize.Height);
}
}
/// <summary>
/// Gets or sets a value indicating whether the tab selecter area is scrollable.
/// </summary>
[
Category("Appearance"),
DefaultValue(false),
Description("Specifies whether whether whether the tab selecter area is scrollable.")
]
public bool ScrollableTabSelectorArea
{
get
{
return scrollableTabSelectorArea;
}
set
{
Debug.Assert(!value, "'Scrollable tab selectors may not work correctly with bidi'");
if (scrollableTabSelectorArea != value)
{
scrollableTabSelectorArea = value;
PerformLayout();
Invalidate();
}
}
}
/// <summary>
/// Gets or sets whether the tab selecter area will allow tab text/bitmaps to be clipped.
/// If false, text or bitmaps will be dropped to shrink the tab size.
/// </summary>
[
Category("Appearance"),
DefaultValue(false),
Description("Specifies whether whether whether the tab selecter area is scrollable.")
]
public bool AllowTabClipping
{
get
{
return allowTabClipping;
}
set
{
if (allowTabClipping != value)
{
allowTabClipping = value;
PerformLayout();
Invalidate();
}
}
}
/// <summary>
/// Gets the tab count.
/// </summary>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int TabCount
{
get
{
return tabEntryList.Count;
}
}
/// <summary>
/// Gets or sets the index of the currently-selected tab page.
/// </summary>
public int SelectedTabNumber
{
get
{
return tabEntryList.IndexOfValue(SelectedTabEntry);
}
set
{
TabEntry tabEntry = (TabEntry)tabEntryList[value];
if (tabEntry != null)
SelectedTabEntry = tabEntry;
}
}
public TabPageControl GetTab(int i)
{
return ((TabEntry) tabEntryList[i]).TabPageControl;
}
/// <summary>
/// Gets the selected TabPageControl that was used to create the tab.
/// </summary>
public TabPageControl SelectedTab
{
get
{
return SelectedTabEntry.TabPageControl;
}
}
private void IncrementTab()
{
int currentIndex = SelectedTabNumber + 1;
if (currentIndex >= tabEntryList.Count )
currentIndex = 0;
TabEntry tabEntry = (TabEntry)tabEntryList[currentIndex];
if (tabEntry != null)
SelectedTabEntry = tabEntry;
}
private void DecrementTab()
{
int currentIndex = SelectedTabNumber - 1;
if (currentIndex < 0 )
currentIndex = tabEntryList.Count - 1;
TabEntry tabEntry = (TabEntry)tabEntryList[currentIndex];
if (tabEntry != null)
SelectedTabEntry = tabEntry;
}
public bool CheckForTabSwitch(Keys keyData)
{
if ((Control.ModifierKeys & Keys.Control) != 0)
{
Keys keys1 = keyData & Keys.KeyCode;
if (keys1 == Keys.Tab)
{
if ((Control.ModifierKeys & Keys.Shift) != 0)
{
DecrementTab();
}
else
{
IncrementTab();
}
return true;
}
}
return false;
}
/// <summary>
/// Sets a tab control.
/// </summary>
/// <param name="index">The tab index to set.</param>
/// <param name="tabPageControl">The tab page control to set.</param>
public void SetTab(int tabNumber, TabPageControl tabPageControl)
{
// If there already is a tab entry for the specified tab number, remove it.
RemoveTabEntry(tabNumber);
// Instantiate the new tab entry.
TabEntry tabEntry = new TabEntry(this, tabPageControl);
tabEntryList.Add(tabNumber, tabEntry);
tabPageContainerControl.Controls.Add(tabEntry.TabPageControl);
LightweightControls.Add(tabEntry.TabSelectorLightweightControl);
tabEntry.TabSelectorLightweightControl.DragInside += new DragEventHandler(TabSelectorLightweightControl_DragInside);
tabEntry.TabSelectorLightweightControl.DragOver += new DragEventHandler(TabSelectorLightweightControl_DragOver);
tabEntry.TabSelectorLightweightControl.Selected += new EventHandler(TabSelectorLightweightControl_Selected);
tabEntry.TabPageControl.VisibleChanged += new EventHandler(TabPageControl_VisibleChanged);
// Layout and invalidate.
PerformLayout();
Invalidate();
}
/// <summary>
/// Removes a tab control.
/// </summary>
/// <param name="tabNumber">The tab number to remove.</param>
public void RemoveTab(int tabNumber)
{
// Remove it.
RemoveTabEntry(tabNumber);
// Layout and invalidate.
PerformLayout();
Invalidate();
}
/// <summary>
/// Determines whether the specified tab number has been added.
/// </summary>
/// <param name="tabNumber">The tab number to look for.</param>
/// <returns>True if a tab has been added with the specified tab number; false otherwise.</returns>
public bool HasTab(int tabNumber)
{
return tabEntryList.Contains(tabNumber);
}
#endregion Public Methods & Properties
#region Internal Methods & Properties
/// <summary>
/// Gets the selected tab entry.
/// </summary>
internal TabEntry SelectedTabEntry
{
get
{
// Select the first tab entry, if there isn't a selected tab entry.
if (selectedTabEntry == null)
SelectedTabEntry = FirstTabEntry;
return selectedTabEntry;
}
set
{
if (selectedTabEntry != value)
{
if (selectedTabEntry != null)
selectedTabEntry.Unselected();
// Select the new tab entry.
selectedTabEntry = value;
if (selectedTabEntry != null)
selectedTabEntry.Selected();
PerformLayout();
Invalidate();
// Raise the SelectedTabNumberChanged event.
OnSelectedTabNumberChanged(EventArgs.Empty);
}
}
}
/// <summary>
/// Gets the first tab entry.
/// </summary>
internal TabEntry FirstTabEntry
{
get
{
return (tabEntryList.Count == 0) ? null : (TabEntry)tabEntryList.GetByIndex(0);
}
}
#endregion
#region Protected Event Overrides
/// <summary>
/// Raises the Layout event. The mother of all layout processing.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected override void OnLayout(EventArgs e)
{
// Call the base class's method so registered delegates receive the event.
base.OnLayout(e);
// No layout required if this control is not visible.
if (Parent == null)
return;
// If there are not tabs, layout processing is simple.
if (tabEntryList.Count == 0)
{
HideTabScrollerInterface();
tabSelectorAreaSize = new Size(0, 1);
return;
}
// Pre-process the layout of tab selectors.
int width = (TAB_INSET*2)+(PAD*4)+(PAD*(tabEntryList.Count-1)), height = 0;
foreach (TabEntry tabEntry in tabEntryList.Values)
{
if(!tabEntry.Hidden)
{
// Reset the tab selector and have it perform its layout logic so that it is at
// its natural size.
tabEntry.TabSelectorLightweightControl.SmallTabs = SmallTabs;
tabEntry.TabSelectorLightweightControl.ShowTabBitmap = true;
tabEntry.TabSelectorLightweightControl.ShowTabText = true;
tabEntry.TabSelectorLightweightControl.PerformLayout();
// If this tab selector is the tallest one we've seen, it sets a new high-
// water mark.
if (tabEntry.TabSelectorLightweightControl.UnselectedVirtualSize.Height > height)
height = tabEntry.TabSelectorLightweightControl.UnselectedVirtualSize.Height;
// Adjust the width to account for this tab selector.
width += tabEntry.TabSelectorLightweightControl.UnselectedVirtualSize.Width;
// Push the tabs closer together
width -= 6;
}
}
width += 6;
// Pad height.
height += PAD;
// If the tab selection area is scrollable, enable/disable the scroller interface.
if (scrollableTabSelectorArea)
{
// Set the tab selector area size.
tabSelectorAreaSize = new Size(width, height);
// If the entire tab selector area is visible, hide the tab scroller interface.
if (width <= VirtualWidth)
HideTabScrollerInterface();
else
{
// If the tab scroller position is zero, the left tab scroller button is not
// shown.
if (tabScrollerPosition == 0)
tabScrollerButtonLightweightControlLeft.Visible = false;
else
{
// Layout the left tab scroller button.
tabScrollerButtonLightweightControlLeft.VirtualBounds = new Rectangle( 0,
0,
tabScrollerButtonLightweightControlLeft.DefaultVirtualSize.Width,
tabSelectorAreaSize.Height);
tabScrollerButtonLightweightControlLeft.Visible = true;
tabScrollerButtonLightweightControlLeft.BringToFront();
}
// Layout the right tab scroller button.
if (tabScrollerPosition == MaximumTabScrollerPosition)
tabScrollerButtonLightweightControlRight.Visible = false;
else
{
int rightScrollerButtonWidth = tabScrollerButtonLightweightControlRight.DefaultVirtualSize.Width;
tabScrollerButtonLightweightControlRight.VirtualBounds = new Rectangle( TabAreaRectangle.Right-rightScrollerButtonWidth,
0,
rightScrollerButtonWidth,
tabSelectorAreaSize.Height);
tabScrollerButtonLightweightControlRight.Visible = true;
tabScrollerButtonLightweightControlRight.BringToFront();
}
}
}
else
{
// Hide the tab scroller interface.
HideTabScrollerInterface();
if (!allowTabClipping)
{
// If the entire tab selector area is not visible, switch into "no bitmap" mode.
if (width > VirtualWidth)
{
// Reset the width.
width = (TAB_INSET*2)+(PAD*4)+(PAD*(tabEntryList.Count-1));
// Re-process the layout of tab selectors.
foreach (TabEntry tabEntry in tabEntryList.Values)
{
if(!tabEntry.Hidden)
{
// Hide tab bitmap.
tabEntry.TabSelectorLightweightControl.ShowTabBitmap = false;
tabEntry.TabSelectorLightweightControl.ShowTabText = true;
tabEntry.TabSelectorLightweightControl.PerformLayout();
// Adjust the width to account for this tab selector.
width += tabEntry.TabSelectorLightweightControl.UnselectedVirtualSize.Width;
}
}
}
// If the entire tab selector area is not visible, switch into "no text except selected" mode.
if (width > VirtualWidth)
{
// Reset the width.
width = (TAB_INSET*2)+(PAD*4)+(PAD*(tabEntryList.Count-1));
// Re-process the layout of tab selectors.
foreach (TabEntry tabEntry in tabEntryList.Values)
{
if(!tabEntry.Hidden)
{
// Hide tab text.
tabEntry.TabSelectorLightweightControl.ShowTabBitmap = true;
tabEntry.TabSelectorLightweightControl.ShowTabText = tabEntry.IsSelected;
tabEntry.TabSelectorLightweightControl.PerformLayout();
// Adjust the width to account for this tab selector.
width += tabEntry.TabSelectorLightweightControl.UnselectedVirtualSize.Width;
}
}
}
// If the entire tab selector area is not visible, switch into "no text" mode.
if (width > VirtualWidth)
{
// Reset the width.
width = (TAB_INSET*2)+(PAD*4)+(PAD*(tabEntryList.Count-1));
// Re-process the layout of tab selectors.
foreach (TabEntry tabEntry in tabEntryList.Values)
{
if(!tabEntry.Hidden)
{
// Hide tab text.
tabEntry.TabSelectorLightweightControl.ShowTabBitmap = true;
tabEntry.TabSelectorLightweightControl.ShowTabText = false;
tabEntry.TabSelectorLightweightControl.PerformLayout();
// Adjust the width to account for this tab selector.
width += tabEntry.TabSelectorLightweightControl.UnselectedVirtualSize.Width;
}
}
}
// If the entire tab selector area is not visible, hide it.
if (width > VirtualWidth)
{
// Reset the width.
width = (TAB_INSET*2)+(PAD*4)+(PAD*(tabEntryList.Count-1));
// Re-process the layout of tab selectors.
foreach (TabEntry tabEntry in tabEntryList.Values)
{
if(!tabEntry.Hidden)
{
// Hide tab text.
tabEntry.TabSelectorLightweightControl.ShowTabBitmap = false;
tabEntry.TabSelectorLightweightControl.PerformLayout();
// Adjust the width to account for this tab selector.
width += tabEntry.TabSelectorLightweightControl.UnselectedVirtualSize.Width;
}
}
if (width > VirtualWidth)
height=1;
}
}
// Set the tab selector layout size.
tabSelectorAreaSize = new Size(width, height);
}
// Finally, actually layout the tab entries.
int x = TAB_INSET+(PAD*2);
TabEntry previousTabEntry = null;
foreach (TabEntry tabEntry in tabEntryList.Values)
{
if(!tabEntry.Hidden)
{
// Adjust the x offset for proper positioning of this tab and set the y offset,
// too. Now we know WHERE the tab will be laid out in the tab area.
if (previousTabEntry != null)
x += previousTabEntry.IsSelected ? -PAD + 1 : -1;
int y = Math.Max(0, tabSelectorAreaSize.Height-tabEntry.TabSelectorLightweightControl.VirtualBounds.Height);
// Latout the tab entry.
tabEntry.TabSelectorLightweightControl.VirtualLocation = new Point(x-tabScrollerPosition, y);
// Adjust the x offset to account for the tab entry.
x += tabEntry.TabSelectorLightweightControl.VirtualBounds.Width;
// Set the previous tab entry for the next loop iteration.
previousTabEntry = tabEntry;
}
}
// Set the bounds of the tab page control.
Rectangle tabPageControlBounds = VirtualClientRectangleToParent(TabPageRectangle);
if (tabPageContainerControl.Bounds != tabPageControlBounds)
tabPageContainerControl.Bounds = tabPageControlBounds;
// Make sure the selected tab entry and its TabPageControl are visible and at the top
// of the Z order and that, if there is one, the previously selected tab entry's
// TabPageControl is not visible.
if (SelectedTabEntry != null)
{
SelectedTabEntry.TabSelectorLightweightControl.BringToFront();
SelectedTabEntry.TabPageControl.BringToFront();
}
RtlLayoutFixup(true);
}
/// <summary>
/// Raises the LightweightControlContainerControlChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected override void OnLightweightControlContainerControlChanged(EventArgs e)
{
// Call the base class's method so that registered delegates receive the event.
base.OnLightweightControlContainerControlChanged(e);
// Set the tab page control's parent.
if (tabPageContainerControl.Parent != Parent)
tabPageContainerControl.Parent = Parent;
PerformLayout();
Invalidate();
}
/// <summary>
/// Raises the LightweightControlContainerControlVirtualLocationChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected override void OnLightweightControlContainerControlVirtualLocationChanged(EventArgs e)
{
// Call the base class's method so that registered delegates receive the event.
base.OnLightweightControlContainerControlVirtualLocationChanged(e);
// Layout and invalidate.
PerformLayout();
Invalidate();
}
/// <summary>
/// Raises the MouseWheel event.
/// </summary>
/// <param name="e">A MouseEventArgs that contains the event data.</param>
protected override void OnMouseWheel(MouseEventArgs e)
{
// Call the base class's method so that registered delegates receive the event.
base.OnMouseWheel(e);
// Scroll the tab layout area.
ScrollTabLayoutArea(-(e.Delta/WHEEL_DELTA)*ScrollDelta);
}
/// <summary>
/// Raises the Paint event.
/// </summary>
/// <param name="e">A PaintEventArgs that contains the event data.</param>
protected override void OnPaint(PaintEventArgs e)
{
// Draw the tab page border.
DrawTabPageBorders(e.Graphics);
// Call the base class's method so that registered delegates receive the event.
base.OnPaint(e);
}
/// <summary>
/// Raises the VirtualLocationChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected override void OnVirtualLocationChanged(EventArgs e)
{
// Call the base class's method so that registered delegates receive the event.
base.OnVirtualLocationChanged(e);
// Layout and invalidate.
PerformLayout();
Invalidate();
}
#endregion Protected Event Overrides
#region Protected Events
/// <summary>
/// Raises the SelectedTabNumberChanged event.
/// </summary>
/// <param name="e">An EventArgs that contains the event data.</param>
protected virtual void OnSelectedTabNumberChanged(EventArgs e)
{
if (SelectedTabNumberChanged != null)
SelectedTabNumberChanged(this, e);
}
#endregion
#region Private Methods & Properties
/// <summary>
/// Helper to remove a tab entry.
/// </summary>
/// <param name="tabNumber">The tab number of the tab entry to remove.</param>
private void RemoveTabEntry(int tabNumber)
{
// Locate the tab entry for the specified tab number. It it's found, remove it.
TabEntry tabEntry = (TabEntry)tabEntryList[tabNumber];
if (tabEntry != null)
{
if (SelectedTabEntry == tabEntry)
SelectedTabEntry = FirstTabEntry;
tabPageContainerControl.Controls.Remove(tabEntry.TabPageControl);
LightweightControls.Remove(tabEntry.TabSelectorLightweightControl);
tabEntryList.Remove(tabNumber);
}
}
/// <summary>
/// Gets or sets the tab scroller position.
/// </summary>
private int TabScrollerPosition
{
get
{
return tabScrollerPosition;
}
set
{
tabScrollerPosition = MathHelper.Clip(value, 0, MaximumTabScrollerPosition);
}
}
/// <summary>
/// Gets the tab area rectangle. This is the entire area available for tab and tab
/// scroller button layout.
/// </summary>
private Rectangle TabAreaRectangle
{
get
{
return new Rectangle( 0,
0,
VirtualWidth,
tabSelectorAreaSize.Height);
}
}
/// <summary>
/// Gets the tab page border rectangle.
/// </summary>
private Rectangle TabPageBorderRectangle
{
get
{
return new Rectangle( 0,
tabSelectorAreaSize.Height-1,
VirtualWidth,
VirtualHeight-(tabSelectorAreaSize.Height-1));
}
}
/// <summary>
/// Gets the tab page rectangle.
/// </summary>
private Rectangle TabPageRectangle
{
get
{
int border = drawSideAndBottomTabPageBorders ? 1 : 0;
return new Rectangle( border,
tabSelectorAreaSize.Height+border,
VirtualWidth-(border*2),
VirtualHeight-(tabSelectorAreaSize.Height+(border*2)));
}
}
/// <summary>
/// Gets the maximum tab scroller position.
/// </summary>
private int MaximumTabScrollerPosition
{
get
{
return Math.Max(0, tabSelectorAreaSize.Width-TabAreaRectangle.Width);
}
}
/// <summary>
/// Gets the scroll delta, or how many pixels to scroll the tab area.
/// </summary>
private int ScrollDelta
{
get
{
return TabAreaRectangle.Width/8;
}
}
/// <summary>
/// Hides the tab scroller interface.
/// </summary>
private void HideTabScrollerInterface()
{
tabScrollerPosition = 0;
tabScrollerButtonLightweightControlLeft.Visible = false;
tabScrollerButtonLightweightControlRight.Visible = false;
}
/// <summary>
/// Draws the tab page border.
/// </summary>
/// <param name="graphics">Graphics context where the tab page border is to be drawn.</param>
private void DrawTabPageBorders(Graphics graphics)
{
Color c = SystemColors.ControlDark;
if (_colorizeBorder)
c = ColorizedResources.Instance.BorderLightColor;
// Draw tab page borders.
using (SolidBrush borderBrush = new SolidBrush(c))
{
// Obtain the tab page border rectangle.
Rectangle tabPageBorderRectangle = TabPageBorderRectangle;
// Draw the top edge.
graphics.FillRectangle( borderBrush,
tabPageBorderRectangle.X,
tabPageBorderRectangle.Y,
tabPageBorderRectangle.Width,
1);
// Draw the highlight under the top edge.
using (SolidBrush highlightBrush = new SolidBrush(Color.FromArgb(206, 219, 248)))
{
graphics.FillRectangle( highlightBrush,
tabPageBorderRectangle.X,
tabPageBorderRectangle.Y+1,
tabPageBorderRectangle.Width,
1);
}
// Draw tab page borders, if we should.
if (drawSideAndBottomTabPageBorders)
{
// Draw the left edge.
graphics.FillRectangle( borderBrush,
tabPageBorderRectangle.X,
tabPageBorderRectangle.Y+1,
1,
tabPageBorderRectangle.Height-1);
// Draw the right edge.
graphics.FillRectangle( borderBrush,
tabPageBorderRectangle.Right-1,
tabPageBorderRectangle.Y+1,
1,
tabPageBorderRectangle.Height-1);
// Draw the bottom edge.
graphics.FillRectangle( borderBrush,
tabPageBorderRectangle.X+1,
tabPageBorderRectangle.Bottom-1,
tabPageBorderRectangle.Width-2,
1);
}
}
}
/// <summary>
/// TabSelectorLightweightControl_DragInside event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void TabSelectorLightweightControl_DragInside(object sender, DragEventArgs e)
{
// Note the DateTime of the last DragInside event.
dragInsideTime = DateTime.Now;
}
/// <summary>
/// TabSelectorLightweightControl_DragInside event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void TabSelectorLightweightControl_DragOver(object sender, DragEventArgs e)
{
// Wait an amount of time before selecting the tab page.
if (DateTime.Now.Subtract(dragInsideTime).Milliseconds < DRAG_DROP_SELECTION_DELAY)
return;
// Ensure that the sender is who we think it is.
Debug.Assert(sender is TabSelectorLightweightControl, "Doh!", "Bad event wiring is the leading cause of code decay. Call Brian.");
if (sender is TabSelectorLightweightControl)
{
// Set the selected tab entry, if we should.
TabSelectorLightweightControl tabSelectorLightweightControl = (TabSelectorLightweightControl)sender;
if (tabSelectorLightweightControl.TabEntry.TabPageControl.DragDropSelectable && SelectedTabEntry != tabSelectorLightweightControl.TabEntry)
SelectedTabEntry = tabSelectorLightweightControl.TabEntry;
}
}
/// <summary>
/// TabSelectorLightweightControl_Selected event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void TabSelectorLightweightControl_Selected(object sender, EventArgs e)
{
// Ensure that the sender is who we think it is.
Debug.Assert(sender is TabSelectorLightweightControl, "Doh!", "Bad event wiring is the leading cause of code decay. Call Brian.");
if (sender is TabSelectorLightweightControl)
{
// Set the selected tab entry.
TabSelectorLightweightControl tabSelectorLightweightControl = (TabSelectorLightweightControl)sender;
SelectedTabEntry = tabSelectorLightweightControl.TabEntry;
}
}
private void TabPageControl_VisibleChanged(object sender, EventArgs e)
{
PerformLayout();
Invalidate();
}
/// <summary>
/// tabScrollerButtonLightweightControlLeft_Scroll event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void tabScrollerButtonLightweightControlLeft_Scroll(object sender, EventArgs e)
{
ScrollTabLayoutArea(-ScrollDelta);
}
/// <summary>
/// tabScrollerButtonLightweightControlRight_Scroll event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void tabScrollerButtonLightweightControlRight_Scroll(object sender, EventArgs e)
{
ScrollTabLayoutArea(ScrollDelta);
}
/// <summary>
/// tabScrollerButtonLightweightControlLeft_AutoScroll event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void tabScrollerButtonLightweightControlLeft_AutoScroll(object sender, EventArgs e)
{
ScrollTabLayoutArea(-AUTO_SCROLL_DELTA);
}
/// <summary>
/// tabScrollerButtonLightweightControlRight_AutoScroll event handler.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">An EventArgs that contains the event data.</param>
private void tabScrollerButtonLightweightControlRight_AutoScroll(object sender, EventArgs e)
{
ScrollTabLayoutArea(AUTO_SCROLL_DELTA);
}
/// <summary>
/// Scrolls the tab layout area.
/// </summary>
/// <param name="delta">Scroll delta. This value does not have to take scroll limits into
/// account as the TabScrollerPosition property handles this.</param>
private void ScrollTabLayoutArea(int delta)
{
// If we have a scrollable tab layout area, scroll it.
if (ScrollableTabSelectorArea)
{
// Adjust the tab scroller position.
TabScrollerPosition += delta;
// Get the screen up to date.
PerformLayout();
Invalidate();
Update();
}
}
#endregion Private Methods & Properties
#region Accessibility
protected override void AddAccessibleControlsToList(ArrayList list)
{
for(int i=0; i<TabCount; i++)
{
TabEntry tabEntry = (TabEntry)tabEntryList[i];
list.Add(tabEntry.TabSelectorLightweightControl);
}
base.AddAccessibleControlsToList(list);
}
#endregion
}
}
| |
// ****************************************************************
// Copyright 2008, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
namespace NUnit.Core.Extensibility
{
/// <summary>
/// ParameterSet encapsulates method arguments and
/// other selected parameters needed for constructing
/// a parameterized test case.
/// </summary>
public class ParameterSet : NUnit.Framework.ITestCaseData
{
#region Constants
private static readonly string DESCRIPTION = "_DESCRIPTION";
//private static readonly string IGNOREREASON = "_IGNOREREASON";
private static readonly string CATEGORIES = "_CATEGORIES";
#endregion
#region Instance Fields
private RunState runState;
private Exception providerException;
private object[] arguments;
private object[] originalArguments;
private System.Type expectedExceptionType;
private string expectedExceptionName;
private string expectedMessage;
private string matchType;
private object expectedResult;
private string testName;
private string ignoreReason;
private bool isIgnored;
private bool isExplicit;
private bool hasExpectedResult;
/// <summary>
/// A dictionary of properties, used to add information
/// to tests without requiring the class to change.
/// </summary>
private IDictionary properties;
#endregion
#region Properties
/// <summary>
/// The RunState for this set of parameters.
/// </summary>
public RunState RunState
{
get { return runState; }
set { runState = value; }
}
///// <summary>
///// The reason for not running the test case
///// represented by this ParameterSet
///// </summary>
//public string NotRunReason
//{
// get { return (string) Properties[IGNOREREASON]; }
//}
/// <summary>
/// Holds any exception thrown by the parameter provider
/// </summary>
public Exception ProviderException
{
get { return providerException; }
}
/// <summary>
/// The arguments to be used in running the test,
/// which must match the method signature.
/// </summary>
public object[] Arguments
{
get { return arguments; }
set
{
arguments = value;
if (originalArguments == null)
originalArguments = value;
}
}
/// <summary>
/// The original arguments supplied by the user,
/// used for display purposes.
/// </summary>
public object[] OriginalArguments
{
get { return originalArguments; }
}
/// <summary>
/// The Type of any exception that is expected.
/// </summary>
public System.Type ExpectedException
{
get { return expectedExceptionType; }
set { expectedExceptionType = value; }
}
/// <summary>
/// The FullName of any exception that is expected
/// </summary>
public string ExpectedExceptionName
{
get { return expectedExceptionName; }
set { expectedExceptionName = value; }
}
/// <summary>
/// The Message of any exception that is expected
/// </summary>
public string ExpectedMessage
{
get { return expectedMessage; }
set { expectedMessage = value; }
}
/// <summary>
/// Gets or sets the type of match to be performed on the expected message
/// </summary>
public string MatchType
{
get { return matchType; }
set { matchType = value; }
}
/// <summary>
/// The expected result of the test, which
/// must match the method return type.
/// </summary>
public object Result
{
get { return expectedResult; }
set
{
expectedResult = value;
hasExpectedResult = true;
}
}
/// <summary>
/// Returns true if an expected result has been
/// specified for this parameter set.
/// </summary>
public bool HasExpectedResult
{
get { return hasExpectedResult; }
}
/// <summary>
/// A description to be applied to this test case
/// </summary>
public string Description
{
get { return (string) Properties[DESCRIPTION]; }
set
{
if (value != null)
Properties[DESCRIPTION] = value;
else
Properties.Remove(DESCRIPTION);
}
}
/// <summary>
/// A name to be used for this test case in lieu
/// of the standard generated name containing
/// the argument list.
/// </summary>
public string TestName
{
get { return testName; }
set { testName = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ParameterSet"/> is ignored.
/// </summary>
/// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value>
public bool Ignored
{
get { return isIgnored; }
set { isIgnored = value; }
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ParameterSet"/> is explicit.
/// </summary>
/// <value><c>true</c> if explicit; otherwise, <c>false</c>.</value>
public bool Explicit
{
get { return isExplicit; }
set { isExplicit = value; }
}
/// <summary>
/// Gets or sets the ignore reason.
/// </summary>
/// <value>The ignore reason.</value>
public string IgnoreReason
{
get { return ignoreReason; }
set { ignoreReason = value; }
}
/// <summary>
/// Gets a list of categories associated with this test.
/// </summary>
public IList Categories
{
get
{
if (Properties[CATEGORIES] == null)
Properties[CATEGORIES] = new ArrayList();
return (IList)Properties[CATEGORIES];
}
}
/// <summary>
/// Gets the property dictionary for this test
/// </summary>
public IDictionary Properties
{
get
{
if (properties == null)
properties = new ListDictionary();
return properties;
}
}
#endregion
#region Constructors
/// <summary>
/// Construct a non-runnable ParameterSet, specifying
/// the provider excetpion that made it invalid.
/// </summary>
public ParameterSet(Exception exception)
{
this.runState = RunState.NotRunnable;
this.providerException = exception;
this.ignoreReason = exception.Message;
}
/// <summary>
/// Construct an empty parameter set, which
/// defaults to being Runnable.
/// </summary>
public ParameterSet()
{
this.runState = RunState.Runnable;
}
#endregion
#region Static Methods
/// <summary>
/// Constructs a ParameterSet from another object, accessing properties
/// by reflection. The object must expose at least an Arguments property
/// in order for the test to be runnable.
/// </summary>
/// <param name="source"></param>
public static ParameterSet FromDataSource(object source)
{
ParameterSet parms = new ParameterSet();
parms.Arguments = GetParm(source, PropertyNames.Arguments) as object[];
parms.ExpectedException = GetParm(source, PropertyNames.ExpectedException) as Type;
if (parms.ExpectedException != null)
parms.ExpectedExceptionName = parms.ExpectedException.FullName;
else
parms.ExpectedExceptionName = GetParm(source, PropertyNames.ExpectedExceptionName) as string;
parms.ExpectedMessage = GetParm(source, PropertyNames.ExpectedMessage) as string;
object matchEnum = GetParm(source, PropertyNames.MatchType);
if ( matchEnum != null )
parms.MatchType = matchEnum.ToString();
// Note: pre-2.6 versions of some attributes don't have the HasExpectedResult property
object hasResult = GetParm(source, PropertyNames.HasExpectedResult);
object expectedResult = GetParm(source, PropertyNames.ExpectedResult);
if (hasResult != null && (bool)hasResult || expectedResult != null)
parms.Result = expectedResult;
parms.Description = GetParm(source, PropertyNames.Description) as string;
parms.TestName = GetParm(source, PropertyNames.TestName) as string;
object objIgnore = GetParm(source, PropertyNames.Ignored);
if (objIgnore != null)
parms.Ignored = (bool)objIgnore;
parms.IgnoreReason = GetParm(source, PropertyNames.IgnoreReason) as string;
object objExplicit = GetParm(source, PropertyNames.Explicit);
if (objExplicit != null)
parms.Explicit = (bool)objExplicit;
// Some sources may also implement Properties and/or Categories
bool gotCategories = false;
IDictionary props = GetParm(source, PropertyNames.Properties) as IDictionary;
if ( props != null )
foreach (string key in props.Keys)
{
parms.Properties.Add(key, props[key]);
if (key == CATEGORIES) gotCategories = true;
}
// Some sources implement Categories. They may have been
// provided as properties or they may be separate.
if (!gotCategories)
{
IList categories = GetParm(source, PropertyNames.Categories) as IList;
if (categories != null)
foreach (string cat in categories)
parms.Categories.Add(cat);
}
return parms;
}
private static object GetParm(object source, string name)
{
Type type = source.GetType();
PropertyInfo prop = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty);
if (prop != null)
return prop.GetValue(source, null);
FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetField);
if (field != null)
return field.GetValue(source);
return null;
}
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
using JetBrains.Annotations;
// ReSharper disable InconsistentNaming
// ReSharper disable FieldCanBeMadeReadOnly.Global
namespace Microsoft.Win32.TaskScheduler.V1Interop
{
#pragma warning disable CS0618 // Type or member is obsolete
#region class HRESULT -- Values peculiar to the task scheduler.
internal class HResult
{
// The task is ready to run at its next scheduled time.
public const int SCHED_S_TASK_READY = 0x00041300;
// The task is currently running.
public const int SCHED_S_TASK_RUNNING = 0x00041301;
// The task will not run at the scheduled times because it has been disabled.
public const int SCHED_S_TASK_DISABLED = 0x00041302;
// The task has not yet run.
public const int SCHED_S_TASK_HAS_NOT_RUN = 0x00041303;
// There are no more runs scheduled for this task.
public const int SCHED_S_TASK_NO_MORE_RUNS = 0x00041304;
// One or more of the properties that are needed to run this task on a schedule have not been set.
public const int SCHED_S_TASK_NOT_SCHEDULED = 0x00041305;
// The last run of the task was terminated by the user.
public const int SCHED_S_TASK_TERMINATED = 0x00041306;
// Either the task has no triggers or the existing triggers are disabled or not set.
public const int SCHED_S_TASK_NO_VALID_TRIGGERS = 0x00041307;
// Event triggers don't have set run times.
public const int SCHED_S_EVENT_TRIGGER = 0x00041308;
// Trigger not found.
public const int SCHED_E_TRIGGER_NOT_FOUND = unchecked((int)0x80041309);
// One or more of the properties that are needed to run this task have not been set.
public const int SCHED_E_TASK_NOT_READY = unchecked((int)0x8004130A);
// There is no running instance of the task to terminate.
public const int SCHED_E_TASK_NOT_RUNNING = unchecked((int)0x8004130B);
// The Task Scheduler Service is not installed on this computer.
public const int SCHED_E_SERVICE_NOT_INSTALLED = unchecked((int)0x8004130C);
// The task object could not be opened.
public const int SCHED_E_CANNOT_OPEN_TASK = unchecked((int)0x8004130D);
// The object is either an invalid task object or is not a task object.
public const int SCHED_E_INVALID_TASK = unchecked((int)0x8004130E);
// No account information could be found in the Task Scheduler security database for the task indicated.
public const int SCHED_E_ACCOUNT_INFORMATION_NOT_SET = unchecked((int)0x8004130F);
// Unable to establish existence of the account specified.
public const int SCHED_E_ACCOUNT_NAME_NOT_FOUND = unchecked((int)0x80041310);
// Corruption was detected in the Task Scheduler security database; the database has been reset.
public const int SCHED_E_ACCOUNT_DBASE_CORRUPT = unchecked((int)0x80041311);
// Task Scheduler security services are available only on Windows NT.
public const int SCHED_E_NO_SECURITY_SERVICES = unchecked((int)0x80041312);
// The task object version is either unsupported or invalid.
public const int SCHED_E_UNKNOWN_OBJECT_VERSION = unchecked((int)0x80041313);
// The task has been configured with an unsupported combination of account settings and run time options.
public const int SCHED_E_UNSUPPORTED_ACCOUNT_OPTION = unchecked((int)0x80041314);
// The Task Scheduler Service is not running.
public const int SCHED_E_SERVICE_NOT_RUNNING = unchecked((int)0x80041315);
// The Task Scheduler service must be configured to run in the System account to function properly. Individual tasks may be configured to run in other accounts.
public const int SCHED_E_SERVICE_NOT_LOCALSYSTEM = unchecked((int)0x80041316);
}
#endregion
#region Enums
/// <summary>
/// Options for a task, used for the Flags property of a Task. Uses the
/// "Flags" attribute, so these values are combined with |.
/// Some flags are documented as Windows 95 only, but they have a
/// user interface in Windows XP so that may not be true.
/// </summary>
[Flags]
internal enum TaskFlags
{
/// <summary>
/// The interactive flag is set if the task is intended to be displayed to the user.
/// If the flag is not set, no user interface associated with the task is presented
/// to the user when the task is executed.
/// </summary>
Interactive = 0x1,
/// <summary>
/// The task will be deleted when there are no more scheduled run times.
/// </summary>
DeleteWhenDone = 0x2,
/// <summary>
/// The task is disabled. This is useful to temporarily prevent a task from running
/// at the scheduled time(s).
/// </summary>
Disabled = 0x4,
/// <summary>
/// The task begins only if the computer is not in use at the scheduled start time. Windows 95 only.
/// </summary>
StartOnlyIfIdle = 0x10,
/// <summary>
/// The task terminates if the computer makes an idle to non-idle transition while the task is running.
/// The computer is not considered idle until the IdleWait triggers' time elapses with no user input.
/// Windows 95 only. For information regarding idle triggers, see <see cref="IdleTrigger"/>.
/// </summary>
KillOnIdleEnd = 0x20,
/// <summary>
/// The task does not start if its target computer is running on battery power. Windows 95 only.
/// </summary>
DontStartIfOnBatteries = 0x40,
/// <summary>
/// The task ends, and the associated application quits if the task's target computer switches
/// to battery power. Windows 95 only.
/// </summary>
KillIfGoingOnBatteries = 0x80,
/// <summary>
/// The task runs only if the system is docked. Windows 95 only.
/// </summary>
RunOnlyIfDocked = 0x100,
/// <summary>
/// The work item created will be hidden.
/// </summary>
Hidden = 0x200,
/// <summary>
/// The task runs only if there is currently a valid Internet connection.
/// This feature is currently not implemented.
/// </summary>
RunIfConnectedToInternet = 0x400,
/// <summary>
/// The task starts again if the computer makes a non-idle to idle transition before all the
/// task's task_triggers elapse. (Use this flag in conjunction with KillOnIdleEnd.) Windows 95 only.
/// </summary>
RestartOnIdleResume = 0x800,
/// <summary>
/// The task runs only if the SYSTEM account is available.
/// </summary>
SystemRequired = 0x1000,
/// <summary>
/// The task runs only if the user specified in SetAccountInformation is logged on interactively.
/// This flag has no effect on work items set to run in the local account.
/// </summary>
RunOnlyIfLoggedOn = 0x2000
}
/// <summary>
/// Status values returned for a task. Some values have been determined to occur although
/// they do no appear in the Task Scheduler system documentation.
/// </summary>
internal enum TaskStatus
{
/// <summary>The task is ready to run at its next scheduled time.</summary>
Ready = HResult.SCHED_S_TASK_READY,
/// <summary>The task is currently running.</summary>
Running = HResult.SCHED_S_TASK_RUNNING,
/// <summary>One or more of the properties that are needed to run this task on a schedule have not been set. </summary>
NotScheduled = HResult.SCHED_S_TASK_NOT_SCHEDULED,
/// <summary>The task has not yet run.</summary>
NeverRun = HResult.SCHED_S_TASK_HAS_NOT_RUN,
/// <summary>The task will not run at the scheduled times because it has been disabled.</summary>
Disabled = HResult.SCHED_S_TASK_DISABLED,
/// <summary>There are no more runs scheduled for this task.</summary>
NoMoreRuns = HResult.SCHED_S_TASK_NO_MORE_RUNS,
/// <summary>The last run of the task was terminated by the user.</summary>
Terminated = HResult.SCHED_S_TASK_TERMINATED,
/// <summary>Either the task has no triggers or the existing triggers are disabled or not set.</summary>
NoTriggers = HResult.SCHED_S_TASK_NO_VALID_TRIGGERS,
/// <summary>Event triggers don't have set run times.</summary>
NoTriggerTime = HResult.SCHED_S_EVENT_TRIGGER
}
/// <summary>Valid types of triggers</summary>
internal enum TaskTriggerType
{
/// <summary>Trigger is set to run the task a single time. </summary>
RunOnce = 0,
/// <summary>Trigger is set to run the task on a daily interval. </summary>
RunDaily = 1,
/// <summary>Trigger is set to run the work item on specific days of a specific week of a specific month. </summary>
RunWeekly = 2,
/// <summary>Trigger is set to run the task on a specific day(s) of the month.</summary>
RunMonthly = 3,
/// <summary>Trigger is set to run the task on specific days, weeks, and months.</summary>
RunMonthlyDOW = 4,
/// <summary>Trigger is set to run the task if the system remains idle for the amount of time specified by the idle wait time of the task.</summary>
OnIdle = 5,
/// <summary>Trigger is set to run the task at system startup.</summary>
OnSystemStart = 6,
/// <summary>Trigger is set to run the task when a user logs on. </summary>
OnLogon = 7
}
[Flags]
internal enum TaskTriggerFlags : uint
{
HasEndDate = 0x1,
KillAtDurationEnd = 0x2,
Disabled = 0x4
}
#endregion
#region Structs
[StructLayout(LayoutKind.Sequential)]
internal struct Daily
{
public ushort DaysInterval;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Weekly
{
public ushort WeeksInterval;
public DaysOfTheWeek DaysOfTheWeek;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MonthlyDate
{
public uint Days;
public MonthsOfTheYear Months;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MonthlyDOW
{
public ushort WhichWeek;
public DaysOfTheWeek DaysOfTheWeek;
public MonthsOfTheYear Months;
public WhichWeek V2WhichWeek
{
get
{
return (WhichWeek)(1 << ((short)WhichWeek - 1));
}
set
{
int idx = Array.IndexOf(new short[] { 0x1, 0x2, 0x4, 0x8, 0x10 }, (short)value);
if (idx >= 0)
WhichWeek = (ushort)(idx + 1);
else
throw new NotV1SupportedException("Only a single week can be set with Task Scheduler 1.0.");
}
}
}
[StructLayout(LayoutKind.Explicit)]
internal struct TriggerTypeData
{
[FieldOffset(0)]
public Daily daily;
[FieldOffset(0)]
public Weekly weekly;
[FieldOffset(0)]
public MonthlyDate monthlyDate;
[FieldOffset(0)]
public MonthlyDOW monthlyDOW;
}
[StructLayout(LayoutKind.Sequential)]
internal struct TaskTrigger
{
public ushort TriggerSize; // Structure size.
public ushort Reserved1; // Reserved. Must be zero.
public ushort BeginYear; // Trigger beginning date year.
public ushort BeginMonth; // Trigger beginning date month.
public ushort BeginDay; // Trigger beginning date day.
public ushort EndYear; // Optional trigger ending date year.
public ushort EndMonth; // Optional trigger ending date month.
public ushort EndDay; // Optional trigger ending date day.
public ushort StartHour; // Run bracket start time hour.
public ushort StartMinute; // Run bracket start time minute.
public uint MinutesDuration; // Duration of run bracket.
public uint MinutesInterval; // Run bracket repetition interval.
public TaskTriggerFlags Flags; // Trigger flags.
public TaskTriggerType Type; // Trigger type.
public TriggerTypeData Data; // Trigger data peculiar to this type (union).
public ushort Reserved2; // Reserved. Must be zero.
public ushort RandomMinutesInterval; // Maximum number of random minutes after start time.
public DateTime BeginDate
{
get { try { return BeginYear == 0 ? DateTime.MinValue : new DateTime(BeginYear, BeginMonth, BeginDay, StartHour, StartMinute, 0, DateTimeKind.Unspecified); } catch { return DateTime.MinValue; } }
set
{
if (value != DateTime.MinValue)
{
DateTime local = value.Kind == DateTimeKind.Utc ? value.ToLocalTime() : value;
BeginYear = (ushort)local.Year;
BeginMonth = (ushort)local.Month;
BeginDay = (ushort)local.Day;
StartHour = (ushort)local.Hour;
StartMinute = (ushort)local.Minute;
}
else
BeginYear = BeginMonth = BeginDay = StartHour = StartMinute = 0;
}
}
public DateTime? EndDate
{
get { try { return EndYear == 0 ? (DateTime?)null : new DateTime(EndYear, EndMonth, EndDay); } catch { return DateTime.MaxValue; } }
set
{
if (value.HasValue)
{
EndYear = (ushort)value.Value.Year;
EndMonth = (ushort)value.Value.Month;
EndDay = (ushort)value.Value.Day;
Flags |= TaskTriggerFlags.HasEndDate;
}
else
{
EndYear = EndMonth = EndDay = 0;
Flags &= ~TaskTriggerFlags.HasEndDate;
}
}
}
public override string ToString() => $"Trigger Type: {Type};\n> Start: {BeginDate}; End: {(EndYear == 0 ? "null" : EndDate?.ToString())};\n> DurMin: {MinutesDuration}; DurItv: {MinutesInterval};\n>";
}
#endregion
[ComImport, Guid("148BD527-A2AB-11CE-B11F-00AA00530503"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), System.Security.SuppressUnmanagedCodeSecurity, CoClass(typeof(CTaskScheduler))]
internal interface ITaskScheduler
{
void SetTargetComputer([In, MarshalAs(UnmanagedType.LPWStr)] string Computer);
CoTaskMemString GetTargetComputer();
[return: MarshalAs(UnmanagedType.Interface)]
IEnumWorkItems Enum();
[return: MarshalAs(UnmanagedType.Interface)]
ITask Activate([In, MarshalAs(UnmanagedType.LPWStr)][NotNull] string Name, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid);
void Delete([In, MarshalAs(UnmanagedType.LPWStr)][NotNull] string Name);
[return: MarshalAs(UnmanagedType.Interface)]
ITask NewWorkItem([In, MarshalAs(UnmanagedType.LPWStr)][NotNull] string TaskName, [In, MarshalAs(UnmanagedType.LPStruct)] Guid rclsid, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid);
void AddWorkItem([In, MarshalAs(UnmanagedType.LPWStr)][NotNull] string TaskName, [In, MarshalAs(UnmanagedType.Interface)] ITask WorkItem);
void IsOfType([In, MarshalAs(UnmanagedType.LPWStr)][NotNull] string TaskName, [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid);
}
[Guid("148BD528-A2AB-11CE-B11F-00AA00530503"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), System.Security.SuppressUnmanagedCodeSecurity]
internal interface IEnumWorkItems
{
[PreserveSig()]
//int Next([In] uint celt, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 0)] out string[] rgpwszNames, [Out] out uint pceltFetched);
int Next([In] uint RequestCount, [Out] out IntPtr Names, [Out] out uint Fetched);
void Skip([In] uint Count);
void Reset();
[return: MarshalAs(UnmanagedType.Interface)]
IEnumWorkItems Clone();
}
#if WorkItem
// The IScheduledWorkItem interface is actually never used because ITask inherits all of its
// methods. As ITask is the only kind of WorkItem (in 2002) it is the only interface we need.
[Guid("a6b952f0-a4b1-11d0-997d-00aa006887ec"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IScheduledWorkItem
{
void CreateTrigger([Out] out ushort NewTriggerIndex, [Out, MarshalAs(UnmanagedType.Interface)] out ITaskTrigger Trigger);
void DeleteTrigger([In] ushort TriggerIndex);
void GetTriggerCount([Out] out ushort Count);
void GetTrigger([In] ushort TriggerIndex, [Out, MarshalAs(UnmanagedType.Interface)] out ITaskTrigger Trigger);
void GetTriggerString([In] ushort TriggerIndex, out System.IntPtr TriggerString);
void GetRunTimes([In, MarshalAs(UnmanagedType.Struct)] SystemTime Begin, [In, MarshalAs(UnmanagedType.Struct)] SystemTime End, ref ushort Count, [Out] out System.IntPtr TaskTimes);
void GetNextRunTime([In, Out, MarshalAs(UnmanagedType.Struct)] ref SystemTime NextRun);
void SetIdleWait([In] ushort IdleMinutes, [In] ushort DeadlineMinutes);
void GetIdleWait([Out] out ushort IdleMinutes, [Out] out ushort DeadlineMinutes);
void Run();
void Terminate();
void EditWorkItem([In] uint hParent, [In] uint dwReserved);
void GetMostRecentRunTime([In, Out, MarshalAs(UnmanagedType.Struct)] ref SystemTime LastRun);
void GetStatus([Out, MarshalAs(UnmanagedType.Error)] out int Status);
void GetExitCode([Out] out uint ExitCode);
void SetComment([In, MarshalAs(UnmanagedType.LPWStr)] string Comment);
void GetComment(out System.IntPtr Comment);
void SetCreator([In, MarshalAs(UnmanagedType.LPWStr)] string Creator);
void GetCreator(out System.IntPtr Creator);
void SetWorkItemData([In] ushort DataLen, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0, ArraySubType=UnmanagedType.U1)] byte[] Data);
void GetWorkItemData([Out] out ushort DataLen, [Out] out System.IntPtr Data);
void SetErrorRetryCount([In] ushort RetryCount);
void GetErrorRetryCount([Out] out ushort RetryCount);
void SetErrorRetryInterval([In] ushort RetryInterval);
void GetErrorRetryInterval([Out] out ushort RetryInterval);
void SetFlags([In] uint Flags);
void GetFlags([Out] out uint Flags);
void SetAccountInformation([In, MarshalAs(UnmanagedType.LPWStr)] string AccountName, [In, MarshalAs(UnmanagedType.LPWStr)] string Password);
void GetAccountInformation(out System.IntPtr AccountName);
}
#endif
[ComImport, Guid("148BD524-A2AB-11CE-B11F-00AA00530503"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), System.Security.SuppressUnmanagedCodeSecurity, CoClass(typeof(CTask))]
internal interface ITask
{
[return: MarshalAs(UnmanagedType.Interface)]
ITaskTrigger CreateTrigger([Out] out ushort NewTriggerIndex);
void DeleteTrigger([In] ushort TriggerIndex);
[return: MarshalAs(UnmanagedType.U2)]
ushort GetTriggerCount();
[return: MarshalAs(UnmanagedType.Interface)]
ITaskTrigger GetTrigger([In] ushort TriggerIndex);
CoTaskMemString GetTriggerString([In] ushort TriggerIndex);
void GetRunTimes([In, MarshalAs(UnmanagedType.Struct)] ref NativeMethods.SYSTEMTIME Begin, [In, MarshalAs(UnmanagedType.Struct)] ref NativeMethods.SYSTEMTIME End, ref ushort Count, [In, Out] ref IntPtr TaskTimes);
[return: MarshalAs(UnmanagedType.Struct)]
NativeMethods.SYSTEMTIME GetNextRunTime();
void SetIdleWait([In] ushort IdleMinutes, [In] ushort DeadlineMinutes);
void GetIdleWait([Out] out ushort IdleMinutes, [Out] out ushort DeadlineMinutes);
void Run();
void Terminate();
void EditWorkItem([In] IntPtr hParent, [In] uint dwReserved);
[return: MarshalAs(UnmanagedType.Struct)]
NativeMethods.SYSTEMTIME GetMostRecentRunTime();
TaskStatus GetStatus();
uint GetExitCode();
void SetComment([In, MarshalAs(UnmanagedType.LPWStr)] string Comment);
CoTaskMemString GetComment();
void SetCreator([In, MarshalAs(UnmanagedType.LPWStr)] string Creator);
CoTaskMemString GetCreator();
void SetWorkItemData([In] ushort DataLen, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0, ArraySubType = UnmanagedType.U1)] byte[] Data);
void GetWorkItemData(out ushort DataLen, [Out] out IntPtr Data);
void SetErrorRetryCount([In] ushort RetryCount);
ushort GetErrorRetryCount();
void SetErrorRetryInterval([In] ushort RetryInterval);
ushort GetErrorRetryInterval();
void SetFlags([In] TaskFlags Flags);
TaskFlags GetFlags();
void SetAccountInformation([In, MarshalAs(UnmanagedType.LPWStr)] string AccountName, [In] IntPtr Password);
CoTaskMemString GetAccountInformation();
void SetApplicationName([In, MarshalAs(UnmanagedType.LPWStr)] string ApplicationName);
CoTaskMemString GetApplicationName();
void SetParameters([In, MarshalAs(UnmanagedType.LPWStr)] string Parameters);
CoTaskMemString GetParameters();
void SetWorkingDirectory([In, MarshalAs(UnmanagedType.LPWStr)] string WorkingDirectory);
CoTaskMemString GetWorkingDirectory();
void SetPriority([In] uint Priority);
uint GetPriority();
void SetTaskFlags([In] uint Flags);
uint GetTaskFlags();
void SetMaxRunTime([In] uint MaxRunTimeMS);
uint GetMaxRunTime();
}
[Guid("148BD52B-A2AB-11CE-B11F-00AA00530503"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), System.Security.SuppressUnmanagedCodeSecurity]
internal interface ITaskTrigger
{
void SetTrigger([In, Out, MarshalAs(UnmanagedType.Struct)] ref TaskTrigger Trigger);
[return: MarshalAs(UnmanagedType.Struct)]
TaskTrigger GetTrigger();
CoTaskMemString GetTriggerString();
}
[ComImport, Guid("148BD52A-A2AB-11CE-B11F-00AA00530503"), System.Security.SuppressUnmanagedCodeSecurity, ClassInterface(ClassInterfaceType.None)]
internal class CTaskScheduler
{
}
[ComImport, Guid("148BD520-A2AB-11CE-B11F-00AA00530503"), System.Security.SuppressUnmanagedCodeSecurity, ClassInterface(ClassInterfaceType.None)]
internal class CTask
{
}
internal sealed class CoTaskMemString : SafeHandle
{
public CoTaskMemString() : base(IntPtr.Zero, true) { }
public CoTaskMemString(IntPtr handle) : this() { SetHandle(handle); }
public CoTaskMemString(string text) : this() { SetHandle(Marshal.StringToCoTaskMemUni(text)); }
public static implicit operator string (CoTaskMemString cmem) => cmem.ToString();
public override bool IsInvalid => handle == IntPtr.Zero;
protected override bool ReleaseHandle()
{
Marshal.FreeCoTaskMem(handle);
return true;
}
public override string ToString() => Marshal.PtrToStringUni(handle);
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="EwsUtilities.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the EwsUtilities class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml;
/// <summary>
/// EWS utilities
/// </summary>
internal static class EwsUtilities
{
#region Private members
/// <summary>
/// Map from XML element names to ServiceObject type and constructors.
/// </summary>
private static LazyMember<ServiceObjectInfo> serviceObjectInfo = new LazyMember<ServiceObjectInfo>(
delegate()
{
return new ServiceObjectInfo();
});
/// <summary>
/// Version of API binary.
/// </summary>
private static LazyMember<string> buildVersion = new LazyMember<string>(
delegate()
{
try
{
FileVersionInfo fileInfo = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
return fileInfo.FileVersion;
}
catch
{
// OM:2026839 When run in an environment with partial trust, fetching the build version blows up.
// Just return a hardcoded value on failure.
return "0.0";
}
});
/// <summary>
/// Dictionary of enum type to ExchangeVersion maps.
/// </summary>
private static LazyMember<Dictionary<Type, Dictionary<Enum, ExchangeVersion>>> enumVersionDictionaries = new LazyMember<Dictionary<Type, Dictionary<Enum, ExchangeVersion>>>(
() => new Dictionary<Type, Dictionary<Enum, ExchangeVersion>>()
{
{ typeof(WellKnownFolderName), BuildEnumDict(typeof(WellKnownFolderName)) },
{ typeof(ItemTraversal), BuildEnumDict(typeof(ItemTraversal)) },
{ typeof(ConversationQueryTraversal), BuildEnumDict(typeof(ConversationQueryTraversal)) },
{ typeof(FileAsMapping), BuildEnumDict(typeof(FileAsMapping)) },
{ typeof(EventType), BuildEnumDict(typeof(EventType)) },
{ typeof(MeetingRequestsDeliveryScope), BuildEnumDict(typeof(MeetingRequestsDeliveryScope)) },
{ typeof(ViewFilter), BuildEnumDict(typeof(ViewFilter)) },
});
/// <summary>
/// Dictionary of enum type to schema-name-to-enum-value maps.
/// </summary>
private static LazyMember<Dictionary<Type, Dictionary<string, Enum>>> schemaToEnumDictionaries = new LazyMember<Dictionary<Type, Dictionary<string, Enum>>>(
() => new Dictionary<Type, Dictionary<string, Enum>>
{
{ typeof(EventType), BuildSchemaToEnumDict(typeof(EventType)) },
{ typeof(MailboxType), BuildSchemaToEnumDict(typeof(MailboxType)) },
{ typeof(FileAsMapping), BuildSchemaToEnumDict(typeof(FileAsMapping)) },
{ typeof(RuleProperty), BuildSchemaToEnumDict(typeof(RuleProperty)) },
{ typeof(WellKnownFolderName), BuildSchemaToEnumDict(typeof(WellKnownFolderName)) },
});
/// <summary>
/// Dictionary of enum type to enum-value-to-schema-name maps.
/// </summary>
private static LazyMember<Dictionary<Type, Dictionary<Enum, string>>> enumToSchemaDictionaries = new LazyMember<Dictionary<Type, Dictionary<Enum, string>>>(
() => new Dictionary<Type, Dictionary<Enum, string>>
{
{ typeof(EventType), BuildEnumToSchemaDict(typeof(EventType)) },
{ typeof(MailboxType), BuildEnumToSchemaDict(typeof(MailboxType)) },
{ typeof(FileAsMapping), BuildEnumToSchemaDict(typeof(FileAsMapping)) },
{ typeof(RuleProperty), BuildEnumToSchemaDict(typeof(RuleProperty)) },
{ typeof(WellKnownFolderName), BuildEnumToSchemaDict(typeof(WellKnownFolderName)) },
});
/// <summary>
/// Dictionary to map from special CLR type names to their "short" names.
/// </summary>
private static LazyMember<Dictionary<string, string>> typeNameToShortNameMap = new LazyMember<Dictionary<string, string>>(
() => new Dictionary<string, string>
{
{ "Boolean", "bool" },
{ "Int16", "short" },
{ "Int32", "int" },
{ "String", "string" }
});
#endregion
#region Constants
internal const string XSFalse = "false";
internal const string XSTrue = "true";
internal const string EwsTypesNamespacePrefix = "t";
internal const string EwsMessagesNamespacePrefix = "m";
internal const string EwsErrorsNamespacePrefix = "e";
internal const string EwsSoapNamespacePrefix = "soap";
internal const string EwsXmlSchemaInstanceNamespacePrefix = "xsi";
internal const string PassportSoapFaultNamespacePrefix = "psf";
internal const string WSTrustFebruary2005NamespacePrefix = "wst";
internal const string WSAddressingNamespacePrefix = "wsa";
internal const string AutodiscoverSoapNamespacePrefix = "a";
internal const string WSSecurityUtilityNamespacePrefix = "wsu";
internal const string WSSecuritySecExtNamespacePrefix = "wsse";
internal const string EwsTypesNamespace = "http://schemas.microsoft.com/exchange/services/2006/types";
internal const string EwsMessagesNamespace = "http://schemas.microsoft.com/exchange/services/2006/messages";
internal const string EwsErrorsNamespace = "http://schemas.microsoft.com/exchange/services/2006/errors";
internal const string EwsSoapNamespace = "http://schemas.xmlsoap.org/soap/envelope/";
internal const string EwsSoap12Namespace = "http://www.w3.org/2003/05/soap-envelope";
internal const string EwsXmlSchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance";
internal const string PassportSoapFaultNamespace = "http://schemas.microsoft.com/Passport/SoapServices/SOAPFault";
internal const string WSTrustFebruary2005Namespace = "http://schemas.xmlsoap.org/ws/2005/02/trust";
internal const string WSAddressingNamespace = "http://www.w3.org/2005/08/addressing"; // "http://schemas.xmlsoap.org/ws/2004/08/addressing";
internal const string AutodiscoverSoapNamespace = "http://schemas.microsoft.com/exchange/2010/Autodiscover";
internal const string WSSecurityUtilityNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
internal const string WSSecuritySecExtNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
/// <summary>
/// Regular expression for legal domain names.
/// </summary>
internal const string DomainRegex = "^[-a-zA-Z0-9_.]+$";
#endregion
/// <summary>
/// Asserts that the specified condition if true.
/// </summary>
/// <param name="condition">Assertion.</param>
/// <param name="caller">The caller.</param>
/// <param name="message">The message to use if assertion fails.</param>
internal static void Assert(
bool condition,
string caller,
string message)
{
Debug.Assert(
condition,
string.Format("[{0}] {1}", caller, message));
}
/// <summary>
/// Gets the namespace prefix from an XmlNamespace enum value.
/// </summary>
/// <param name="xmlNamespace">The XML namespace.</param>
/// <returns>Namespace prefix string.</returns>
internal static string GetNamespacePrefix(XmlNamespace xmlNamespace)
{
switch (xmlNamespace)
{
case XmlNamespace.Types:
return EwsTypesNamespacePrefix;
case XmlNamespace.Messages:
return EwsMessagesNamespacePrefix;
case XmlNamespace.Errors:
return EwsErrorsNamespacePrefix;
case XmlNamespace.Soap:
case XmlNamespace.Soap12:
return EwsSoapNamespacePrefix;
case XmlNamespace.XmlSchemaInstance:
return EwsXmlSchemaInstanceNamespacePrefix;
case XmlNamespace.PassportSoapFault:
return PassportSoapFaultNamespacePrefix;
case XmlNamespace.WSTrustFebruary2005:
return WSTrustFebruary2005NamespacePrefix;
case XmlNamespace.WSAddressing:
return WSAddressingNamespacePrefix;
case XmlNamespace.Autodiscover:
return AutodiscoverSoapNamespacePrefix;
default:
return string.Empty;
}
}
/// <summary>
/// Gets the namespace URI from an XmlNamespace enum value.
/// </summary>
/// <param name="xmlNamespace">The XML namespace.</param>
/// <returns>Uri as string</returns>
internal static string GetNamespaceUri(XmlNamespace xmlNamespace)
{
switch (xmlNamespace)
{
case XmlNamespace.Types:
return EwsTypesNamespace;
case XmlNamespace.Messages:
return EwsMessagesNamespace;
case XmlNamespace.Errors:
return EwsErrorsNamespace;
case XmlNamespace.Soap:
return EwsSoapNamespace;
case XmlNamespace.Soap12:
return EwsSoap12Namespace;
case XmlNamespace.XmlSchemaInstance:
return EwsXmlSchemaInstanceNamespace;
case XmlNamespace.PassportSoapFault:
return PassportSoapFaultNamespace;
case XmlNamespace.WSTrustFebruary2005:
return WSTrustFebruary2005Namespace;
case XmlNamespace.WSAddressing:
return WSAddressingNamespace;
case XmlNamespace.Autodiscover:
return AutodiscoverSoapNamespace;
default:
return string.Empty;
}
}
/// <summary>
/// Gets the XmlNamespace enum value from a namespace Uri.
/// </summary>
/// <param name="namespaceUri">XML namespace Uri.</param>
/// <returns>XmlNamespace enum value.</returns>
internal static XmlNamespace GetNamespaceFromUri(string namespaceUri)
{
switch (namespaceUri)
{
case EwsErrorsNamespace:
return XmlNamespace.Errors;
case EwsTypesNamespace:
return XmlNamespace.Types;
case EwsMessagesNamespace:
return XmlNamespace.Messages;
case EwsSoapNamespace:
return XmlNamespace.Soap;
case EwsSoap12Namespace:
return XmlNamespace.Soap12;
case EwsXmlSchemaInstanceNamespace:
return XmlNamespace.XmlSchemaInstance;
case PassportSoapFaultNamespace:
return XmlNamespace.PassportSoapFault;
case WSTrustFebruary2005Namespace:
return XmlNamespace.WSTrustFebruary2005;
case WSAddressingNamespace:
return XmlNamespace.WSAddressing;
default:
return XmlNamespace.NotSpecified;
}
}
/// <summary>
/// Creates EWS object based on XML element name.
/// </summary>
/// <typeparam name="TServiceObject">The type of the service object.</typeparam>
/// <param name="service">The service.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <returns>Service object.</returns>
internal static TServiceObject CreateEwsObjectFromXmlElementName<TServiceObject>(ExchangeService service, string xmlElementName)
where TServiceObject : ServiceObject
{
Type itemClass;
if (EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass))
{
CreateServiceObjectWithServiceParam creationDelegate;
if (EwsUtilities.serviceObjectInfo.Member.ServiceObjectConstructorsWithServiceParam.TryGetValue(itemClass, out creationDelegate))
{
return (TServiceObject)creationDelegate(service);
}
else
{
throw new ArgumentException(Strings.NoAppropriateConstructorForItemClass);
}
}
else
{
return default(TServiceObject);
}
}
/// <summary>
/// Creates Item from Item class.
/// </summary>
/// <param name="itemAttachment">The item attachment.</param>
/// <param name="itemClass">The item class.</param>
/// <param name="isNew">If true, item attachment is new.</param>
/// <returns>New Item.</returns>
internal static Item CreateItemFromItemClass(
ItemAttachment itemAttachment,
Type itemClass,
bool isNew)
{
CreateServiceObjectWithAttachmentParam creationDelegate;
if (EwsUtilities.serviceObjectInfo.Member.ServiceObjectConstructorsWithAttachmentParam.TryGetValue(itemClass, out creationDelegate))
{
return (Item)creationDelegate(itemAttachment, isNew);
}
else
{
throw new ArgumentException(Strings.NoAppropriateConstructorForItemClass);
}
}
/// <summary>
/// Creates Item based on XML element name.
/// </summary>
/// <param name="itemAttachment">The item attachment.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <returns>New Item.</returns>
internal static Item CreateItemFromXmlElementName(ItemAttachment itemAttachment, string xmlElementName)
{
Type itemClass;
if (EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass))
{
return CreateItemFromItemClass(itemAttachment, itemClass, false);
}
else
{
return null;
}
}
/// <summary>
/// Gets the expected item type based on the local name.
/// </summary>
/// <param name="xmlElementName"></param>
/// <returns></returns>
internal static Type GetItemTypeFromXmlElementName(string xmlElementName)
{
Type itemClass = null;
EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass);
return itemClass;
}
/// <summary>
/// Finds the first item of type TItem (not a descendant type) in the specified collection.
/// </summary>
/// <typeparam name="TItem">The type of the item to find.</typeparam>
/// <param name="items">The collection.</param>
/// <returns>A TItem instance or null if no instance of TItem could be found.</returns>
internal static TItem FindFirstItemOfType<TItem>(IEnumerable<Item> items)
where TItem : Item
{
Type itemType = typeof(TItem);
foreach (Item item in items)
{
// We're looking for an exact class match here.
if (item.GetType() == itemType)
{
return (TItem)item;
}
}
return null;
}
#region Tracing routines
/// <summary>
/// Write trace start element.
/// </summary>
/// <param name="writer">The writer to write the start element to.</param>
/// <param name="traceTag">The trace tag.</param>
/// <param name="includeVersion">If true, include build version attribute.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Exchange.Usage", "EX0009:DoNotUseDateTimeNowOrFromFileTime", Justification = "Client API")]
private static void WriteTraceStartElement(
XmlWriter writer,
string traceTag,
bool includeVersion)
{
writer.WriteStartElement("Trace");
writer.WriteAttributeString("Tag", traceTag);
writer.WriteAttributeString("Tid", Thread.CurrentThread.ManagedThreadId.ToString());
writer.WriteAttributeString("Time", DateTime.UtcNow.ToString("u", DateTimeFormatInfo.InvariantInfo));
if (includeVersion)
{
writer.WriteAttributeString("Version", EwsUtilities.BuildVersion);
}
}
/// <summary>
/// Format log message.
/// </summary>
/// <param name="entryKind">Kind of the entry.</param>
/// <param name="logEntry">The log entry.</param>
/// <returns>XML log entry as a string.</returns>
internal static string FormatLogMessage(string entryKind, string logEntry)
{
StringBuilder sb = new StringBuilder();
using (StringWriter writer = new StringWriter(sb))
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
{
xmlWriter.Formatting = Formatting.Indented;
EwsUtilities.WriteTraceStartElement(xmlWriter, entryKind, false);
xmlWriter.WriteWhitespace(Environment.NewLine);
xmlWriter.WriteValue(logEntry);
xmlWriter.WriteWhitespace(Environment.NewLine);
xmlWriter.WriteEndElement(); // Trace
xmlWriter.WriteWhitespace(Environment.NewLine);
}
}
return sb.ToString();
}
/// <summary>
/// Format the HTTP headers.
/// </summary>
/// <param name="sb">StringBuilder.</param>
/// <param name="headers">The HTTP headers.</param>
private static void FormatHttpHeaders(StringBuilder sb, WebHeaderCollection headers)
{
foreach (string key in headers.Keys)
{
sb.Append(
string.Format(
"{0}: {1}\n",
key,
headers[key]));
}
}
/// <summary>
/// Format request HTTP headers.
/// </summary>
/// <param name="request">The HTTP request.</param>
internal static string FormatHttpRequestHeaders(IEwsHttpWebRequest request)
{
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("{0} {1} HTTP/1.1\n", request.Method, request.RequestUri.AbsolutePath));
EwsUtilities.FormatHttpHeaders(sb, request.Headers);
sb.Append("\n");
return sb.ToString();
}
/// <summary>
/// Format response HTTP headers.
/// </summary>
/// <param name="response">The HTTP response.</param>
internal static string FormatHttpResponseHeaders(IEwsHttpWebResponse response)
{
StringBuilder sb = new StringBuilder();
sb.Append(
string.Format(
"HTTP/{0} {1} {2}\n",
response.ProtocolVersion,
(int)response.StatusCode,
response.StatusDescription));
sb.Append(EwsUtilities.FormatHttpHeaders(response.Headers));
sb.Append("\n");
return sb.ToString();
}
/// <summary>
/// Format request HTTP headers.
/// </summary>
/// <param name="request">The HTTP request.</param>
internal static string FormatHttpRequestHeaders(HttpWebRequest request)
{
StringBuilder sb = new StringBuilder();
sb.Append(
string.Format(
"{0} {1} HTTP/{2}\n",
request.Method.ToUpperInvariant(),
request.RequestUri.AbsolutePath,
request.ProtocolVersion));
sb.Append(EwsUtilities.FormatHttpHeaders(request.Headers));
sb.Append("\n");
return sb.ToString();
}
/// <summary>
/// Formats HTTP headers.
/// </summary>
/// <param name="headers">The headers.</param>
/// <returns>Headers as a string</returns>
private static string FormatHttpHeaders(WebHeaderCollection headers)
{
StringBuilder sb = new StringBuilder();
foreach (string key in headers.Keys)
{
sb.Append(
string.Format(
"{0}: {1}\n",
key,
headers[key]));
}
return sb.ToString();
}
/// <summary>
/// Format XML content in a MemoryStream for message.
/// </summary>
/// <param name="entryKind">Kind of the entry.</param>
/// <param name="memoryStream">The memory stream.</param>
/// <returns>XML log entry as a string.</returns>
internal static string FormatLogMessageWithXmlContent(string entryKind, MemoryStream memoryStream)
{
StringBuilder sb = new StringBuilder();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.IgnoreComments = true;
settings.IgnoreWhitespace = true;
settings.CloseInput = false;
// Remember the current location in the MemoryStream.
long lastPosition = memoryStream.Position;
// Rewind the position since we want to format the entire contents.
memoryStream.Position = 0;
try
{
using (XmlReader reader = XmlReader.Create(memoryStream, settings))
{
using (StringWriter writer = new StringWriter(sb))
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
{
xmlWriter.Formatting = Formatting.Indented;
EwsUtilities.WriteTraceStartElement(xmlWriter, entryKind, true);
while (!reader.EOF)
{
xmlWriter.WriteNode(reader, true);
}
xmlWriter.WriteEndElement(); // Trace
xmlWriter.WriteWhitespace(Environment.NewLine);
}
}
}
}
catch (XmlException)
{
// We tried to format the content as "pretty" XML. Apparently the content is
// not well-formed XML or isn't XML at all. Fallback and treat it as plain text.
sb.Length = 0;
memoryStream.Position = 0;
sb.Append(Encoding.UTF8.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
}
// Restore Position in the stream.
memoryStream.Position = lastPosition;
return sb.ToString();
}
#endregion
#region Stream routines
/// <summary>
/// Copies source stream to target.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="target">The target.</param>
internal static void CopyStream(Stream source, Stream target)
{
// See if this is a MemoryStream -- we can use WriteTo.
MemoryStream memContentStream = source as MemoryStream;
if (memContentStream != null)
{
memContentStream.WriteTo(target);
}
else
{
// Otherwise, copy data through a buffer
byte[] buffer = new byte[4096];
int bufferSize = buffer.Length;
int bytesRead = source.Read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
target.Write(buffer, 0, bytesRead);
bytesRead = source.Read(buffer, 0, bufferSize);
}
}
}
#endregion
/// <summary>
/// Gets the build version.
/// </summary>
/// <value>The build version.</value>
internal static string BuildVersion
{
get { return EwsUtilities.buildVersion.Member; }
}
#region Conversion routines
/// <summary>
/// Convert bool to XML Schema bool.
/// </summary>
/// <param name="value">Bool value.</param>
/// <returns>String representing bool value in XML Schema.</returns>
internal static string BoolToXSBool(bool value)
{
return value ? EwsUtilities.XSTrue : EwsUtilities.XSFalse;
}
/// <summary>
/// Parses an enum value list.
/// </summary>
/// <typeparam name="T">Type of value.</typeparam>
/// <param name="list">The list.</param>
/// <param name="value">The value.</param>
/// <param name="separators">The separators.</param>
internal static void ParseEnumValueList<T>(
IList<T> list,
string value,
params char[] separators)
where T : struct
{
EwsUtilities.Assert(
typeof(T).IsEnum,
"EwsUtilities.ParseEnumValueList",
"T is not an enum type.");
string[] enumValues = value.Split(separators);
foreach (string enumValue in enumValues)
{
list.Add((T)Enum.Parse(typeof(T), enumValue, false));
}
}
/// <summary>
/// Converts an enum to a string, using the mapping dictionaries if appropriate.
/// </summary>
/// <param name="value">The enum value to be serialized</param>
/// <returns>String representation of enum to be used in the protocol</returns>
internal static string SerializeEnum(Enum value)
{
Dictionary<Enum, string> enumToStringDict;
string strValue;
if (enumToSchemaDictionaries.Member.TryGetValue(value.GetType(), out enumToStringDict) &&
enumToStringDict.TryGetValue(value, out strValue))
{
return strValue;
}
else
{
return value.ToString();
}
}
/// <summary>
/// Parses specified value based on type.
/// </summary>
/// <typeparam name="T">Type of value.</typeparam>
/// <param name="value">The value.</param>
/// <returns>Value of type T.</returns>
internal static T Parse<T>(string value)
{
if (typeof(T).IsEnum)
{
Dictionary<string, Enum> stringToEnumDict;
Enum enumValue;
if (schemaToEnumDictionaries.Member.TryGetValue(typeof(T), out stringToEnumDict) &&
stringToEnumDict.TryGetValue(value, out enumValue))
{
// This double-casting is ugly, but necessary. By this point, we know that T is an Enum
// (same as returned by the dictionary), but the compiler can't prove it. Thus, the
// up-cast before we can down-cast.
return (T)((object)enumValue);
}
else
{
return (T)Enum.Parse(typeof(T), value, false);
}
}
else
{
return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Converts the specified date and time from one time zone to another.
/// </summary>
/// <param name="dateTime">The date time to convert.</param>
/// <param name="sourceTimeZone">The source time zone.</param>
/// <param name="destinationTimeZone">The destination time zone.</param>
/// <returns>A DateTime that holds the converted</returns>
internal static DateTime ConvertTime(
DateTime dateTime,
TimeZoneInfo sourceTimeZone,
TimeZoneInfo destinationTimeZone)
{
try
{
return TimeZoneInfo.ConvertTime(
dateTime,
sourceTimeZone,
destinationTimeZone);
}
catch (ArgumentException e)
{
throw new TimeZoneConversionException(
string.Format(
Strings.CannotConvertBetweenTimeZones,
EwsUtilities.DateTimeToXSDateTime(dateTime),
sourceTimeZone.DisplayName,
destinationTimeZone.DisplayName),
e);
}
}
/// <summary>
/// Reads the string as date time, assuming it is unbiased (e.g. 2009/01/01T08:00)
/// and scoped to service's time zone.
/// </summary>
/// <param name="dateString">The date string.</param>
/// <param name="service">The service.</param>
/// <returns>The string's value as a DateTime object.</returns>
internal static DateTime ParseAsUnbiasedDatetimescopedToServicetimeZone(string dateString, ExchangeService service)
{
// Convert the element's value to a DateTime with no adjustment.
DateTime tempDate = DateTime.Parse(dateString, CultureInfo.InvariantCulture);
// Set the kind according to the service's time zone
if (service.TimeZone == TimeZoneInfo.Utc)
{
return new DateTime(tempDate.Ticks, DateTimeKind.Utc);
}
else if (EwsUtilities.IsLocalTimeZone(service.TimeZone))
{
return new DateTime(tempDate.Ticks, DateTimeKind.Local);
}
else
{
return new DateTime(tempDate.Ticks, DateTimeKind.Unspecified);
}
}
/// <summary>
/// Determines whether the specified time zone is the same as the system's local time zone.
/// </summary>
/// <param name="timeZone">The time zone to check.</param>
/// <returns>
/// <c>true</c> if the specified time zone is the same as the system's local time zone; otherwise, <c>false</c>.
/// </returns>
internal static bool IsLocalTimeZone(TimeZoneInfo timeZone)
{
return (TimeZoneInfo.Local == timeZone) || (TimeZoneInfo.Local.Id == timeZone.Id && TimeZoneInfo.Local.HasSameRules(timeZone));
}
/// <summary>
/// Convert DateTime to XML Schema date.
/// </summary>
/// <param name="date">The date to be converted.</param>
/// <returns>String representation of DateTime.</returns>
internal static string DateTimeToXSDate(DateTime date)
{
// Depending on the current culture, DateTime formatter will
// translate dates from one culture to another (e.g. Gregorian to Lunar). The server
// however, considers all dates to be in Gregorian, so using the InvariantCulture will
// ensure this.
string format;
switch (date.Kind)
{
case DateTimeKind.Utc:
format = "yyyy-MM-ddZ";
break;
case DateTimeKind.Unspecified:
format = "yyyy-MM-dd";
break;
default: // DateTimeKind.Local is remaining
format = "yyyy-MM-ddzzz";
break;
}
return date.ToString(format, CultureInfo.InvariantCulture);
}
/// <summary>
/// Dates the DateTime into an XML schema date time.
/// </summary>
/// <param name="dateTime">The date time.</param>
/// <returns>String representation of DateTime.</returns>
internal static string DateTimeToXSDateTime(DateTime dateTime)
{
string format = "yyyy-MM-ddTHH:mm:ss.fff";
switch (dateTime.Kind)
{
case DateTimeKind.Utc:
format += "Z";
break;
case DateTimeKind.Local:
format += "zzz";
break;
default:
break;
}
// Depending on the current culture, DateTime formatter will replace ':' with
// the DateTimeFormatInfo.TimeSeparator property which may not be ':'. Force the proper string
// to be used by using the InvariantCulture.
return dateTime.ToString(format, CultureInfo.InvariantCulture);
}
/// <summary>
/// Convert EWS DayOfTheWeek enum to System.DayOfWeek.
/// </summary>
/// <param name="dayOfTheWeek">The day of the week.</param>
/// <returns>System.DayOfWeek value.</returns>
internal static DayOfWeek EwsToSystemDayOfWeek(DayOfTheWeek dayOfTheWeek)
{
if (dayOfTheWeek == DayOfTheWeek.Day ||
dayOfTheWeek == DayOfTheWeek.Weekday ||
dayOfTheWeek == DayOfTheWeek.WeekendDay)
{
throw new ArgumentException(
string.Format("Cannot convert {0} to System.DayOfWeek enum value", dayOfTheWeek),
"dayOfTheWeek");
}
else
{
return (DayOfWeek)dayOfTheWeek;
}
}
/// <summary>
/// Convert System.DayOfWeek type to EWS DayOfTheWeek.
/// </summary>
/// <param name="dayOfWeek">The dayOfWeek.</param>
/// <returns>EWS DayOfWeek value</returns>
internal static DayOfTheWeek SystemToEwsDayOfTheWeek(DayOfWeek dayOfWeek)
{
return (DayOfTheWeek)dayOfWeek;
}
/// <summary>
/// Takes a System.TimeSpan structure and converts it into an
/// xs:duration string as defined by the W3 Consortiums Recommendation
/// "XML Schema Part 2: Datatypes Second Edition",
/// http://www.w3.org/TR/xmlschema-2/#duration
/// </summary>
/// <param name="timeSpan">TimeSpan structure to convert</param>
/// <returns>xs:duration formatted string</returns>
internal static string TimeSpanToXSDuration(TimeSpan timeSpan)
{
// Optional '-' offset
string offsetStr = (timeSpan.TotalSeconds < 0) ? "-" : string.Empty;
// The TimeSpan structure does not have a Year or Month
// property, therefore we wouldn't be able to return an xs:duration
// string from a TimeSpan that included the nY or nM components.
return String.Format(
"{0}P{1}DT{2}H{3}M{4}S",
offsetStr,
Math.Abs(timeSpan.Days),
Math.Abs(timeSpan.Hours),
Math.Abs(timeSpan.Minutes),
Math.Abs(timeSpan.Seconds) + "." + Math.Abs(timeSpan.Milliseconds));
}
/// <summary>
/// Takes an xs:duration string as defined by the W3 Consortiums
/// Recommendation "XML Schema Part 2: Datatypes Second Edition",
/// http://www.w3.org/TR/xmlschema-2/#duration, and converts it
/// into a System.TimeSpan structure
/// </summary>
/// <remarks>
/// This method uses the following approximations:
/// 1 year = 365 days
/// 1 month = 30 days
/// Additionally, it only allows for four decimal points of
/// seconds precision.
/// </remarks>
/// <param name="xsDuration">xs:duration string to convert</param>
/// <returns>System.TimeSpan structure</returns>
internal static TimeSpan XSDurationToTimeSpan(string xsDuration)
{
Regex timeSpanParser = new Regex(
"(?<pos>-)?" +
"P" +
"((?<year>[0-9]+)Y)?" +
"((?<month>[0-9]+)M)?" +
"((?<day>[0-9]+)D)?" +
"(T" +
"((?<hour>[0-9]+)H)?" +
"((?<minute>[0-9]+)M)?" +
"((?<seconds>[0-9]+)(\\.(?<precision>[0-9]+))?S)?)?");
Match m = timeSpanParser.Match(xsDuration);
if (!m.Success)
{
throw new ArgumentException(Strings.XsDurationCouldNotBeParsed);
}
string token = m.Result("${pos}");
bool negative = false;
if (!String.IsNullOrEmpty(token))
{
negative = true;
}
// Year
token = m.Result("${year}");
int year = 0;
if (!String.IsNullOrEmpty(token))
{
year = Int32.Parse(token);
}
// Month
token = m.Result("${month}");
int month = 0;
if (!String.IsNullOrEmpty(token))
{
month = Int32.Parse(token);
}
// Day
token = m.Result("${day}");
int day = 0;
if (!String.IsNullOrEmpty(token))
{
day = Int32.Parse(token);
}
// Hour
token = m.Result("${hour}");
int hour = 0;
if (!String.IsNullOrEmpty(token))
{
hour = Int32.Parse(token);
}
// Minute
token = m.Result("${minute}");
int minute = 0;
if (!String.IsNullOrEmpty(token))
{
minute = Int32.Parse(token);
}
// Seconds
token = m.Result("${seconds}");
int seconds = 0;
if (!String.IsNullOrEmpty(token))
{
seconds = Int32.Parse(token);
}
int milliseconds = 0;
token = m.Result("${precision}");
// Only allowed 4 digits of precision
if (token.Length > 4)
{
token = token.Substring(0, 4);
}
if (!String.IsNullOrEmpty(token))
{
milliseconds = Int32.Parse(token);
}
// Apply conversions of year and months to days.
// Year = 365 days
// Month = 30 days
day = day + (year * 365) + (month * 30);
TimeSpan retval = new TimeSpan(day, hour, minute, seconds, milliseconds);
if (negative)
{
retval = -retval;
}
return retval;
}
/// <summary>
/// Converts the specified time span to its XSD representation.
/// </summary>
/// <param name="timeSpan">The time span.</param>
/// <returns>The XSD representation of the specified time span.</returns>
public static string TimeSpanToXSTime(TimeSpan timeSpan)
{
return string.Format(
"{0:00}:{1:00}:{2:00}",
timeSpan.Hours,
timeSpan.Minutes,
timeSpan.Seconds);
}
#endregion
#region Type Name utilities
/// <summary>
/// Gets the printable name of a CLR type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>Printable name.</returns>
public static string GetPrintableTypeName(Type type)
{
if (type.IsGenericType)
{
// Convert generic type to printable form (e.g. List<Item>)
string genericPrefix = type.Name.Substring(0, type.Name.IndexOf('`'));
StringBuilder nameBuilder = new StringBuilder(genericPrefix);
// Note: building array of generic parameters is done recursively. Each parameter could be any type.
string[] genericArgs = type.GetGenericArguments().ToList<Type>().ConvertAll<string>(t => GetPrintableTypeName(t)).ToArray<string>();
nameBuilder.Append("<");
nameBuilder.Append(string.Join(",", genericArgs));
nameBuilder.Append(">");
return nameBuilder.ToString();
}
else if (type.IsArray)
{
// Convert array type to printable form.
string arrayPrefix = type.Name.Substring(0, type.Name.IndexOf('['));
StringBuilder nameBuilder = new StringBuilder(EwsUtilities.GetSimplifiedTypeName(arrayPrefix));
for (int rank = 0; rank < type.GetArrayRank(); rank++)
{
nameBuilder.Append("[]");
}
return nameBuilder.ToString();
}
else
{
return EwsUtilities.GetSimplifiedTypeName(type.Name);
}
}
/// <summary>
/// Gets the printable name of a simple CLR type.
/// </summary>
/// <param name="typeName">The type name.</param>
/// <returns>Printable name.</returns>
private static string GetSimplifiedTypeName(string typeName)
{
// If type has a shortname (e.g. int for Int32) map to the short name.
string name;
return typeNameToShortNameMap.Member.TryGetValue(typeName, out name) ? name : typeName;
}
#endregion
#region EmailAddress parsing
/// <summary>
/// Gets the domain name from an email address.
/// </summary>
/// <param name="emailAddress">The email address.</param>
/// <returns>Domain name.</returns>
internal static string DomainFromEmailAddress(string emailAddress)
{
string[] emailAddressParts = emailAddress.Split('@');
if (emailAddressParts.Length != 2 || string.IsNullOrEmpty(emailAddressParts[1]))
{
throw new FormatException(Strings.InvalidEmailAddress);
}
return emailAddressParts[1];
}
#endregion
#region Method parameters validation routines
/// <summary>
/// Validates parameter (and allows null value).
/// </summary>
/// <param name="param">The param.</param>
/// <param name="paramName">Name of the param.</param>
internal static void ValidateParamAllowNull(object param, string paramName)
{
ISelfValidate selfValidate = param as ISelfValidate;
if (selfValidate != null)
{
try
{
selfValidate.Validate();
}
catch (ServiceValidationException e)
{
throw new ArgumentException(
Strings.ValidationFailed,
paramName,
e);
}
}
ServiceObject ewsObject = param as ServiceObject;
if (ewsObject != null)
{
if (ewsObject.IsNew)
{
throw new ArgumentException(Strings.ObjectDoesNotHaveId, paramName);
}
}
}
/// <summary>
/// Validates parameter (null value not allowed).
/// </summary>
/// <param name="param">The param.</param>
/// <param name="paramName">Name of the param.</param>
internal static void ValidateParam(object param, string paramName)
{
bool isValid;
string strParam = param as string;
if (strParam != null)
{
isValid = !string.IsNullOrEmpty(strParam);
}
else
{
isValid = param != null;
}
if (!isValid)
{
throw new ArgumentNullException(paramName);
}
ValidateParamAllowNull(param, paramName);
}
/// <summary>
/// Validates parameter collection.
/// </summary>
/// <param name="collection">The collection.</param>
/// <param name="paramName">Name of the param.</param>
internal static void ValidateParamCollection(IEnumerable collection, string paramName)
{
ValidateParam(collection, paramName);
int count = 0;
foreach (object obj in collection)
{
try
{
ValidateParam(obj, string.Format("collection[{0}]", count));
}
catch (ArgumentException e)
{
throw new ArgumentException(
string.Format("The element at position {0} is invalid", count),
paramName,
e);
}
count++;
}
if (count == 0)
{
throw new ArgumentException(Strings.CollectionIsEmpty, paramName);
}
}
/// <summary>
/// Validates string parameter to be non-empty string (null value allowed).
/// </summary>
/// <param name="param">The string parameter.</param>
/// <param name="paramName">Name of the parameter.</param>
internal static void ValidateNonBlankStringParamAllowNull(string param, string paramName)
{
if (param != null)
{
// Non-empty string has at least one character which is *not* a whitespace character
if (param.Length == param.CountMatchingChars((c) => Char.IsWhiteSpace(c)))
{
throw new ArgumentException(Strings.ArgumentIsBlankString, paramName);
}
}
}
/// <summary>
/// Validates string parameter to be non-empty string (null value not allowed).
/// </summary>
/// <param name="param">The string parameter.</param>
/// <param name="paramName">Name of the parameter.</param>
internal static void ValidateNonBlankStringParam(string param, string paramName)
{
if (param == null)
{
throw new ArgumentNullException(paramName);
}
ValidateNonBlankStringParamAllowNull(param, paramName);
}
/// <summary>
/// Validates the enum value against the request version.
/// </summary>
/// <param name="enumValue">The enum value.</param>
/// <param name="requestVersion">The request version.</param>
/// <exception cref="ServiceVersionException">Raised if this enum value requires a later version of Exchange.</exception>
internal static void ValidateEnumVersionValue(Enum enumValue, ExchangeVersion requestVersion)
{
Type enumType = enumValue.GetType();
Dictionary<Enum, ExchangeVersion> enumVersionDict = enumVersionDictionaries.Member[enumType];
ExchangeVersion enumVersion = enumVersionDict[enumValue];
if (requestVersion < enumVersion)
{
throw new ServiceVersionException(
string.Format(
Strings.EnumValueIncompatibleWithRequestVersion,
enumValue.ToString(),
enumType.Name,
enumVersion));
}
}
/// <summary>
/// Validates service object version against the request version.
/// </summary>
/// <param name="serviceObject">The service object.</param>
/// <param name="requestVersion">The request version.</param>
/// <exception cref="ServiceVersionException">Raised if this service object type requires a later version of Exchange.</exception>
internal static void ValidateServiceObjectVersion(ServiceObject serviceObject, ExchangeVersion requestVersion)
{
ExchangeVersion minimumRequiredServerVersion = serviceObject.GetMinimumRequiredServerVersion();
if (requestVersion < minimumRequiredServerVersion)
{
throw new ServiceVersionException(
string.Format(
Strings.ObjectTypeIncompatibleWithRequestVersion,
serviceObject.GetType().Name,
minimumRequiredServerVersion));
}
}
/// <summary>
/// Validates property version against the request version.
/// </summary>
/// <param name="service">The Exchange service.</param>
/// <param name="minimumServerVersion">The minimum server version that supports the property.</param>
/// <param name="propertyName">Name of the property.</param>
internal static void ValidatePropertyVersion(
ExchangeService service,
ExchangeVersion minimumServerVersion,
string propertyName)
{
if (service.RequestedServerVersion < minimumServerVersion)
{
throw new ServiceVersionException(
string.Format(
Strings.PropertyIncompatibleWithRequestVersion,
propertyName,
minimumServerVersion));
}
}
/// <summary>
/// Validates method version against the request version.
/// </summary>
/// <param name="service">The Exchange service.</param>
/// <param name="minimumServerVersion">The minimum server version that supports the method.</param>
/// <param name="methodName">Name of the method.</param>
internal static void ValidateMethodVersion(
ExchangeService service,
ExchangeVersion minimumServerVersion,
string methodName)
{
if (service.RequestedServerVersion < minimumServerVersion)
{
throw new ServiceVersionException(
string.Format(
Strings.MethodIncompatibleWithRequestVersion,
methodName,
minimumServerVersion));
}
}
/// <summary>
/// Validates class version against the request version.
/// </summary>
/// <param name="service">The Exchange service.</param>
/// <param name="minimumServerVersion">The minimum server version that supports the method.</param>
/// <param name="className">Name of the class.</param>
internal static void ValidateClassVersion(
ExchangeService service,
ExchangeVersion minimumServerVersion,
string className)
{
if (service.RequestedServerVersion < minimumServerVersion)
{
throw new ServiceVersionException(
string.Format(
Strings.ClassIncompatibleWithRequestVersion,
className,
minimumServerVersion));
}
}
/// <summary>
/// Validates domain name (null value allowed)
/// </summary>
/// <param name="domainName">Domain name.</param>
/// <param name="paramName">Parameter name.</param>
internal static void ValidateDomainNameAllowNull(string domainName, string paramName)
{
if (domainName != null)
{
Regex regex = new Regex(DomainRegex);
if (!regex.IsMatch(domainName))
{
throw new ArgumentException(string.Format(Strings.InvalidDomainName, domainName), paramName);
}
}
}
/// <summary>
/// Gets version for enum member.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <param name="enumName">The enum name.</param>
/// <returns>Exchange version in which the enum value was first defined.</returns>
private static ExchangeVersion GetEnumVersion(Type enumType, string enumName)
{
MemberInfo[] memberInfo = enumType.GetMember(enumName);
EwsUtilities.Assert(
(memberInfo != null) && (memberInfo.Length > 0),
"EwsUtilities.GetEnumVersion",
"Enum member " + enumName + " not found in " + enumType);
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(RequiredServerVersionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((RequiredServerVersionAttribute)attrs[0]).Version;
}
else
{
return ExchangeVersion.Exchange2007_SP1;
}
}
/// <summary>
/// Builds the enum to version mapping dictionary.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <returns>Dictionary of enum values to versions.</returns>
private static Dictionary<Enum, ExchangeVersion> BuildEnumDict(Type enumType)
{
Dictionary<Enum, ExchangeVersion> dict = new Dictionary<Enum, ExchangeVersion>();
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
Enum value = (Enum)Enum.Parse(enumType, name, false);
ExchangeVersion version = GetEnumVersion(enumType, name);
dict.Add(value, version);
}
return dict;
}
/// <summary>
/// Gets the schema name for enum member.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <param name="enumName">The enum name.</param>
/// <returns>The name for the enum used in the protocol, or null if it is the same as the enum's ToString().</returns>
private static string GetEnumSchemaName(Type enumType, string enumName)
{
MemberInfo[] memberInfo = enumType.GetMember(enumName);
EwsUtilities.Assert(
(memberInfo != null) && (memberInfo.Length > 0),
"EwsUtilities.GetEnumSchemaName",
"Enum member " + enumName + " not found in " + enumType);
object[] attrs = memberInfo[0].GetCustomAttributes(typeof(EwsEnumAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((EwsEnumAttribute)attrs[0]).SchemaName;
}
else
{
return null;
}
}
/// <summary>
/// Builds the schema to enum mapping dictionary.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <returns>The mapping from enum to schema name</returns>
private static Dictionary<string, Enum> BuildSchemaToEnumDict(Type enumType)
{
Dictionary<string, Enum> dict = new Dictionary<string, Enum>();
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
Enum value = (Enum)Enum.Parse(enumType, name, false);
string schemaName = EwsUtilities.GetEnumSchemaName(enumType, name);
if (!String.IsNullOrEmpty(schemaName))
{
dict.Add(schemaName, value);
}
}
return dict;
}
/// <summary>
/// Builds the enum to schema mapping dictionary.
/// </summary>
/// <param name="enumType">Type of the enum.</param>
/// <returns>The mapping from enum to schema name</returns>
private static Dictionary<Enum, string> BuildEnumToSchemaDict(Type enumType)
{
Dictionary<Enum, string> dict = new Dictionary<Enum, string>();
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
Enum value = (Enum)Enum.Parse(enumType, name, false);
string schemaName = EwsUtilities.GetEnumSchemaName(enumType, name);
if (!String.IsNullOrEmpty(schemaName))
{
dict.Add(value, schemaName);
}
}
return dict;
}
#endregion
#region IEnumerable utility methods
/// <summary>
/// Gets the enumerated object count.
/// </summary>
/// <param name="objects">The objects.</param>
/// <returns>Count of objects in IEnumerable.</returns>
internal static int GetEnumeratedObjectCount(IEnumerable objects)
{
int count = 0;
foreach (object obj in objects)
{
count++;
}
return count;
}
/// <summary>
/// Gets enumerated object at index.
/// </summary>
/// <param name="objects">The objects.</param>
/// <param name="index">The index.</param>
/// <returns>Object at index.</returns>
internal static object GetEnumeratedObjectAt(IEnumerable objects, int index)
{
int count = 0;
foreach (object obj in objects)
{
if (count == index)
{
return obj;
}
count++;
}
throw new ArgumentOutOfRangeException("index", Strings.IEnumerableDoesNotContainThatManyObject);
}
#endregion
#region Extension methods
/// <summary>
/// Count characters in string that match a condition.
/// </summary>
/// <param name="str">The string.</param>
/// <param name="charPredicate">Predicate to evaluate for each character in the string.</param>
/// <returns>Count of characters that match condition expressed by predicate.</returns>
internal static int CountMatchingChars(this string str, Predicate<char> charPredicate)
{
int count = 0;
foreach (char ch in str)
{
if (charPredicate(ch))
{
count++;
}
}
return count;
}
/// <summary>
/// Determines whether every element in the collection matches the conditions defined by the specified predicate.
/// </summary>
/// <typeparam name="T">Entry type.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="predicate">Predicate that defines the conditions to check against the elements.</param>
/// <returns>True if every element in the collection matches the conditions defined by the specified predicate; otherwise, false.</returns>
internal static bool TrueForAll<T>(this IEnumerable<T> collection, Predicate<T> predicate)
{
foreach (T entry in collection)
{
if (!predicate(entry))
{
return false;
}
}
return true;
}
/// <summary>
/// Call an action for each member of a collection.
/// </summary>
/// <param name="collection">The collection.</param>
/// <param name="action">The action to apply.</param>
/// <typeparam name="T">Collection element type.</typeparam>
internal static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
foreach (T entry in collection)
{
action(entry);
}
}
#endregion
}
}
| |
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
*/
/*
** Author: Eric Veach, July 1994.
// C# Port port by: Lars Brubaker
// [email protected]
// Copyright (C) 2007
**
*/
/* The mesh structure is similar in spirit, notation, and operations
* to the "quad-edge" structure (see L. Guibas and J. Stolfi, Primitives
* for the manipulation of general subdivisions and the computation of
* Voronoi diagrams, ACM Transactions on Graphics, 4(2):74-123, April 1985).
* For a simplified description, see the course notes for CS348a,
* "Mathematical Foundations of Computer Graphics", available at the
* Stanford bookstore (and taught during the fall quarter).
* The implementation also borrows a tiny subset of the graph-based approach
* use in Mantyla's Geometric Work Bench (see M. Mantyla, An Introduction
* to Sold Modeling, Computer Science Press, Rockville, Maryland, 1988).
*
* The fundamental data structure is the "half-edge". Two half-edges
* go together to make an edge, but they point in opposite directions.
* Each half-edge has a pointer to its mate (the "symmetric" half-edge Sym),
* its origin vertex (Org), the face on its left side (Lface), and the
* adjacent half-edges in the CCW direction around the origin vertex
* (Onext) and around the left face (Lnext). There is also a "next"
* pointer for the global edge list (see below).
*
* The notation used for mesh navigation:
* Sym = the mate of a half-edge (same edge, but opposite direction)
* Onext = edge CCW around origin vertex (keep same origin)
* Dnext = edge CCW around destination vertex (keep same dest)
* Lnext = edge CCW around left face (dest becomes new origin)
* Rnext = edge CCW around right face (origin becomes new dest)
*
* "prev" means to substitute CW for CCW in the definitions above.
*
* The mesh keeps global lists of all vertices, faces, and edges,
* stored as doubly-linked circular lists with a dummy header node.
* The mesh stores pointers to these dummy headers (vHead, fHead, eHead).
*
* The circular edge list is special; since half-edges always occur
* in pairs (e and e.Sym), each half-edge stores a pointer in only
* one direction. Starting at eHead and following the e.next pointers
* will visit each *edge* once (ie. e or e.Sym, but not both).
* e.Sym stores a pointer in the opposite direction, thus it is
* always true that e.Sym.next.Sym.next == e.
*
* Each vertex has a pointer to next and previous vertices in the
* circular list, and a pointer to a half-edge with this vertex as
* the origin (null if this is the dummy header). There is also a
* field "data" for client data.
*
* Each face has a pointer to the next and previous faces in the
* circular list, and a pointer to a half-edge with this face as
* the left face (null if this is the dummy header). There is also
* a field "data" for client data.
*
* Note that what we call a "face" is really a loop; faces may consist
* of more than one loop (ie. not simply connected), but there is no
* record of this in the data structure. The mesh may consist of
* several disconnected regions, so it may not be possible to visit
* the entire mesh by starting at a half-edge and traversing the edge
* structure.
*
* The mesh does NOT support isolated vertices; a vertex is deleted along
* with its last edge. Similarly when two faces are merged, one of the
* faces is deleted. For mesh operations,
* all face (loop) and vertex pointers must not be null. However, once
* mesh manipulation is finished, ZapFace can be used to delete
* faces of the mesh, one at a time. All external faces can be "zapped"
* before the mesh is returned to the client; then a null face indicates
* a region which is not part of the output polygon.
*/
using System;
namespace Tesselate
{
// the mesh class
/* The mesh operations below have three motivations: completeness,
* convenience, and efficiency. The basic mesh operations are MakeEdge,
* Splice, and Delete. All the other edge operations can be implemented
* in terms of these. The other operations are provided for convenience
* and/or efficiency.
*
* When a face is split or a vertex is added, they are inserted into the
* global list *before* the existing vertex or face (ie. e.Org or e.Lface).
* This makes it easier to process all vertices or faces in the global lists
* without worrying about processing the same data twice. As a convenience,
* when a face is split, the "inside" flag is copied from the old face.
* Other internal data (v.data, v.activeRegion, f.data, f.marked,
* f.trail, e.winding) is set to zero.
*
* ********************** Basic Edge Operations **************************
*
* MakeEdge() creates one edge, two vertices, and a loop.
* The loop (face) consists of the two new half-edges.
*
* Splice( eOrg, eDst ) is the basic operation for changing the
* mesh connectivity and topology. It changes the mesh so that
* eOrg.Onext <- OLD( eDst.Onext )
* eDst.Onext <- OLD( eOrg.Onext )
* where OLD(...) means the value before the meshSplice operation.
*
* This can have two effects on the vertex structure:
* - if eOrg.Org != eDst.Org, the two vertices are merged together
* - if eOrg.Org == eDst.Org, the origin is split into two vertices
* In both cases, eDst.Org is changed and eOrg.Org is untouched.
*
* Similarly (and independently) for the face structure,
* - if eOrg.Lface == eDst.Lface, one loop is split into two
* - if eOrg.Lface != eDst.Lface, two distinct loops are joined into one
* In both cases, eDst.Lface is changed and eOrg.Lface is unaffected.
*
* __gl_meshDelete( eDel ) removes the edge eDel. There are several cases:
* if (eDel.Lface != eDel.Rface), we join two loops into one; the loop
* eDel.Lface is deleted. Otherwise, we are splitting one loop into two;
* the newly created loop will contain eDel.Dst. If the deletion of eDel
* would create isolated vertices, those are deleted as well.
*
* ********************** Other Edge Operations **************************
*
* __gl_meshAddEdgeVertex( eOrg ) creates a new edge eNew such that
* eNew == eOrg.Lnext, and eNew.Dst is a newly created vertex.
* eOrg and eNew will have the same left face.
*
* __gl_meshSplitEdge( eOrg ) splits eOrg into two edges eOrg and eNew,
* such that eNew == eOrg.Lnext. The new vertex is eOrg.Dst == eNew.Org.
* eOrg and eNew will have the same left face.
*
* __gl_meshConnect( eOrg, eDst ) creates a new edge from eOrg.Dst
* to eDst.Org, and returns the corresponding half-edge eNew.
* If eOrg.Lface == eDst.Lface, this splits one loop into two,
* and the newly created loop is eNew.Lface. Otherwise, two disjoint
* loops are merged into one, and the loop eDst.Lface is destroyed.
*
* ************************ Other Operations *****************************
*
* __gl_meshNewMesh() creates a new mesh with no edges, no vertices,
* and no loops (what we usually call a "face").
*
* __gl_meshUnion( mesh1, mesh2 ) forms the union of all structures in
* both meshes, and returns the new mesh (the old meshes are destroyed).
*
* __gl_meshDeleteMesh( mesh ) will free all storage for any valid mesh.
*
* __gl_meshZapFace( fZap ) destroys a face and removes it from the
* global face list. All edges of fZap will have a null pointer as their
* left face. Any edges which also have a null pointer as their right face
* are deleted entirely (along with any isolated vertices this produces).
* An entire mesh can be deleted by zapping its faces, one at a time,
* in any order. Zapped faces cannot be used in further mesh operations!
*
* __gl_meshCheckMesh( mesh ) checks a mesh for self-consistency.
*/
public class Mesh
{
internal ContourVertex _vertexHead = new ContourVertex(); /* dummy header for vertex list */
internal Face _faceHead = new Face(); /* dummy header for face list */
internal HalfEdge _halfEdgeHead = new HalfEdge(); /* dummy header for edge list */
HalfEdge _otherHalfOfThisEdgeHead = new HalfEdge(); /* and its symmetric counterpart */
/* Creates a new mesh with no edges, no vertices,
* and no loops (what we usually call a "face").
*/
public Mesh()
{
HalfEdge otherHalfOfThisEdge = _otherHalfOfThisEdgeHead;
_vertexHead._nextVertex = _vertexHead._prevVertex = _vertexHead;
_vertexHead._edgeThisIsOriginOf = null;
_vertexHead._clientIndex = 0;
_faceHead._nextFace = _faceHead._prevFace = _faceHead;
_faceHead._halfEdgeThisIsLeftFaceOf = null;
_faceHead._trail = null;
_faceHead._marked = false;
_faceHead._isInterior = false;
_halfEdgeHead._nextHalfEdge = _halfEdgeHead;
_halfEdgeHead._otherHalfOfThisEdge = otherHalfOfThisEdge;
_halfEdgeHead._nextEdgeCCWAroundOrigin = null;
_halfEdgeHead._nextEdgeCCWAroundLeftFace = null;
_halfEdgeHead._originVertex = null;
_halfEdgeHead._leftFace = null;
_halfEdgeHead._winding = 0;
_halfEdgeHead._regionThisIsUpperEdgeOf = null;
otherHalfOfThisEdge._nextHalfEdge = otherHalfOfThisEdge;
otherHalfOfThisEdge._otherHalfOfThisEdge = _halfEdgeHead;
otherHalfOfThisEdge._nextEdgeCCWAroundOrigin = null;
otherHalfOfThisEdge._nextEdgeCCWAroundLeftFace = null;
otherHalfOfThisEdge._originVertex = null;
otherHalfOfThisEdge._leftFace = null;
otherHalfOfThisEdge._winding = 0;
otherHalfOfThisEdge._regionThisIsUpperEdgeOf = null;
}
/* MakeFace( newFace, eOrig, fNext ) attaches a new face and makes it the left
* face of all edges in the face loop to which eOrig belongs. "fNext" gives
* a place to insert the new face in the global face list. We insert
* the new face *before* fNext so that algorithms which walk the face
* list will not see the newly created faces.
*/
#if DEBUG
static int s_dbugFaceIndexTotal = 0;
#endif
static void MakeFace(Face newFace, HalfEdge eOrig, Face fNext)
{
HalfEdge e;
Face fPrev;
Face fNew = newFace;
#if DEBUG
fNew.dbugIndex = s_dbugFaceIndexTotal++;
#endif
// insert in circular doubly-linked list before fNext
fPrev = fNext._prevFace;
fNew._prevFace = fPrev;
fPrev._nextFace = fNew;
fNew._nextFace = fNext;
fNext._prevFace = fNew;
fNew._halfEdgeThisIsLeftFaceOf = eOrig;
fNew._trail = null;
fNew._marked = false;
// The new face is marked "inside" if the old one was. This is a
// convenience for the common case where a face has been split in two.
fNew._isInterior = fNext._isInterior;
// fix other edges on this face loop
e = eOrig;
do
{
e._leftFace = fNew;
e = e._nextEdgeCCWAroundLeftFace;
} while (e != eOrig);
}
// __gl_meshMakeEdge creates one edge, two vertices, and a loop (face).
// The loop consists of the two new half-edges.
public HalfEdge MakeEdge()
{
ContourVertex newVertex1 = new ContourVertex();
ContourVertex newVertex2 = new ContourVertex();
Face newFace = new Face();
HalfEdge e;
e = MakeEdge(_halfEdgeHead);
MakeVertex(newVertex1, e, _vertexHead);
MakeVertex(newVertex2, e._otherHalfOfThisEdge, _vertexHead);
MakeFace(newFace, e, _faceHead);
return e;
}
/* MakeVertex( newVertex, eOrig, vNext ) attaches a new vertex and makes it the
* origin of all edges in the vertex loop to which eOrig belongs. "vNext" gives
* a place to insert the new vertex in the global vertex list. We insert
* the new vertex *before* vNext so that algorithms which walk the vertex
* list will not see the newly created vertices.
*/
static void MakeVertex(ContourVertex newVertex, HalfEdge eOrig, ContourVertex vNext)
{
HalfEdge e;
ContourVertex vPrev;
ContourVertex vNew = newVertex;
/* insert in circular doubly-linked list before vNext */
vPrev = vNext._prevVertex;
vNew._prevVertex = vPrev;
vPrev._nextVertex = vNew;
vNew._nextVertex = vNext;
vNext._prevVertex = vNew;
vNew._edgeThisIsOriginOf = eOrig;
vNew._clientIndex = 0;
/* leave coords, s, t undefined */
/* fix other edges on this vertex loop */
e = eOrig;
do
{
e._originVertex = vNew;
e = e._nextEdgeCCWAroundOrigin;
} while (e != eOrig);
}
/* KillVertex( vDel ) destroys a vertex and removes it from the global
* vertex list. It updates the vertex loop to point to a given new vertex.
*/
static void KillVertex(ContourVertex vDel, ContourVertex newOrg)
{
HalfEdge e, eStart = vDel._edgeThisIsOriginOf;
ContourVertex vPrev, vNext;
/* change the origin of all affected edges */
e = eStart;
do
{
e._originVertex = newOrg;
e = e._nextEdgeCCWAroundOrigin;
} while (e != eStart);
/* delete from circular doubly-linked list */
vPrev = vDel._prevVertex;
vNext = vDel._nextVertex;
vNext._prevVertex = vPrev;
vPrev._nextVertex = vNext;
}
/* KillFace( fDel ) destroys a face and removes it from the global face
* list. It updates the face loop to point to a given new face.
*/
static void KillFace(Face fDel, Face newLface)
{
HalfEdge e, eStart = fDel._halfEdgeThisIsLeftFaceOf;
Face fPrev, fNext;
/* change the left face of all affected edges */
e = eStart;
do
{
e._leftFace = newLface;
e = e._nextEdgeCCWAroundLeftFace;
} while (e != eStart);
/* delete from circular doubly-linked list */
fPrev = fDel._prevFace;
fNext = fDel._nextFace;
fNext._prevFace = fPrev;
fPrev._nextFace = fNext;
}
/* Splice( a, b ) is best described by the Guibas/Stolfi paper or the
* CS348a notes (see mesh.h). Basically it modifies the mesh so that
* a.Onext and b.Onext are exchanged. This can have various effects
* depending on whether a and b belong to different face or vertex rings.
* For more explanation see __gl_meshSplice() below.
*/
static void Splice(HalfEdge a, HalfEdge b)
{
HalfEdge aOnext = a._nextEdgeCCWAroundOrigin;
HalfEdge bOnext = b._nextEdgeCCWAroundOrigin;
aOnext._otherHalfOfThisEdge._nextEdgeCCWAroundLeftFace = b;
bOnext._otherHalfOfThisEdge._nextEdgeCCWAroundLeftFace = a;
a._nextEdgeCCWAroundOrigin = bOnext;
b._nextEdgeCCWAroundOrigin = aOnext;
}
/* __gl_meshSplice( eOrg, eDst ) is the basic operation for changing the
* mesh connectivity and topology. It changes the mesh so that
* eOrg.Onext <- OLD( eDst.Onext )
* eDst.Onext <- OLD( eOrg.Onext )
* where OLD(...) means the value before the meshSplice operation.
*
* This can have two effects on the vertex structure:
* - if eOrg.Org != eDst.Org, the two vertices are merged together
* - if eOrg.Org == eDst.Org, the origin is split into two vertices
* In both cases, eDst.Org is changed and eOrg.Org is untouched.
*
* Similarly (and independently) for the face structure,
* - if eOrg.Lface == eDst.Lface, one loop is split into two
* - if eOrg.Lface != eDst.Lface, two distinct loops are joined into one
* In both cases, eDst.Lface is changed and eOrg.Lface is unaffected.
*
* Some special cases:
* If eDst == eOrg, the operation has no effect.
* If eDst == eOrg.Lnext, the new face will have a single edge.
* If eDst == eOrg.Lprev, the old face will have a single edge.
* If eDst == eOrg.Onext, the new vertex will have a single edge.
* If eDst == eOrg.Oprev, the old vertex will have a single edge.
*/
public static void meshSplice(HalfEdge eOrg, HalfEdge eDst)
{
bool joiningLoops = false;
bool joiningVertices = false;
if (eOrg == eDst) return;
if (eDst._originVertex != eOrg._originVertex)
{
/* We are merging two disjoint vertices -- destroy eDst.Org */
joiningVertices = true;
KillVertex(eDst._originVertex, eOrg._originVertex);
}
if (eDst._leftFace != eOrg._leftFace)
{
/* We are connecting two disjoint loops -- destroy eDst.Lface */
joiningLoops = true;
KillFace(eDst._leftFace, eOrg._leftFace);
}
/* Change the edge structure */
Splice(eDst, eOrg);
if (!joiningVertices)
{
ContourVertex newVertex = new ContourVertex();
/* We split one vertex into two -- the new vertex is eDst.Org.
* Make sure the old vertex points to a valid half-edge.
*/
MakeVertex(newVertex, eDst, eOrg._originVertex);
eOrg._originVertex._edgeThisIsOriginOf = eOrg;
}
if (!joiningLoops)
{
Face newFace = new Face();
/* We split one loop into two -- the new loop is eDst.Lface.
* Make sure the old face points to a valid half-edge.
*/
MakeFace(newFace, eDst, eOrg._leftFace);
eOrg._leftFace._halfEdgeThisIsLeftFaceOf = eOrg;
}
}
/* KillEdge( eDel ) destroys an edge (the half-edges eDel and eDel.Sym),
* and removes from the global edge list.
*/
static void KillEdge(HalfEdge eDel)
{
HalfEdge ePrev, eNext;
/* Half-edges are allocated in pairs, see EdgePair above */
if (eDel._otherHalfOfThisEdge._isFirstHalfEdge)
{
eDel = eDel._otherHalfOfThisEdge;
}
/* delete from circular doubly-linked list */
eNext = eDel._nextHalfEdge;
ePrev = eDel._otherHalfOfThisEdge._nextHalfEdge;
eNext._otherHalfOfThisEdge._nextHalfEdge = ePrev;
ePrev._otherHalfOfThisEdge._nextHalfEdge = eNext;
}
/* __gl_meshDelete( eDel ) removes the edge eDel. There are several cases:
* if (eDel.Lface != eDel.Rface), we join two loops into one; the loop
* eDel.Lface is deleted. Otherwise, we are splitting one loop into two;
* the newly created loop will contain eDel.Dst. If the deletion of eDel
* would create isolated vertices, those are deleted as well.
*
* This function could be implemented as two calls to __gl_meshSplice
* plus a few calls to free, but this would allocate and delete
* unnecessary vertices and faces.
*/
public static void DeleteHalfEdge(HalfEdge edgeToDelete)
{
HalfEdge otherHalfOfEdgeToDelete = edgeToDelete._otherHalfOfThisEdge;
bool joiningLoops = false;
// First step: disconnect the origin vertex eDel.Org. We make all
// changes to get a consistent mesh in this "intermediate" state.
if (edgeToDelete._leftFace != edgeToDelete.rightFace)
{
// We are joining two loops into one -- remove the left face
joiningLoops = true;
KillFace(edgeToDelete._leftFace, edgeToDelete.rightFace);
}
if (edgeToDelete._nextEdgeCCWAroundOrigin == edgeToDelete)
{
KillVertex(edgeToDelete._originVertex, null);
}
else
{
// Make sure that eDel.Org and eDel.Rface point to valid half-edges
edgeToDelete.rightFace._halfEdgeThisIsLeftFaceOf = edgeToDelete.Oprev;
edgeToDelete._originVertex._edgeThisIsOriginOf = edgeToDelete._nextEdgeCCWAroundOrigin;
Splice(edgeToDelete, edgeToDelete.Oprev);
if (!joiningLoops)
{
Face newFace = new Face();
// We are splitting one loop into two -- create a new loop for eDel.
MakeFace(newFace, edgeToDelete, edgeToDelete._leftFace);
}
}
// Claim: the mesh is now in a consistent state, except that eDel.Org
// may have been deleted. Now we disconnect eDel.Dst.
if (otherHalfOfEdgeToDelete._nextEdgeCCWAroundOrigin == otherHalfOfEdgeToDelete)
{
KillVertex(otherHalfOfEdgeToDelete._originVertex, null);
KillFace(otherHalfOfEdgeToDelete._leftFace, null);
}
else
{
// Make sure that eDel.Dst and eDel.Lface point to valid half-edges
edgeToDelete._leftFace._halfEdgeThisIsLeftFaceOf = otherHalfOfEdgeToDelete.Oprev;
otherHalfOfEdgeToDelete._originVertex._edgeThisIsOriginOf = otherHalfOfEdgeToDelete._nextEdgeCCWAroundOrigin;
Splice(otherHalfOfEdgeToDelete, otherHalfOfEdgeToDelete.Oprev);
}
// Any isolated vertices or faces have already been freed.
KillEdge(edgeToDelete);
}
/* __gl_meshAddEdgeVertex( eOrg ) creates a new edge eNew such that
* eNew == eOrg.Lnext, and eNew.Dst is a newly created vertex.
* eOrg and eNew will have the same left face.
*/
static HalfEdge meshAddEdgeVertex(HalfEdge eOrg)
{
HalfEdge eNewSym;
HalfEdge eNew = MakeEdge(eOrg);
eNewSym = eNew._otherHalfOfThisEdge;
/* Connect the new edge appropriately */
Splice(eNew, eOrg._nextEdgeCCWAroundLeftFace);
/* Set the vertex and face information */
eNew._originVertex = eOrg.DirectionVertex;
{
ContourVertex newVertex = new ContourVertex();
MakeVertex(newVertex, eNewSym, eNew._originVertex);
}
eNew._leftFace = eNewSym._leftFace = eOrg._leftFace;
return eNew;
}
/* __gl_meshSplitEdge( eOrg ) splits eOrg into two edges eOrg and eNew,
* such that eNew == eOrg.Lnext. The new vertex is eOrg.Dst == eNew.Org.
* eOrg and eNew will have the same left face.
*/
public static HalfEdge meshSplitEdge(HalfEdge eOrg)
{
HalfEdge eNew;
HalfEdge tempHalfEdge = meshAddEdgeVertex(eOrg);
eNew = tempHalfEdge._otherHalfOfThisEdge;
/* Disconnect eOrg from eOrg.Dst and connect it to eNew.Org */
Splice(eOrg._otherHalfOfThisEdge, eOrg._otherHalfOfThisEdge.Oprev);
Splice(eOrg._otherHalfOfThisEdge, eNew);
/* Set the vertex and face information */
eOrg.DirectionVertex = eNew._originVertex;
eNew.DirectionVertex._edgeThisIsOriginOf = eNew._otherHalfOfThisEdge; /* may have pointed to eOrg.Sym */
eNew.rightFace = eOrg.rightFace;
eNew._winding = eOrg._winding; /* copy old winding information */
eNew._otherHalfOfThisEdge._winding = eOrg._otherHalfOfThisEdge._winding;
return eNew;
}
/* Allocate and free half-edges in pairs for efficiency.
* The *only* place that should use this fact is allocation/free.
*/
class EdgePair
{
public readonly HalfEdge e = new HalfEdge();
public readonly HalfEdge eSym = new HalfEdge();
#if DEBUG
static int debugIndex;
#endif
public EdgePair()
{
#if DEBUG
e.debugIndex = debugIndex++;
eSym.debugIndex = debugIndex++;
#endif
}
};
/* MakeEdge creates a new pair of half-edges which form their own loop.
* No vertex or face structures are allocated, but these must be assigned
* before the current edge operation is completed.
*/
static HalfEdge MakeEdge(HalfEdge eNext)
{
HalfEdge ePrev;
EdgePair pair = new EdgePair();
/* Make sure eNext points to the first edge of the edge pair */
if (eNext._otherHalfOfThisEdge._isFirstHalfEdge)
{
eNext = eNext._otherHalfOfThisEdge;
}
/* Insert in circular doubly-linked list before eNext.
* Note that the prev pointer is stored in Sym.next.
*/
ePrev = eNext._otherHalfOfThisEdge._nextHalfEdge;
pair.eSym._nextHalfEdge = ePrev;
ePrev._otherHalfOfThisEdge._nextHalfEdge = pair.e;
pair.e._nextHalfEdge = eNext;
eNext._otherHalfOfThisEdge._nextHalfEdge = pair.eSym;
pair.e._isFirstHalfEdge = true;
pair.e._otherHalfOfThisEdge = pair.eSym;
pair.e._nextEdgeCCWAroundOrigin = pair.e;
pair.e._nextEdgeCCWAroundLeftFace = pair.eSym;
pair.e._originVertex = null;
pair.e._leftFace = null;
pair.e._winding = 0;
pair.e._regionThisIsUpperEdgeOf = null;
pair.eSym._isFirstHalfEdge = false;
pair.eSym._otherHalfOfThisEdge = pair.e;
pair.eSym._nextEdgeCCWAroundOrigin = pair.eSym;
pair.eSym._nextEdgeCCWAroundLeftFace = pair.e;
pair.eSym._originVertex = null;
pair.eSym._leftFace = null;
pair.eSym._winding = 0;
pair.eSym._regionThisIsUpperEdgeOf = null;
return pair.e;
}
/* __gl_meshConnect( eOrg, eDst ) creates a new edge from eOrg.Dst
* to eDst.Org, and returns the corresponding half-edge eNew.
* If eOrg.Lface == eDst.Lface, this splits one loop into two,
* and the newly created loop is eNew.Lface. Otherwise, two disjoint
* loops are merged into one, and the loop eDst.Lface is destroyed.
*
* If (eOrg == eDst), the new face will have only two edges.
* If (eOrg.Lnext == eDst), the old face is reduced to a single edge.
* If (eOrg.Lnext.Lnext == eDst), the old face is reduced to two edges.
*/
public static HalfEdge meshConnect(HalfEdge eOrg, HalfEdge eDst)
{
HalfEdge eNewSym;
bool joiningLoops = false;
HalfEdge eNew = MakeEdge(eOrg);
eNewSym = eNew._otherHalfOfThisEdge;
if (eDst._leftFace != eOrg._leftFace)
{
/* We are connecting two disjoint loops -- destroy eDst.Lface */
joiningLoops = true;
KillFace(eDst._leftFace, eOrg._leftFace);
}
/* Connect the new edge appropriately */
Splice(eNew, eOrg._nextEdgeCCWAroundLeftFace);
Splice(eNewSym, eDst);
/* Set the vertex and face information */
eNew._originVertex = eOrg.DirectionVertex;
eNewSym._originVertex = eDst._originVertex;
eNew._leftFace = eNewSym._leftFace = eOrg._leftFace;
/* Make sure the old face points to a valid half-edge */
eOrg._leftFace._halfEdgeThisIsLeftFaceOf = eNewSym;
if (!joiningLoops)
{
Face newFace = new Face();
/* We split one loop into two -- the new loop is eNew.Lface */
MakeFace(newFace, eNew, eOrg._leftFace);
}
return eNew;
}
/* __gl_meshUnion( mesh1, mesh2 ) forms the union of all structures in
* both meshes, and returns the new mesh (the old meshes are destroyed).
*/
Mesh meshUnion(Mesh mesh1, Mesh mesh2)
{
Face f1 = mesh1._faceHead;
ContourVertex v1 = mesh1._vertexHead;
HalfEdge e1 = mesh1._halfEdgeHead;
Face f2 = mesh2._faceHead;
ContourVertex v2 = mesh2._vertexHead;
HalfEdge e2 = mesh2._halfEdgeHead;
/* Add the faces, vertices, and edges of mesh2 to those of mesh1 */
if (f2._nextFace != f2)
{
f1._prevFace._nextFace = f2._nextFace;
f2._nextFace._prevFace = f1._prevFace;
f2._prevFace._nextFace = f1;
f1._prevFace = f2._prevFace;
}
if (v2._nextVertex != v2)
{
v1._prevVertex._nextVertex = v2._nextVertex;
v2._nextVertex._prevVertex = v1._prevVertex;
v2._prevVertex._nextVertex = v1;
v1._prevVertex = v2._prevVertex;
}
if (e2._nextHalfEdge != e2)
{
e1._otherHalfOfThisEdge._nextHalfEdge._otherHalfOfThisEdge._nextHalfEdge = e2._nextHalfEdge;
e2._nextHalfEdge._otherHalfOfThisEdge._nextHalfEdge = e1._otherHalfOfThisEdge._nextHalfEdge;
e2._otherHalfOfThisEdge._nextHalfEdge._otherHalfOfThisEdge._nextHalfEdge = e1;
e1._otherHalfOfThisEdge._nextHalfEdge = e2._otherHalfOfThisEdge._nextHalfEdge;
}
mesh2 = null;
return mesh1;
}
/* __gl_meshZapFace( fZap ) destroys a face and removes it from the
* global face list. All edges of fZap will have a null pointer as their
* left face. Any edges which also have a null pointer as their right face
* are deleted entirely (along with any isolated vertices this produces).
* An entire mesh can be deleted by zapping its faces, one at a time,
* in any order. Zapped faces cannot be used in further mesh operations!
*/
public static void meshZapFace(Face fZap)
{
HalfEdge eStart = fZap._halfEdgeThisIsLeftFaceOf;
HalfEdge e, eNext, eSym;
Face fPrev, fNext;
/* walk around face, deleting edges whose right face is also null */
eNext = eStart._nextEdgeCCWAroundLeftFace;
do
{
e = eNext;
eNext = e._nextEdgeCCWAroundLeftFace;
e._leftFace = null;
if (e.rightFace == null)
{
/* delete the edge -- see __gl_MeshDelete above */
if (e._nextEdgeCCWAroundOrigin == e)
{
KillVertex(e._originVertex, null);
}
else
{
/* Make sure that e.Org points to a valid half-edge */
e._originVertex._edgeThisIsOriginOf = e._nextEdgeCCWAroundOrigin;
Splice(e, e.Oprev);
}
eSym = e._otherHalfOfThisEdge;
if (eSym._nextEdgeCCWAroundOrigin == eSym)
{
KillVertex(eSym._originVertex, null);
}
else
{
/* Make sure that eSym.Org points to a valid half-edge */
eSym._originVertex._edgeThisIsOriginOf = eSym._nextEdgeCCWAroundOrigin;
Splice(eSym, eSym.Oprev);
}
KillEdge(e);
}
} while (e != eStart);
/* delete from circular doubly-linked list */
fPrev = fZap._prevFace;
fNext = fZap._nextFace;
fNext._prevFace = fPrev;
fPrev._nextFace = fNext;
fZap = null;
}
/* __gl_meshCheckMesh( mesh ) checks a mesh for self-consistency.
*/
public void CheckMesh()
{
Face fHead = _faceHead;
ContourVertex vHead = _vertexHead;
HalfEdge eHead = _halfEdgeHead;
Face f, fPrev;
ContourVertex v, vPrev;
HalfEdge e, ePrev;
fPrev = fHead;
for (fPrev = fHead; (f = fPrev._nextFace) != fHead; fPrev = f)
{
if (f._prevFace != fPrev)
{
throw new Exception();
}
e = f._halfEdgeThisIsLeftFaceOf;
do
{
if (e._otherHalfOfThisEdge == e)
{
throw new Exception();
}
if (e._otherHalfOfThisEdge._otherHalfOfThisEdge != e)
{
throw new Exception();
}
if (e._nextEdgeCCWAroundLeftFace._nextEdgeCCWAroundOrigin._otherHalfOfThisEdge != e)
{
throw new Exception();
}
if (e._nextEdgeCCWAroundOrigin._otherHalfOfThisEdge._nextEdgeCCWAroundLeftFace != e)
{
throw new Exception();
}
if (e._leftFace != f)
{
throw new Exception();
}
e = e._nextEdgeCCWAroundLeftFace;
} while (e != f._halfEdgeThisIsLeftFaceOf);
}
if (f._prevFace != fPrev || f._halfEdgeThisIsLeftFaceOf != null)
{
throw new Exception();
}
vPrev = vHead;
for (vPrev = vHead; (v = vPrev._nextVertex) != vHead; vPrev = v)
{
if (v._prevVertex != vPrev)
{
throw new Exception();
}
e = v._edgeThisIsOriginOf;
do
{
if (e._otherHalfOfThisEdge == e)
{
throw new Exception();
}
if (e._otherHalfOfThisEdge._otherHalfOfThisEdge != e)
{
throw new Exception();
}
if (e._nextEdgeCCWAroundLeftFace._nextEdgeCCWAroundOrigin._otherHalfOfThisEdge != e)
{
throw new Exception();
}
if (e._nextEdgeCCWAroundOrigin._otherHalfOfThisEdge._nextEdgeCCWAroundLeftFace != e)
{
throw new Exception();
}
if (e._originVertex != v)
{
throw new Exception();
}
e = e._nextEdgeCCWAroundOrigin;
} while (e != v._edgeThisIsOriginOf);
}
if (v._prevVertex != vPrev || v._edgeThisIsOriginOf != null || v._clientIndex != 0)
{
throw new Exception();
}
ePrev = eHead;
for (ePrev = eHead; (e = ePrev._nextHalfEdge) != eHead; ePrev = e)
{
if (e._otherHalfOfThisEdge._nextHalfEdge != ePrev._otherHalfOfThisEdge)
{
throw new Exception();
}
if (e._otherHalfOfThisEdge == e)
{
throw new Exception();
}
if (e._otherHalfOfThisEdge._otherHalfOfThisEdge != e)
{
throw new Exception();
}
if (e._originVertex == null)
{
throw new Exception();
}
if (e.DirectionVertex == null)
{
throw new Exception();
}
if (e._nextEdgeCCWAroundLeftFace._nextEdgeCCWAroundOrigin._otherHalfOfThisEdge != e)
{
throw new Exception();
}
if (e._nextEdgeCCWAroundOrigin._otherHalfOfThisEdge._nextEdgeCCWAroundLeftFace != e)
{
throw new Exception();
}
}
if (e._otherHalfOfThisEdge._nextHalfEdge != ePrev._otherHalfOfThisEdge
|| e._otherHalfOfThisEdge != _otherHalfOfThisEdgeHead
|| e._otherHalfOfThisEdge._otherHalfOfThisEdge != e
|| e._originVertex != null || e.DirectionVertex != null
|| e._leftFace != null || e.rightFace != null)
{
throw new Exception();
}
}
/* SetWindingNumber( value, keepOnlyBoundary ) resets the
* winding numbers on all edges so that regions marked "inside" the
* polygon have a winding number of "value", and regions outside
* have a winding number of 0.
*
* If keepOnlyBoundary is TRUE, it also deletes all edges which do not
* separate an interior region from an exterior one.
*/
public bool SetWindingNumber(int value, bool keepOnlyBoundary)
{
HalfEdge e, eNext;
for (e = _halfEdgeHead._nextHalfEdge; e != _halfEdgeHead; e = eNext)
{
eNext = e._nextHalfEdge;
if (e.rightFace._isInterior != e._leftFace._isInterior)
{
/* This is a boundary edge (one side is interior, one is exterior). */
e._winding = (e._leftFace._isInterior) ? value : -value;
}
else
{
/* Both regions are interior, or both are exterior. */
if (!keepOnlyBoundary)
{
e._winding = 0;
}
else
{
Mesh.DeleteHalfEdge(e);
}
}
}
return true;
}
/* DiscardExterior() zaps (ie. sets to NULL) all faces
* which are not marked "inside" the polygon. Since further mesh operations
* on NULL faces are not allowed, the main purpose is to clean up the
* mesh so that exterior loops are not represented in the data structure.
*/
public void DiscardExterior()
{
Face f, next;
for (f = _faceHead._nextFace; f != _faceHead; f = next)
{
/* Since f will be destroyed, save its next pointer. */
next = f._nextFace;
if (!f._isInterior)
{
Mesh.meshZapFace(f);
}
}
}
/* TessellateInterior() tessellates each region of
* the mesh which is marked "inside" the polygon. Each such region
* must be monotone.
*/
public bool TessellateInterior()
{
Face f, next;
for (f = _faceHead._nextFace; f != _faceHead; f = next)
{
/* Make sure we don''t try to tessellate the new triangles. */
next = f._nextFace;
if (f._isInterior)
{
if (!f.TessellateMonoRegion())
{
return false;
}
}
}
return true;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using DotNetOpenId;
using DotNetOpenId.Provider;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
namespace OpenSim.Server.Handlers.Authentication
{
public class OpenIdStreamHandler : BaseOutputStreamHandler
{
#region HTML
/// <summary>Page shown if the OpenID endpoint is requested directly</summary>
private const string ENDPOINT_PAGE =
@"<html><head><title>OpenID Endpoint</title></head><body>
This is an OpenID server endpoint, not a human-readable resource.
For more information, see <a href='http://openid.net/'>http://openid.net/</a>.
</body></html>";
/// <summary>Page shown for an invalid OpenID identity</summary>
private const string INVALID_OPENID_PAGE =
@"<html><head><title>Identity not found</title></head>
<body>Invalid OpenID identity</body></html>";
/// <summary>Login form used to authenticate OpenID requests</summary>
private const string LOGIN_PAGE =
@"<html>
<head><title>OpenSim OpenID Login</title></head>
<body>
<h3>OpenSim Login</h3>
<form method=""post"">
<label for=""first"">First Name:</label> <input readonly type=""text"" name=""first"" id=""first"" value=""{0}""/>
<label for=""last"">Last Name:</label> <input readonly type=""text"" name=""last"" id=""last"" value=""{1}""/>
<label for=""pass"">Password:</label> <input type=""password"" name=""pass"" id=""pass""/>
<input type=""submit"" value=""Login"">
</form>
</body>
</html>";
/// <summary>Page shown for a valid OpenID identity</summary>
private const string OPENID_PAGE =
@"<html>
<head>
<title>{2} {3}</title>
<link rel=""openid2.provider openid.server"" href=""{0}://{1}/openid/server/""/>
</head>
<body>OpenID identifier for {2} {3}</body>
</html>
";
#endregion HTML
private IAuthenticationService m_authenticationService;
private ProviderMemoryStore m_openidStore = new ProviderMemoryStore();
private IUserAccountService m_userAccountService;
/// <summary>
/// Constructor
/// </summary>
public OpenIdStreamHandler(
string httpMethod, string path, IUserAccountService userService, IAuthenticationService authService)
: base(httpMethod, path, "OpenId", "OpenID stream handler")
{
m_authenticationService = authService;
m_userAccountService = userService;
}
public override string ContentType { get { return "text/html"; } }
/// <summary>
/// Handles all GET and POST requests for OpenID identifier pages and endpoint
/// server communication
/// </summary>
protected override void ProcessRequest(
string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath));
// Defult to returning HTML content
httpResponse.ContentType = ContentType;
try
{
NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd());
NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query);
NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery);
OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery);
if (provider.Request != null)
{
if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest)
{
IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request;
string[] passwordValues = postQuery.GetValues("pass");
UserAccount account;
if (TryGetAccount(new Uri(authRequest.ClaimedIdentifier.ToString()), out account))
{
// Check for form POST data
if (passwordValues != null && passwordValues.Length == 1)
{
if (account != null &&
(m_authenticationService.Authenticate(account.PrincipalID, Util.Md5Hash(passwordValues[0]), 30) != string.Empty))
authRequest.IsAuthenticated = true;
else
authRequest.IsAuthenticated = false;
}
else
{
// Authentication was requested, send the client a login form
using (StreamWriter writer = new StreamWriter(response))
writer.Write(String.Format(LOGIN_PAGE, account.FirstName, account.LastName));
return;
}
}
else
{
// Cannot find an avatar matching the claimed identifier
authRequest.IsAuthenticated = false;
}
}
// Add OpenID headers to the response
foreach (string key in provider.Request.Response.Headers.Keys)
httpResponse.AddHeader(key, provider.Request.Response.Headers[key]);
string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type");
if (contentTypeValues != null && contentTypeValues.Length == 1)
httpResponse.ContentType = contentTypeValues[0];
// Set the response code and document body based on the OpenID result
httpResponse.StatusCode = (int)provider.Request.Response.Code;
response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length);
response.Close();
}
else if (httpRequest.Url.AbsolutePath.Contains("/openid/server"))
{
// Standard HTTP GET was made on the OpenID endpoint, send the client the default error page
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ENDPOINT_PAGE);
}
else
{
// Try and lookup this avatar
UserAccount account;
if (TryGetAccount(httpRequest.Url, out account))
{
using (StreamWriter writer = new StreamWriter(response))
{
// TODO: Print out a full profile page for this avatar
writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme,
httpRequest.Url.Authority, account.FirstName, account.LastName));
}
}
else
{
// Couldn't parse an avatar name, or couldn't find the avatar in the user server
using (StreamWriter writer = new StreamWriter(response))
writer.Write(INVALID_OPENID_PAGE);
}
}
}
catch (Exception ex)
{
httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
using (StreamWriter writer = new StreamWriter(response))
writer.Write(ex.Message);
}
}
/// <summary>
/// Parse a URL with a relative path of the form /users/First_Last and try to
/// retrieve the profile matching that avatar name
/// </summary>
/// <param name="requestUrl">URL to parse for an avatar name</param>
/// <param name="profile">Profile data for the avatar</param>
/// <returns>True if the parse and lookup were successful, otherwise false</returns>
private bool TryGetAccount(Uri requestUrl, out UserAccount account)
{
if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/")
{
// Parse the avatar name from the path
string username = requestUrl.Segments[requestUrl.Segments.Length - 1];
string[] name = username.Split('_');
if (name.Length == 2)
{
account = m_userAccountService.GetUserAccount(UUID.Zero, name[0], name[1]);
return (account != null);
}
}
account = null;
return false;
}
}
/// <summary>
/// Temporary, in-memory store for OpenID associations
/// </summary>
public class ProviderMemoryStore : IAssociationStore<AssociationRelyingPartyType>
{
private SortedList<DateTime, AssociationItem> m_sortedStore = new SortedList<DateTime, AssociationItem>();
private Dictionary<string, AssociationItem> m_store = new Dictionary<string, AssociationItem>();
private object m_syncRoot = new object();
private class AssociationItem
{
public AssociationRelyingPartyType DistinguishingFactor;
public DateTime Expires;
public string Handle;
public byte[] PrivateData;
}
#region IAssociationStore<AssociationRelyingPartyType> Members
public void ClearExpiredAssociations()
{
lock (m_syncRoot)
{
List<AssociationItem> itemsCopy = new List<AssociationItem>(m_sortedStore.Values);
DateTime now = DateTime.Now;
for (int i = 0; i < itemsCopy.Count; i++)
{
AssociationItem item = itemsCopy[i];
if (item.Expires <= now)
{
m_sortedStore.RemoveAt(i);
m_store.Remove(item.Handle);
}
}
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor)
{
lock (m_syncRoot)
{
if (m_sortedStore.Count > 0)
{
AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1];
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
}
else
{
return null;
}
}
}
public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
AssociationItem item;
bool success = false;
lock (m_syncRoot)
success = m_store.TryGetValue(handle, out item);
if (success)
return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData);
else
return null;
}
public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle)
{
lock (m_syncRoot)
{
for (int i = 0; i < m_sortedStore.Values.Count; i++)
{
AssociationItem item = m_sortedStore.Values[i];
if (item.Handle == handle)
{
m_sortedStore.RemoveAt(i);
break;
}
}
return m_store.Remove(handle);
}
}
public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc)
{
AssociationItem item = new AssociationItem();
item.DistinguishingFactor = distinguishingFactor;
item.Handle = assoc.Handle;
item.Expires = assoc.Expires.ToLocalTime();
item.PrivateData = assoc.SerializePrivateData();
lock (m_syncRoot)
{
m_store[item.Handle] = item;
m_sortedStore[item.Expires] = item;
}
}
#endregion IAssociationStore<AssociationRelyingPartyType> Members
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.Asn1;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.Protocols.TestTools.StackSdk.Security.Cryptographic;
using Microsoft.Protocols.TestTools.StackSdk.Security.KerberosLib;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.DirectoryServices.ActiveDirectory;
namespace Microsoft.Protocols.TestSuites.FileSharing.Auth.TestSuite
{
[TestClass]
public class KerberosAuthentication : AuthenticationTestBase
{
[Flags]
protected enum CaseVariant
{
NONE = 0,
AUTHENTICATOR_CNAME_NOT_MATCH = 1 << 0,
AUTHENTICATOR_CREALM_NOT_MATCH = 1 << 1,
AUTHENTICATOR_WRONG_ENC_KEY = 1 << 2,
AUTHENTICATOR_EXCEED_TIME_SKEW = 1 << 3,
TICKET_WRONG_REALM = 1 << 4,
TICKET_WRONG_SNAME = 1 << 5,
TICKET_WRONG_KVNO = 1 << 6,
TICKET_NOT_VALID = 1 << 7,
TICKET_EXPIRED = 1 << 8,
TICKET_WRONG_ENC_KEY = 1 << 9,
AUTHDATA_UNKNOWN_TYPE_IN_TKT = 1 << 10,
AUTHDATA_UNKNOWN_TYPE_IN_TKT_OPTIONAL = 1 << 11,
AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR = 1 << 12,
AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR_OPTIONAL = 1 << 13,
}
public const int DefaultKdcPort = 88;
public static bool IsComputerInDomain;
public static string KDCIP;
public static int KDCPort;
public static KerberosConstValue.OidPkt OidPkt;
public KerberosConstValue.GSSToken GssToken;
public KeyManager keyManager;
private string servicePrincipalName;
#region Test Initialize and Cleanup
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
Initialize(testContext);
BaseTestSite.Log.Add(LogEntryKind.Debug, "Check if current computer is in a domain.");
try
{
using (Domain domain = Domain.GetComputerDomain())
{
DomainController dc = domain.FindDomainController(LocatorOptions.KdcRequired);
KDCIP = dc.IPAddress;
IsComputerInDomain = true;
}
KDCPort = DefaultKdcPort;
OidPkt = KerberosConstValue.OidPkt.KerberosToken;
}
catch
{
IsComputerInDomain = false;
}
}
[ClassCleanup]
public static void ClassCleanup()
{
Cleanup();
}
protected override void TestInitialize()
{
base.TestInitialize();
if (!IsComputerInDomain)
{
BaseTestSite.Assert.Inconclusive("Kerberos Authentication test cases are not applicable in non-domain environment");
}
if (servicePrincipalName == null)
{
servicePrincipalName = Smb2Utility.GetCifsServicePrincipalName(TestConfig.SutComputerName);
}
switch (TestConfig.DefaultSecurityPackage)
{
case TestTools.StackSdk.Security.Sspi.SecurityPackageType.Negotiate:
GssToken = KerberosConstValue.GSSToken.GSSSPNG;
break;
case TestTools.StackSdk.Security.Sspi.SecurityPackageType.Kerberos:
GssToken = KerberosConstValue.GSSToken.GSSAPI;
break;
default:
BaseTestSite.Assert.Inconclusive("Security package: {0} is not applicable for Kerberos Authentication test cases",
TestConfig.DefaultSecurityPackage);
break;
}
}
protected override void TestCleanup()
{
base.TestCleanup();
}
#endregion
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[Description("This test case is designed to test whether server can handle Kerberos Authentication using GSSAPI correctly.")]
public void BVT_KerbAuth_AccessFile_Success()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.NONE);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("This test case is designed to test whether server can handle wrong cname in the Authenticator in AP_REQ.")]
public void KerbAuth_Authenticator_CNameNotMatch()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.AUTHENTICATOR_CNAME_NOT_MATCH);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("This test case is designed to test whether server can handle wrong crealm in the Authenticator in AP_REQ.")]
public void KerbAuth_Authenticator_CRealmNotMatch()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.AUTHENTICATOR_CREALM_NOT_MATCH);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.InvalidIdentifier)]
[Description("This test case is designed to test whether server can handle wrong encryption key of the Authenticator in AP_REQ.")]
public void KerbAuth_Authenticator_WrongEncKey()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.AUTHENTICATOR_WRONG_ENC_KEY);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle unknown Realm in the Ticket in AP_REQ.")]
public void KerbAuth_Ticket_WrongRealm()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.TICKET_WRONG_REALM);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle unknown SName in the Ticket in AP_REQ.")]
public void KerbAuth_Ticket_WrongSName()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.TICKET_WRONG_SNAME);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle invalid KVNO in the Ticket in AP_REQ.")]
public void KerbAuth_Ticket_WrongKvno()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.TICKET_WRONG_KVNO);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle invalid Ticket in AP_REQ.")]
public void KerbAuth_Ticket_NotValid()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.TICKET_NOT_VALID);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle expired Ticket in AP_REQ.")]
public void KerbAuth_Ticket_Expired()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.TICKET_EXPIRED);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle wrong encryption key of the Ticket in AP_REQ.")]
public void KerbAuth_Ticket_WrongEncKey()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.TICKET_WRONG_ENC_KEY);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle unknown AuthorizationData in the Ticket.")]
public void KerbAuth_AuthData_UnknownType_Ticket()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_TKT);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle " +
"unknown AuthorizationData contained in AD-IF-RELEVANT in the Ticket.")]
public void KerbAuth_AuthData_UnknownType_Optional_Ticket()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_TKT_OPTIONAL);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle unknown AuthorizationData in the Authenticator.")]
public void KerbAuth_AuthData_UnknownType_Authenticator()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle " +
"unknown AuthorizationData contained in AD-IF-RELEVANT in the Authenticator.")]
public void KerbAuth_AuthData_UnknownType_Optional_Authenticator()
{
LoadConfig();
Smb2KerberosAuthentication(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR_OPTIONAL);
}
[TestMethod]
[TestCategory(TestCategories.Auth)]
[TestCategory(TestCategories.KerberosAuthentication)]
[TestCategory(TestCategories.Positive)]
[Description("This test case is designed to test whether server can handle Replay correctly.")]
public void KerbAuth_Replay()
{
#region Get Service Ticket
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Initialize Kerberos Functional Client");
KerberosFunctionalClient kerberosClient = new KerberosFunctionalClient(
TestConfig.DomainName,
TestConfig.UserName,
TestConfig.UserPassword,
KerberosAccountType.User,
KDCIP,
KDCPort,
TransportType.TCP,
OidPkt,
BaseTestSite);
//Create and send AS request
const KdcOptions options = KdcOptions.FORWARDABLE | KdcOptions.CANONICALIZE | KdcOptions.RENEWABLE;
kerberosClient.SendAsRequest(options, null);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects Kerberos Error from KDC");
//Receive preauthentication required error
METHOD_DATA methodData;
KerberosKrbError krbError = kerberosClient.ExpectPreauthRequiredError(out methodData);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client sends AS request with PA-DATA set");
//Create sequence of PA data
string timeStamp = KerberosUtility.CurrentKerberosTime.Value;
PaEncTimeStamp paEncTimeStamp = new PaEncTimeStamp(timeStamp,
0,
kerberosClient.Context.SelectedEType,
kerberosClient.Context.CName.Password,
kerberosClient.Context.CName.Salt);
PaPacRequest paPacRequest = new PaPacRequest(true);
Asn1SequenceOf<PA_DATA> seqOfPaData = new Asn1SequenceOf<PA_DATA>(new[] { paEncTimeStamp.Data, paPacRequest.Data });
//Create and send AS request
kerberosClient.SendAsRequest(options, seqOfPaData);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects AS response from KDC");
KerberosAsResponse asResponse = kerberosClient.ExpectAsResponse();
BaseTestSite.Assert.IsNotNull(asResponse.Response.ticket, "AS response should contain a TGT.");
//Create and send TGS request
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client sends TGS request to KDC");
kerberosClient.SendTgsRequest(servicePrincipalName, options);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects TGS response from KDC");
KerberosTgsResponse tgsResponse = kerberosClient.ExpectTgsResponse();
BaseTestSite.Assert.AreEqual(servicePrincipalName,
KerberosUtility.PrincipalName2String(tgsResponse.Response.ticket.sname),
"Service principal name in service ticket should match expected.");
#endregion
#region Create AP request
Ticket serviceTicket = kerberosClient.Context.Ticket.Ticket;
Realm crealm = serviceTicket.realm;
EncryptionKey subkey = KerberosUtility.GenerateKey(kerberosClient.Context.SessionKey);
PrincipalName cname = kerberosClient.Context.CName.Name;
Authenticator authenticator = CreateAuthenticator(cname, crealm, subkey);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create AP Request");
KerberosApRequest request = new KerberosApRequest(
kerberosClient.Context.Pvno,
new APOptions(KerberosUtility.ConvertInt2Flags((int)ApOptions.MutualRequired)),
kerberosClient.Context.Ticket,
authenticator,
KeyUsageNumber.AP_REQ_Authenticator
);
#endregion
#region Create GSS token and send session setup request
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create GSS Token");
byte[] token = KerberosUtility.AddGssApiTokenHeader(request, OidPkt, GssToken);
Smb2FunctionalClientForKerbAuth smb2Client = new Smb2FunctionalClientForKerbAuth(TestConfig.Timeout, TestConfig, BaseTestSite);
smb2Client.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress);
byte[] repToken;
uint status = DoSessionSetupWithGssToken(smb2Client, token, out repToken);
KerberosApResponse apRep = kerberosClient.GetApResponseFromToken(repToken, GssToken);
// Get subkey from AP response, which used for signing in smb2
apRep.Decrypt(kerberosClient.Context.Ticket.SessionKey.keyvalue.ByteArrayValue);
smb2Client.SetSessionSigningAndEncryption(true, false, apRep.ApEncPart.subkey.keyvalue.ByteArrayValue);
#endregion
#region Second client
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Replay the request from another client");
Smb2FunctionalClientForKerbAuth smb2Client2 = new Smb2FunctionalClientForKerbAuth(TestConfig.Timeout, TestConfig, BaseTestSite);
smb2Client2.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress);
status = DoSessionSetupWithGssToken(smb2Client2, token, out repToken);
BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status,
"Session Setup should fail because it uses a Replay of KRB_AP_REQ");
if (TestConfig.IsWindowsPlatform)
{
krbError = kerberosClient.GetKrbErrorFromToken(repToken);
BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_REPEAT, krbError.ErrorCode,
"SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_REPEAT);
}
smb2Client2.Disconnect();
#endregion
string path = Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.BasicFileShare);
AccessFile(smb2Client, path);
smb2Client.LogOff();
smb2Client.Disconnect();
}
private void LoadConfig()
{
if (string.IsNullOrEmpty(TestConfig.KeytabFile) &&
(string.IsNullOrEmpty(TestConfig.ServicePassword) || string.IsNullOrEmpty(TestConfig.ServiceSaltString)))
{
BaseTestSite.Assert.Inconclusive("This case requires either Keytab file or cifs service password and salt string.");
}
keyManager = new KeyManager();
if (!string.IsNullOrEmpty(TestConfig.KeytabFile))
{
keyManager.LoadKeytab(TestConfig.KeytabFile);
}
else
{
keyManager.MakeKey(servicePrincipalName, TestConfig.DomainName, TestConfig.ServicePassword, TestConfig.ServiceSaltString);
}
}
private void Smb2KerberosAuthentication(CaseVariant variant)
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Initialize Kerberos Functional Client");
KerberosFunctionalClient kerberosClient = new KerberosFunctionalClient(
TestConfig.DomainName,
TestConfig.UserName,
TestConfig.UserPassword,
KerberosAccountType.User,
KDCIP,
KDCPort,
TransportType.TCP,
OidPkt,
BaseTestSite);
#region Service Ticket
EncryptionKey serviceKey;
EncTicketPart encTicketPart = RetrieveAndDecryptServiceTicket(kerberosClient, out serviceKey);
Ticket serviceTicket = kerberosClient.Context.Ticket.Ticket;
Realm crealm = serviceTicket.realm;
BaseTestSite.Assert.AreEqual(TestConfig.DomainName.ToLower(),
encTicketPart.crealm.Value.ToLower(),
"Realm name in service ticket encrypted part should match as expected, case insensitive");
BaseTestSite.Assert.AreEqual(TestConfig.UserName.ToLower(),
KerberosUtility.PrincipalName2String(encTicketPart.cname).ToLower(),
"User name in service ticket encrypted part should match as expected, case insensitive.");
if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_TKT))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Add a type-unknown AuthorizationData to the ticket");
AuthorizationDataElement unknownElement = GenerateUnKnownAuthorizationDataElement();
AppendNewAuthDataElement(encTicketPart.authorization_data, unknownElement);
}
if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_TKT_OPTIONAL))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Add a type-unknown AuthorizationData which is inside AD_IF_RELEVANT to the ticket");
AuthorizationDataElement unknownElement = GenerateUnKnownAuthorizationDataElement();
AD_IF_RELEVANT ifRelavantElement =
new AD_IF_RELEVANT(new[] { unknownElement });
var dataBuffer = new Asn1BerEncodingBuffer();
ifRelavantElement.BerEncode(dataBuffer);
AuthorizationDataElement unknownElementOptional =
new AuthorizationDataElement(new KerbInt32((long)AuthorizationData_elementType.AD_IF_RELEVANT), new Asn1OctetString(dataBuffer.Data));
AppendNewAuthDataElement(encTicketPart.authorization_data, unknownElementOptional);
}
if (variant.HasFlag(CaseVariant.TICKET_NOT_VALID))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Change the Ticket start time to tomorrow");
DateTime tomorrow = DateTime.Now.AddDays(1);
string kerbTimeString = tomorrow.ToUniversalTime().ToString("yyyyMMddhhmmssZ");
encTicketPart.starttime = new KerberosTime(kerbTimeString, true);
}
if (variant.HasFlag(CaseVariant.TICKET_EXPIRED))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Change the Ticket end time to yesterday");
DateTime yesterday = DateTime.Now.AddDays(-1);
string kerbTimeString = yesterday.ToUniversalTime().ToString("yyyyMMddhhmmssZ");
encTicketPart.endtime = new KerberosTime(kerbTimeString, true);
}
if (variant.HasFlag(CaseVariant.TICKET_WRONG_ENC_KEY))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Modify the Ticket, making it encrypted with wrong key");
serviceKey = KerberosUtility.GenerateKey(serviceKey);
}
EncryptedData data = EncryptTicket(encTicketPart, serviceKey);
serviceTicket.enc_part = data;
if (variant.HasFlag(CaseVariant.TICKET_WRONG_REALM))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Change the Realm in the Ticket to an unknown realm");
serviceTicket.realm = new Realm("kerb.com");
}
if (variant.HasFlag(CaseVariant.TICKET_WRONG_SNAME))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Change the SNAME in the Ticket to an unknown service name");
serviceTicket.sname = new PrincipalName(new KerbInt32((long)PrincipalType.NT_SRV_INST),
KerberosUtility.String2SeqKerbString("UnknownService", TestConfig.DomainName));
}
if (variant.HasFlag(CaseVariant.TICKET_WRONG_KVNO))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep,
"Change the KVNO in the Ticket to an invalid Key Version Number (Int32.MaxValue)");
const int invalidKvno = System.Int32.MaxValue;
serviceTicket.enc_part.kvno = new KerbInt32(invalidKvno);
}
#endregion
#region Authenticator
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create Authenticator");
EncryptionKey subkey = KerberosUtility.GenerateKey(kerberosClient.Context.SessionKey);
PrincipalName cname;
if (variant.HasFlag(CaseVariant.AUTHENTICATOR_CNAME_NOT_MATCH))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Use wrong cname in the Authenticator");
cname = new PrincipalName(new KerbInt32((long)PrincipalType.NT_PRINCIPAL),
KerberosUtility.String2SeqKerbString(TestConfig.NonAdminUserName, TestConfig.DomainName));
}
else
{
cname = kerberosClient.Context.CName.Name;
}
Authenticator authenticator = CreateAuthenticator(cname, crealm, subkey);
if (variant.HasFlag(CaseVariant.AUTHENTICATOR_CREALM_NOT_MATCH))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Use wrong crealm in the Authenticator");
authenticator.crealm = new Realm("kerb.com");
}
if (variant.HasFlag(CaseVariant.AUTHENTICATOR_EXCEED_TIME_SKEW))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Change the ctime in the Authenticator to one hour later");
DateTime oneHourLater = DateTime.Now.AddHours(1);
string kerbTimeString = oneHourLater.ToUniversalTime().ToString("yyyyMMddhhmmssZ");
authenticator.ctime = new KerberosTime(kerbTimeString, true);
}
if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Add a type-unknown AuthorizationData to the Authenticator");
AuthorizationDataElement unknownElement = GenerateUnKnownAuthorizationDataElement();
authenticator.authorization_data = new AuthorizationData(new[] { unknownElement });
}
if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR_OPTIONAL))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep,
"Add a type-unknown AuthorizationData which is inside AD_IF_RELEVANT to the Authenticator");
AuthorizationDataElement unknownElement = GenerateUnKnownAuthorizationDataElement();
AD_IF_RELEVANT ifRelavantElement =
new AD_IF_RELEVANT(new[] { unknownElement });
var dataBuffer = new Asn1BerEncodingBuffer();
ifRelavantElement.BerEncode(dataBuffer);
AuthorizationDataElement unknownElementOptional =
new AuthorizationDataElement(new KerbInt32((long)AuthorizationData_elementType.AD_IF_RELEVANT), new Asn1OctetString(dataBuffer.Data));
authenticator.authorization_data = new AuthorizationData(new[] { unknownElementOptional });
}
#endregion
#region AP Request
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create AP Request");
if (variant.HasFlag(CaseVariant.AUTHENTICATOR_WRONG_ENC_KEY))
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Use wrong key to encrypt the Authenticator");
kerberosClient.Context.Ticket.SessionKey = KerberosUtility.GenerateKey(kerberosClient.Context.Ticket.SessionKey);
}
KerberosApRequest request = new KerberosApRequest(
kerberosClient.Context.Pvno,
new APOptions(KerberosUtility.ConvertInt2Flags((int)ApOptions.MutualRequired)),
kerberosClient.Context.Ticket,
authenticator,
KeyUsageNumber.AP_REQ_Authenticator
);
#endregion
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create GSS Token");
byte[] token = KerberosUtility.AddGssApiTokenHeader(request, OidPkt, GssToken);
Smb2FunctionalClientForKerbAuth smb2Client = new Smb2FunctionalClientForKerbAuth(TestConfig.Timeout, TestConfig, BaseTestSite);
smb2Client.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress);
#region Check the result
byte[] repToken;
uint status = DoSessionSetupWithGssToken(smb2Client, token, out repToken);
if (variant.HasFlag(CaseVariant.AUTHENTICATOR_CNAME_NOT_MATCH) || variant.HasFlag(CaseVariant.AUTHENTICATOR_CREALM_NOT_MATCH))
{
BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status,
"Session Setup should fail because the cname or crealm in the authenticator does not match the same field in the Ticket");
if (TestConfig.IsWindowsPlatform)
{
KerberosKrbError krbError = kerberosClient.GetKrbErrorFromToken(repToken);
BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_BADMATCH, krbError.ErrorCode,
"SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_BADMATCH);
}
smb2Client.Disconnect();
return;
}
if (variant.HasFlag(CaseVariant.AUTHENTICATOR_WRONG_ENC_KEY) || variant.HasFlag(CaseVariant.TICKET_WRONG_ENC_KEY))
{
BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status,
"Session Setup should fail because Ticket or Authenticator cannot be correctly decrypted");
if (TestConfig.IsWindowsPlatform)
{
KerberosKrbError krbError = kerberosClient.GetKrbErrorFromToken(repToken);
BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_MODIFIED, krbError.ErrorCode,
"SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_MODIFIED);
}
smb2Client.Disconnect();
return;
}
if (variant.HasFlag(CaseVariant.AUTHENTICATOR_EXCEED_TIME_SKEW))
{
BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status,
"Session Setup should fail because the server time and the client time " +
"in the Authenticator differ by (1 hour) more than the allowable clock skew");
if (TestConfig.IsWindowsPlatform)
{
KerberosKrbError krbError = kerberosClient.GetKrbErrorFromToken(repToken);
BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_SKEW, krbError.ErrorCode,
"SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_SKEW);
}
smb2Client.Disconnect();
return;
}
if (variant.HasFlag(CaseVariant.TICKET_WRONG_KVNO) ||
variant.HasFlag(CaseVariant.TICKET_WRONG_REALM) ||
variant.HasFlag(CaseVariant.TICKET_WRONG_SNAME))
{
BaseTestSite.Log.Add(LogEntryKind.Comment, "If decryption fails, server would try other keys");
}
if (variant.HasFlag(CaseVariant.TICKET_NOT_VALID))
{
BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status,
"Session Setup should fail because the starttime (tomorrow) in the Ticket " +
"is later than the current time by more than the allowable clock skew");
if (TestConfig.IsWindowsPlatform)
{
KerberosKrbError krbError = kerberosClient.GetKrbErrorFromToken(repToken);
BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_TKT_NYV, krbError.ErrorCode,
"SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_TKT_NYV);
}
smb2Client.Disconnect();
return;
}
if (variant.HasFlag(CaseVariant.TICKET_EXPIRED))
{
BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status,
"Session Setup should fail because the current time is later than the endtime (yesterday)" +
" in the Ticket by more than the allowable clock skew");
if (TestConfig.IsWindowsPlatform)
{
KerberosKrbError krbError = kerberosClient.GetKrbErrorFromToken(repToken);
BaseTestSite.Assert.AreEqual(KRB_ERROR_CODE.KRB_AP_ERR_TKT_EXPIRED, krbError.ErrorCode,
"SMB Server should return {0}", KRB_ERROR_CODE.KRB_AP_ERR_TKT_EXPIRED);
}
smb2Client.Disconnect();
return;
}
if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_TKT))
{
BaseTestSite.Assert.AreNotEqual(Smb2Status.STATUS_SUCCESS, status,
"Session Setup should fail because of the unknown AutherizationData in the ticket");
smb2Client.Disconnect();
return;
}
if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR))
{
BaseTestSite.Log.Add(LogEntryKind.Comment,
"Unknown AuthorizationData in the Authenticator should not fail the request");
}
if (variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_TKT_OPTIONAL) ||
variant.HasFlag(CaseVariant.AUTHDATA_UNKNOWN_TYPE_IN_AUTHENTICATOR_OPTIONAL))
{
BaseTestSite.Log.Add(LogEntryKind.Comment, "Unknown AuthorizationData in AD_IF_RELEVANT is optional. " +
"Server should not fail the request.");
}
KerberosApResponse apRep = kerberosClient.GetApResponseFromToken(repToken, GssToken);
// Get subkey from AP response, which used for signing in smb2
apRep.Decrypt(kerberosClient.Context.Ticket.SessionKey.keyvalue.ByteArrayValue);
smb2Client.SetSessionSigningAndEncryption(true, false, apRep.ApEncPart.subkey.keyvalue.ByteArrayValue);
string path = Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.BasicFileShare);
AccessFile(smb2Client, path);
#endregion
smb2Client.LogOff();
smb2Client.Disconnect();
}
private EncTicketPart RetrieveAndDecryptServiceTicket(KerberosFunctionalClient kerberosClient, out EncryptionKey serviceKey)
{
//Create and send AS request
const KdcOptions options = KdcOptions.FORWARDABLE | KdcOptions.CANONICALIZE | KdcOptions.RENEWABLE;
kerberosClient.SendAsRequest(options, null);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects Kerberos Error from KDC");
//Receive preauthentication required error
METHOD_DATA methodData;
KerberosKrbError krbError = kerberosClient.ExpectPreauthRequiredError(out methodData);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client sends AS request with PA-DATA set");
//Create sequence of PA data
string timeStamp = KerberosUtility.CurrentKerberosTime.Value;
PaEncTimeStamp paEncTimeStamp = new PaEncTimeStamp(timeStamp,
0,
kerberosClient.Context.SelectedEType,
kerberosClient.Context.CName.Password,
kerberosClient.Context.CName.Salt);
PaPacRequest paPacRequest = new PaPacRequest(true);
Asn1SequenceOf<PA_DATA> seqOfPaData = new Asn1SequenceOf<PA_DATA>(new[] { paEncTimeStamp.Data, paPacRequest.Data });
//Create and send AS request
kerberosClient.SendAsRequest(options, seqOfPaData);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects AS response from KDC");
KerberosAsResponse asResponse = kerberosClient.ExpectAsResponse();
BaseTestSite.Assert.IsNotNull(asResponse.Response.ticket, "AS response should contain a TGT.");
//Create and send TGS request
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client sends TGS request to KDC");
kerberosClient.SendTgsRequest(servicePrincipalName, options);
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Kerberos Functional Client expects TGS response from KDC");
KerberosTgsResponse tgsResponse = kerberosClient.ExpectTgsResponse();
BaseTestSite.Assert.AreEqual(servicePrincipalName,
KerberosUtility.PrincipalName2String(tgsResponse.Response.ticket.sname),
"Service principal name in service ticket should match expected.");
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Decrypt SMB2 Service Ticket");
serviceKey = keyManager.QueryKey(servicePrincipalName, TestConfig.DomainName, kerberosClient.Context.SelectedEType);
tgsResponse.DecryptTicket(serviceKey);
return tgsResponse.TicketEncPart;
}
private EncryptedData EncryptTicket(EncTicketPart encTicketPart, EncryptionKey serviceKey)
{
Asn1BerEncodingBuffer encodeBuffer = new Asn1BerEncodingBuffer();
encTicketPart.BerEncode(encodeBuffer, true);
byte[] encData = KerberosUtility.Encrypt(
(EncryptionType)serviceKey.keytype.Value,
serviceKey.keyvalue.ByteArrayValue,
encodeBuffer.Data,
(int)KeyUsageNumber.AS_REP_TicketAndTGS_REP_Ticket);
return new EncryptedData(
new KerbInt32(serviceKey.keytype.Value),
null,
new Asn1OctetString(encData));
}
private Authenticator CreateAuthenticator(PrincipalName cname, Realm realm, EncryptionKey subkey = null, AuthorizationData data = null)
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Create authenticator");
Random r = new Random();
int seqNum = r.Next();
Authenticator plaintextAuthenticator = new Authenticator
{
authenticator_vno = new Asn1Integer(KerberosConstValue.KERBEROSV5),
crealm = realm,
cusec = new Microseconds(0),
ctime = KerberosUtility.CurrentKerberosTime,
seq_number = new KerbUInt32(seqNum),
cname = cname,
subkey = subkey,
authorization_data = data
};
AuthCheckSum checksum = new AuthCheckSum { Lgth = KerberosConstValue.AUTHENTICATOR_CHECKSUM_LENGTH };
checksum.Bnd = new byte[checksum.Lgth];
checksum.Flags = (int)(ChecksumFlags.GSS_C_MUTUAL_FLAG | ChecksumFlags.GSS_C_INTEG_FLAG);
byte[] checkData = ArrayUtility.ConcatenateArrays(BitConverter.GetBytes(checksum.Lgth),
checksum.Bnd, BitConverter.GetBytes(checksum.Flags));
plaintextAuthenticator.cksum = new Checksum(new KerbInt32((int)ChecksumType.ap_authenticator_8003), new Asn1OctetString(checkData));
return plaintextAuthenticator;
}
private uint DoSessionSetupWithGssToken(Smb2FunctionalClientForKerbAuth smb2Client,
byte[] gssTokenByte,
out byte[] repToken)
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Negotiate and SessionSetup using created gssToken");
smb2Client.Negotiate(TestConfig.RequestDialects, TestConfig.IsSMB1NegotiateEnabled);
uint status = smb2Client.SessionSetup(
Packet_Header_Flags_Values.NONE,
SESSION_SETUP_Request_Flags.NONE,
SESSION_SETUP_Request_SecurityMode_Values.NONE,
SESSION_SETUP_Request_Capabilities_Values.GLOBAL_CAP_DFS,
gssTokenByte,
out repToken);
return status;
}
private void AccessFile(Smb2FunctionalClientForKerbAuth smb2Client, string path)
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Try accessing files.");
uint treeId;
smb2Client.TreeConnect(path, out treeId);
Smb2CreateContextResponse[] serverCreateContexts;
FILEID fileId;
smb2Client.Create(
treeId,
Guid.NewGuid() + ".txt",
CreateOptions_Values.FILE_NON_DIRECTORY_FILE,
out fileId,
out serverCreateContexts);
smb2Client.Close(treeId, fileId);
smb2Client.TreeDisconnect(treeId);
}
private AuthorizationDataElement GenerateUnKnownAuthorizationDataElement()
{
byte[] randomData = new byte[100];
Random r = new Random();
r.NextBytes(randomData);
const int unknownType = Int16.MaxValue;
AuthorizationDataElement unknowElement = new AuthorizationDataElement(new KerbInt32(unknownType), new Asn1OctetString(randomData));
return unknowElement;
}
private void AppendNewAuthDataElement(AuthorizationData originalAuthData, AuthorizationDataElement newElement)
{
int elementNum = originalAuthData.Elements.Length;
AuthorizationDataElement[] elements = new AuthorizationDataElement[elementNum + 1];
originalAuthData.Elements.CopyTo(elements, 0);
elements[elementNum] = newElement;
originalAuthData.Elements = elements;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Test
{
public class OrderByTests
{
#region OrderBy Tests
//
// OrderBy
//
[Fact]
public static void RunOrderByTest1()
{
// Non-pipelining tests (synchronous channels).
RunOrderByTest1Core(0, false, DataDistributionType.AlreadyAscending);
RunOrderByTest1Core(0, true, DataDistributionType.AlreadyAscending);
RunOrderByTest1Core(50, false, DataDistributionType.AlreadyAscending);
RunOrderByTest1Core(50, false, DataDistributionType.AlreadyDescending);
RunOrderByTest1Core(50, false, DataDistributionType.Random);
RunOrderByTest1Core(50, true, DataDistributionType.AlreadyAscending);
RunOrderByTest1Core(50, true, DataDistributionType.AlreadyDescending);
RunOrderByTest1Core(50, true, DataDistributionType.Random);
RunOrderByTest1Core(1024 * 128, false, DataDistributionType.AlreadyAscending);
RunOrderByTest1Core(1024 * 128, false, DataDistributionType.AlreadyDescending);
RunOrderByTest1Core(1024 * 128, false, DataDistributionType.Random);
RunOrderByTest1Core(1024 * 128, true, DataDistributionType.AlreadyAscending);
RunOrderByTest1Core(1024 * 128, true, DataDistributionType.AlreadyDescending);
RunOrderByTest1Core(1024 * 128, true, DataDistributionType.Random);
}
[Fact]
public static void RunOrderByTest2()
{
// Pipelining tests (asynchronous channels).
RunOrderByTest2Core(1024 * 128, false, DataDistributionType.AlreadyAscending);
RunOrderByTest2Core(1024 * 128, false, DataDistributionType.AlreadyDescending);
RunOrderByTest2Core(1024 * 128, false, DataDistributionType.Random);
RunOrderByTest2Core(1024 * 128, true, DataDistributionType.AlreadyAscending);
RunOrderByTest2Core(1024 * 128, true, DataDistributionType.AlreadyDescending);
RunOrderByTest2Core(1024 * 128, true, DataDistributionType.Random);
}
[Fact]
public static void RunOrderByComposedWithTests()
{
// Try some composition tests (i.e. wrapping).
RunOrderByComposedWithWhere1(1024 * 128, false, DataDistributionType.Random);
RunOrderByComposedWithWhere1(1024 * 128, true, DataDistributionType.Random);
RunOrderByComposedWithWhere2(1024 * 128, false, DataDistributionType.Random);
RunOrderByComposedWithWhere2(1024 * 128, true, DataDistributionType.Random);
RunOrderByComposedWithJoinJoin(32, 32, false);
RunOrderByComposedWithJoinJoin(32, 32, true);
RunOrderByComposedWithWhereWhere1(1024 * 128, false, DataDistributionType.Random);
RunOrderByComposedWithWhereWhere1(1024 * 128, true, DataDistributionType.Random);
RunOrderByComposedWithWhereSelect1(1024 * 128, false, DataDistributionType.Random);
RunOrderByComposedWithWhereSelect1(1024 * 128, true, DataDistributionType.Random);
RunOrderByComposedWithOrderBy(1024 * 128, false, DataDistributionType.Random);
RunOrderByComposedWithOrderBy(1024 * 128, true, DataDistributionType.Random);
RunOrderByComposedWithOrderBy(1024 * 128, false, DataDistributionType.Random);
RunOrderByComposedWithOrderBy(1024 * 128, true, DataDistributionType.Random);
}
// To-do: Re-enable this long-running test as an outer-loop test
// [Fact]
public static void RunOrderByComposedWithJoinJoinTests_LongRunning()
{
RunOrderByComposedWithJoinJoin(1024 * 512, 1024 * 128, false);
RunOrderByComposedWithJoinJoin(1024 * 512, 1024 * 128, true);
}
[Fact]
public static void RunStableSortTest1()
{
// Stable sort.
RunStableSortTest1Core(1024);
RunStableSortTest1Core(1024 * 128);
}
//-----------------------------------------------------------------------------------
// Exercises basic OrderBy behavior by sorting a fixed set of integers. This always
// uses synchronous channels internally, i.e. by not pipelining.
//
private static void RunOrderByTest1Core(int dataSize, bool descending, DataDistributionType type)
{
int[] data = CreateOrderByInput(dataSize, type);
ParallelQuery<int> q;
if (descending)
{
q = data.AsParallel().OrderByDescending<int, int>(
delegate (int x) { return x; });
}
else
{
q = data.AsParallel().OrderBy<int, int>(
delegate (int x) { return x; });
}
// Force synchronous execution before validating results.
List<int> r = q.ToList<int>();
int prev = descending ? int.MaxValue : int.MinValue;
for (int i = 0; i < r.Count; i++)
{
int x = r[i];
if (descending ? x > prev : x < prev)
{
string method = string.Format("RunOrderByTest1(dataSize = {0}, descending = {1}, type = {2}) - synchronous/no pipeline:",
dataSize, descending, type);
Assert.True(false, string.Format(method + " > **ERROR** {0} came before {1} -- but isn't what we expected", prev, x));
}
prev = x;
}
}
//-----------------------------------------------------------------------------------
// Exercises basic OrderBy behavior by sorting a fixed set of integers. This always
// uses asynchronous channels internally, i.e. by pipelining.
//
private static void RunOrderByTest2Core(int dataSize, bool descending, DataDistributionType type)
{
int[] data = CreateOrderByInput(dataSize, type);
ParallelQuery<int> q;
if (descending)
{
q = data.AsParallel().OrderByDescending<int, int>(
delegate (int x) { return x; });
}
else
{
q = data.AsParallel().OrderBy<int, int>(
delegate (int x) { return x; });
}
int prev = descending ? int.MaxValue : int.MinValue;
foreach (int x in q)
{
if (descending ? x > prev : x < prev)
{
string method = string.Format("RunOrderByTest2(dataSize = {0}, descending = {1}, type = {2}) - asynchronous/pipeline:",
dataSize, descending, type);
Assert.True(false, string.Format(method + " > **ERROR** {0} came before {1} -- but isn't what we expected", prev, x)); ;
}
prev = x;
}
}
//-----------------------------------------------------------------------------------
// If sort is followed by another operator, we need to preserve key ordering all the
// way back up to the merge. That is true even if some elements are missing in the
// output data stream. This test tries to compose ORDERBY with WHERE. This test
// processes output sequentially (not pipelined).
//
private static void RunOrderByComposedWithWhere1(int dataSize, bool descending, DataDistributionType type)
{
int[] data = CreateOrderByInput(dataSize, type);
ParallelQuery<int> q;
// Create the ORDERBY:
if (descending)
{
q = data.AsParallel().OrderByDescending<int, int>(
delegate (int x) { return x; });
}
else
{
q = data.AsParallel().OrderBy<int, int>(
delegate (int x) { return x; });
}
// Wrap with a WHERE:
q = q.Where<int>(delegate (int x) { return (x % 2) == 0; });
// Force synchronous execution before validating results.
List<int> results = q.ToList<int>();
int prev = descending ? int.MaxValue : int.MinValue;
for (int i = 0; i < results.Count; i++)
{
int x = results[i];
if (descending ? x > prev : x < prev)
{
string method = string.Format("RunOrderByComposedWithWhere1(dataSize = {0}, descending = {1}, type = {2}) - sequential/no pipeline:",
dataSize, descending, type);
Assert.True(false, string.Format(method + " > **ERROR** {0} came before {1} -- but isn't what we expected", prev, x));
}
prev = x;
}
}
//-----------------------------------------------------------------------------------
// If sort is followed by another operator, we need to preserve key ordering all the
// way back up to the merge. That is true even if some elements are missing in the
// output data stream. This test tries to compose ORDERBY with WHERE. This test
// processes output asynchronously via pipelining.
//
private static void RunOrderByComposedWithWhere2(int dataSize, bool descending, DataDistributionType type)
{
int[] data = CreateOrderByInput(dataSize, type);
ParallelQuery<int> q;
// Create the ORDERBY:
if (descending)
{
q = data.AsParallel().OrderByDescending<int, int>(
delegate (int x) { return x; });
}
else
{
q = data.AsParallel().OrderBy<int, int>(
delegate (int x) { return x; });
}
// Wrap with a WHERE:
q = q.Where<int>(delegate (int x) { return (x % 2) == 0; });
int prev = descending ? int.MaxValue : int.MinValue;
foreach (int x in q)
{
if (descending ? x > prev : x < prev)
{
string method = string.Format("RunOrderByComposedWithWhere2(dataSize = {0}, descending = {1}, type = {2}) - async/pipeline",
dataSize, descending, type);
Assert.True(false, string.Format(method + " > **ERROR** {0} came before {1} -- but isn't what we expected", prev, x));
}
prev = x;
}
}
private static void RunOrderByComposedWithJoinJoin(int outerSize, int innerSize, bool descending)
{
// Generate data in the reverse order in which it'll be sorted.
DataDistributionType type = descending ? DataDistributionType.AlreadyAscending : DataDistributionType.AlreadyDescending;
int[] left = CreateOrderByInput(outerSize, type);
int[] right = CreateOrderByInput(innerSize, type);
int min = outerSize >= innerSize ? innerSize : outerSize;
int[] middle = new int[min];
if (descending)
for (int i = middle.Length; i > 0; i--)
middle[i - 1] = i;
else
for (int i = 0; i < middle.Length; i++)
middle[i] = i;
Func<int, int> identityKeySelector = delegate (int x) { return x; };
// Create the sort object.
ParallelQuery<int> sortedLeft;
if (descending)
{
sortedLeft = left.AsParallel().OrderByDescending<int, int>(identityKeySelector);
}
else
{
sortedLeft = left.AsParallel().OrderBy<int, int>(identityKeySelector);
}
// and now the join...
ParallelQuery<Pair<int, int>> innerJoin = sortedLeft.Join<int, int, int, Pair<int, int>>(
right.AsParallel(), identityKeySelector, identityKeySelector, delegate (int x, int y) { return new Pair<int, int>(x, y); });
ParallelQuery<int> outerJoin = innerJoin.Join<Pair<int, int>, int, int, int>(
middle.AsParallel(), delegate (Pair<int, int> p) { return p.First; }, identityKeySelector, delegate (Pair<int, int> x, int y) { return x.First; });
// Ensure pairs are of equal values, and that they are in ascending or descending order.
int cnt = 0;
int? last = null;
string method = string.Format("RunOrderByComposedWithJoinJoin(outerSize = {0}, innerSize = {1}, descending = {2})",
outerSize, innerSize, descending);
foreach (int p in outerJoin)
{
cnt++;
if (!((last == null || ((last.Value <= p && !descending) || (last.Value >= p && descending)))))
{
Assert.True(false, string.Format(method + " > *ERROR: sort order not correct: last = {0}, curr = {1}", last.Value, p));
}
last = p;
}
}
//-----------------------------------------------------------------------------------
// If sort is followed by another operator, we need to preserve key ordering all the
// way back up to the merge. That is true even if some elements are missing in the
// output data stream. This test tries to compose ORDERBY with two WHEREs. This test
// processes output sequentially (not pipelined).
//
private static void RunOrderByComposedWithWhereWhere1(int dataSize, bool descending, DataDistributionType type)
{
int[] data = CreateOrderByInput(dataSize, type);
ParallelQuery<int> q;
// Create the ORDERBY:
if (descending)
{
q = data.AsParallel().OrderByDescending<int, int>(
delegate (int x) { return x; });
}
else
{
q = data.AsParallel().OrderBy<int, int>(
delegate (int x) { return x; });
}
// Wrap with a WHERE:
q = q.Where<int>(delegate (int x) { return (x % 2) == 0; });
// Wrap with another WHERE:
q = q.Where<int>(delegate (int x) { return (x % 4) == 0; });
// Force synchronous execution before validating results.
List<int> results = q.ToList<int>();
int prev = descending ? int.MaxValue : int.MinValue;
foreach (int x in results)
{
if (descending ? x > prev : x < prev)
{
string method = string.Format("RunOrderByComposedWithWhereWhere1(dataSize = {0}, descending = {1}, type = {2}) - sequential/no pipeline",
dataSize, descending, type);
Assert.True(false, string.Format(method + " > **ERROR** {0} came before {1} -- but isn't what we expected", prev, x));
}
prev = x;
}
}
//-----------------------------------------------------------------------------------
// If sort is followed by another operator, we need to preserve key ordering all the
// way back up to the merge. That is true even if some elements are missing in the
// output data stream. This test tries to compose ORDERBY with WHERE and SELECT.
// This test processes output sequentially (not pipelined).
//
// This is particularly interesting because the SELECT completely loses the original
// type information in the tree, yet the merge is able to put things back in order.
//
private static void RunOrderByComposedWithWhereSelect1(int dataSize, bool descending, DataDistributionType type)
{
int[] data = CreateOrderByInput(dataSize, type);
ParallelQuery<int> q0;
// Create the ORDERBY:
if (descending)
{
q0 = data.AsParallel().OrderByDescending<int, int>(
delegate (int x) { return x; });
}
else
{
q0 = data.AsParallel().OrderBy<int, int>(
delegate (int x) { return x; });
}
// Wrap with a WHERE:
q0 = q0.Where<int>(delegate (int x) { return (x % 2) == 0; });
// Wrap with a SELECT:
ParallelQuery<string> q1 = q0.Select<int, string>(delegate (int x) { return x.ToString(); });
// Force synchronous execution before validating results.
List<string> results = q1.ToList<string>();
int prev = descending ? int.MaxValue : int.MinValue;
foreach (string xs in results)
{
int x = int.Parse(xs);
if (descending ? x > prev : x < prev)
{
string method = string.Format("RunOrderByComposedWithWhereSelect1(dataSize = {0}, descending = {1}, type = {2}) - sequential/no pipeline",
dataSize, descending, type);
Assert.True(false, string.Format(method + " > **ERROR** {0} came before {1} -- but isn't what we expected", prev, x));
}
prev = x;
}
}
//-----------------------------------------------------------------------------------
// Nested sorts.
//
private static void RunOrderByComposedWithOrderBy(int dataSize, bool descending, DataDistributionType type)
{
int[] data = CreateOrderByInput(dataSize, type);
ParallelQuery<int> q;
// Create the ORDERBY:
if (!descending)
{
q = data.AsParallel().OrderByDescending<int, int>(
delegate (int x) { return x; });
}
else
{
q = data.AsParallel().OrderBy<int, int>(
delegate (int x) { return x; });
}
// Wrap with a WHERE:
q = q.Where<int>(delegate (int x) { return (x % 2) == 0; });
// And wrap with another ORDERBY:
if (descending)
{
q = q.OrderByDescending<int, int>(delegate (int x) { return x; });
}
else
{
q = q.OrderBy<int, int>(delegate (int x) { return x; });
}
// Force synchronous execution before validating results.
List<int> results = q.ToList<int>();
int prev = descending ? int.MaxValue : int.MinValue;
for (int i = 0; i < results.Count; i++)
{
int x = results[i];
if (descending ? x > prev : x < prev)
{
string method = string.Format("RunOrderByComposedWithOrderBy(dataSize = {0}, descending = {1}, type = {2}) - sequential/no pipeline",
dataSize, descending, type);
Assert.True(false, string.Format(method + " > **ERROR** {0} came before {1} -- but isn't what we expected", prev, x));
}
prev = x;
}
}
//-----------------------------------------------------------------------------------
// Stable sort implementation: uses indices, OrderBy, ThenBy.
//
private static void RunStableSortTest1Core(int dataSize)
{
SSC[] clist = new SSC[dataSize];
for (int i = 0; i < clist.Length; i++)
{
clist[i] = new SSC((dataSize - i) / (dataSize / 5), i);
}
IEnumerable<SSC> clistSorted = clist.AsParallel().Select<SSC, SSD>((c, i) => new SSD(c, i)).OrderBy<SSD, int>((c) => c.c.SortKey).ThenBy<SSD, int>((c) => c.idx).Select((c) => c.c);
int lastKey = -1, lastIdx = -1;
string method = string.Format("RunStableSortTest1(dataSize = {0}) - synchronous/no pipeline", dataSize);
foreach (SSC c in clistSorted)
{
if (c.SortKey < lastKey)
{
Assert.True(false, string.Format(method + " > FAILED. Keys not in ascending order: {0} expected to be <= {1}", lastKey, c.SortKey));
}
else if (c.SortKey == lastKey && c.Index < lastIdx)
{
Assert.True(false, string.Format(method + " > FAILED. Instability on equal keys: {0} expected to be <= {1}", lastIdx, c.Index));
}
lastKey = c.SortKey;
lastIdx = c.Index;
}
}
#endregion
#region Helper methods
//-----------------------------------------------------------------------------------
// A pair just wraps two bits of data into a single addressable unit. This is a
// value type to ensure it remains very lightweight, since it is frequently used
// with other primitive data types as well.
//
// Note: this class is another copy of the Pair<T, U> class defined in CommonDataTypes.cs.
// For now, we have a copy of the class here, because we can't import the System.Linq.Parallel
// namespace.
//
private struct Pair<T, U>
{
// The first and second bits of data.
internal T m_first;
internal U m_second;
//-----------------------------------------------------------------------------------
// A simple constructor that initializes the first/second fields.
//
public Pair(T first, U second)
{
m_first = first;
m_second = second;
}
//-----------------------------------------------------------------------------------
// Accessors for the left and right data.
//
public T First
{
get { return m_first; }
set { m_first = value; }
}
public U Second
{
get { return m_second; }
set { m_second = value; }
}
}
private class SSC
{
public int SortKey;
public int Index;
public SSC(int key, int idx)
{
SortKey = key; Index = idx;
}
}
private class SSD
{
public SSC c;
public int idx;
public SSD(SSC c, int idx)
{
this.c = c; this.idx = idx;
}
}
private static int[] CreateOrderByInput(int dataSize, DataDistributionType type)
{
int[] data = new int[dataSize];
switch (type)
{
case DataDistributionType.AlreadyAscending:
for (int i = 0; i < data.Length; i++)
data[i] = i;
break;
case DataDistributionType.AlreadyDescending:
for (int i = 0; i < data.Length; i++)
data[i] = dataSize - i;
break;
case DataDistributionType.Random:
//Random rand = new Random();
for (int i = 0; i < data.Length; i++)
data[i] = ValueHelper.Next();
break;
}
return data;
}
enum DataDistributionType
{
AlreadyAscending,
AlreadyDescending,
Random
}
private static class ValueHelper
{
private const string text =
@"Pseudo-random numbers are chosen with equal probability from a finite set of numbers. The chosen numbers are
not completely random because a definite mathematical algorithm is used to select them, but they are sufficiently
random for practical purposes. The current implementation of the Random class is based on a modified version of
Donald E. Knuth's subtractive random number generator algorithm. For more information, see D. E. Knuth.
The Art of Computer Programming, volume 2: Seminumerical Algorithms. Addison-Wesley, Reading, MA, second edition,
1981. The random number generation starts from a seed value. If the same seed is used repeatedly, the
same series of numbers is generated. One way to produce different sequences is to make the seed value
time-dependent, thereby producing a different series with each new instance of Random. By default, the
parameterless constructor of the Random class uses the system clock to generate its seed value, while
its parameterized constructor can take an Int32 value based on the number of ticks in the current time.
However, because the clock has finite resolution, using the parameterless constructor to create different
Random objects in close succession creates random number generators that produce identical sequences of
random numbers. The following example illustrates that two Random objects that are instantiated in close
succession generate an identical series of random numbers. ";
private static int _currentPosition = 0;
private static StartPosition _currentStart = StartPosition.Beginning;
private static readonly int _middlePosition = text.Length / 2;
public static int Next()
{
int nextPosition;
switch (_currentStart)
{
case StartPosition.Beginning:
case StartPosition.Middle:
nextPosition = (_currentPosition + 1) % text.Length;
break;
case StartPosition.End:
nextPosition = (_currentPosition - 1) % text.Length;
break;
default:
throw new ArgumentException(string.Format("Enum does not exist {0}", _currentStart));
}
if ((nextPosition == 0 && _currentStart != StartPosition.Middle)
|| (nextPosition == _middlePosition && _currentStart == StartPosition.Middle))
{
_currentStart = (StartPosition)(((int)_currentStart + 1) % 3);
switch (_currentStart)
{
case StartPosition.Beginning:
nextPosition = 0;
break;
case StartPosition.Middle:
nextPosition = _middlePosition;
break;
case StartPosition.End:
nextPosition = text.Length - 1;
break;
default:
throw new ArgumentException(string.Format("Enum does not exist {0}", _currentStart));
}
}
int lengthOfText = text.Length;
_currentPosition = nextPosition;
char charValue = text[_currentPosition];
return (int)charValue;
}
enum StartPosition
{
Beginning = 0,
Middle = 1,
End = 2
}
}
#endregion
}
}
| |
namespace Unicorn.Mips
{
/// <summary>
/// Represents the registers of an <see cref="MipsEmulator"/>.
/// </summary>
public class MipsRegisters : Registers
{
internal MipsRegisters(Emulator emulator) : base(emulator)
{
// Space
}
// Generated by gen_reg_properties.py.
/// <summary>
/// Gets or sets the value of PC register.
/// </summary>
public long PC
{
get { return Read(1); }
set { Write(1, value); }
}
/// <summary>
/// Gets or sets the value of _0 register.
/// </summary>
public long _0
{
get { return Read(2); }
set { Write(2, value); }
}
/// <summary>
/// Gets or sets the value of _1 register.
/// </summary>
public long _1
{
get { return Read(3); }
set { Write(3, value); }
}
/// <summary>
/// Gets or sets the value of _2 register.
/// </summary>
public long _2
{
get { return Read(4); }
set { Write(4, value); }
}
/// <summary>
/// Gets or sets the value of _3 register.
/// </summary>
public long _3
{
get { return Read(5); }
set { Write(5, value); }
}
/// <summary>
/// Gets or sets the value of _4 register.
/// </summary>
public long _4
{
get { return Read(6); }
set { Write(6, value); }
}
/// <summary>
/// Gets or sets the value of _5 register.
/// </summary>
public long _5
{
get { return Read(7); }
set { Write(7, value); }
}
/// <summary>
/// Gets or sets the value of _6 register.
/// </summary>
public long _6
{
get { return Read(8); }
set { Write(8, value); }
}
/// <summary>
/// Gets or sets the value of _7 register.
/// </summary>
public long _7
{
get { return Read(9); }
set { Write(9, value); }
}
/// <summary>
/// Gets or sets the value of _8 register.
/// </summary>
public long _8
{
get { return Read(10); }
set { Write(10, value); }
}
/// <summary>
/// Gets or sets the value of _9 register.
/// </summary>
public long _9
{
get { return Read(11); }
set { Write(11, value); }
}
/// <summary>
/// Gets or sets the value of _10 register.
/// </summary>
public long _10
{
get { return Read(12); }
set { Write(12, value); }
}
/// <summary>
/// Gets or sets the value of _11 register.
/// </summary>
public long _11
{
get { return Read(13); }
set { Write(13, value); }
}
/// <summary>
/// Gets or sets the value of _12 register.
/// </summary>
public long _12
{
get { return Read(14); }
set { Write(14, value); }
}
/// <summary>
/// Gets or sets the value of _13 register.
/// </summary>
public long _13
{
get { return Read(15); }
set { Write(15, value); }
}
/// <summary>
/// Gets or sets the value of _14 register.
/// </summary>
public long _14
{
get { return Read(16); }
set { Write(16, value); }
}
/// <summary>
/// Gets or sets the value of _15 register.
/// </summary>
public long _15
{
get { return Read(17); }
set { Write(17, value); }
}
/// <summary>
/// Gets or sets the value of _16 register.
/// </summary>
public long _16
{
get { return Read(18); }
set { Write(18, value); }
}
/// <summary>
/// Gets or sets the value of _17 register.
/// </summary>
public long _17
{
get { return Read(19); }
set { Write(19, value); }
}
/// <summary>
/// Gets or sets the value of _18 register.
/// </summary>
public long _18
{
get { return Read(20); }
set { Write(20, value); }
}
/// <summary>
/// Gets or sets the value of _19 register.
/// </summary>
public long _19
{
get { return Read(21); }
set { Write(21, value); }
}
/// <summary>
/// Gets or sets the value of _20 register.
/// </summary>
public long _20
{
get { return Read(22); }
set { Write(22, value); }
}
/// <summary>
/// Gets or sets the value of _21 register.
/// </summary>
public long _21
{
get { return Read(23); }
set { Write(23, value); }
}
/// <summary>
/// Gets or sets the value of _22 register.
/// </summary>
public long _22
{
get { return Read(24); }
set { Write(24, value); }
}
/// <summary>
/// Gets or sets the value of _23 register.
/// </summary>
public long _23
{
get { return Read(25); }
set { Write(25, value); }
}
/// <summary>
/// Gets or sets the value of _24 register.
/// </summary>
public long _24
{
get { return Read(26); }
set { Write(26, value); }
}
/// <summary>
/// Gets or sets the value of _25 register.
/// </summary>
public long _25
{
get { return Read(27); }
set { Write(27, value); }
}
/// <summary>
/// Gets or sets the value of _26 register.
/// </summary>
public long _26
{
get { return Read(28); }
set { Write(28, value); }
}
/// <summary>
/// Gets or sets the value of _27 register.
/// </summary>
public long _27
{
get { return Read(29); }
set { Write(29, value); }
}
/// <summary>
/// Gets or sets the value of _28 register.
/// </summary>
public long _28
{
get { return Read(30); }
set { Write(30, value); }
}
/// <summary>
/// Gets or sets the value of _29 register.
/// </summary>
public long _29
{
get { return Read(31); }
set { Write(31, value); }
}
/// <summary>
/// Gets or sets the value of _30 register.
/// </summary>
public long _30
{
get { return Read(32); }
set { Write(32, value); }
}
/// <summary>
/// Gets or sets the value of _31 register.
/// </summary>
public long _31
{
get { return Read(33); }
set { Write(33, value); }
}
/// <summary>
/// Gets or sets the value of DSPCCOND register.
/// </summary>
public long DSPCCOND
{
get { return Read(34); }
set { Write(34, value); }
}
/// <summary>
/// Gets or sets the value of DSPCARRY register.
/// </summary>
public long DSPCARRY
{
get { return Read(35); }
set { Write(35, value); }
}
/// <summary>
/// Gets or sets the value of DSPEFI register.
/// </summary>
public long DSPEFI
{
get { return Read(36); }
set { Write(36, value); }
}
/// <summary>
/// Gets or sets the value of DSPOUTFLAG register.
/// </summary>
public long DSPOUTFLAG
{
get { return Read(37); }
set { Write(37, value); }
}
/// <summary>
/// Gets or sets the value of DSPOUTFLAG16_19 register.
/// </summary>
public long DSPOUTFLAG16_19
{
get { return Read(38); }
set { Write(38, value); }
}
/// <summary>
/// Gets or sets the value of DSPOUTFLAG20 register.
/// </summary>
public long DSPOUTFLAG20
{
get { return Read(39); }
set { Write(39, value); }
}
/// <summary>
/// Gets or sets the value of DSPOUTFLAG21 register.
/// </summary>
public long DSPOUTFLAG21
{
get { return Read(40); }
set { Write(40, value); }
}
/// <summary>
/// Gets or sets the value of DSPOUTFLAG22 register.
/// </summary>
public long DSPOUTFLAG22
{
get { return Read(41); }
set { Write(41, value); }
}
/// <summary>
/// Gets or sets the value of DSPOUTFLAG23 register.
/// </summary>
public long DSPOUTFLAG23
{
get { return Read(42); }
set { Write(42, value); }
}
/// <summary>
/// Gets or sets the value of DSPPOS register.
/// </summary>
public long DSPPOS
{
get { return Read(43); }
set { Write(43, value); }
}
/// <summary>
/// Gets or sets the value of DSPSCOUNT register.
/// </summary>
public long DSPSCOUNT
{
get { return Read(44); }
set { Write(44, value); }
}
/// <summary>
/// Gets or sets the value of AC0 register.
/// </summary>
public long AC0
{
get { return Read(45); }
set { Write(45, value); }
}
/// <summary>
/// Gets or sets the value of AC1 register.
/// </summary>
public long AC1
{
get { return Read(46); }
set { Write(46, value); }
}
/// <summary>
/// Gets or sets the value of AC2 register.
/// </summary>
public long AC2
{
get { return Read(47); }
set { Write(47, value); }
}
/// <summary>
/// Gets or sets the value of AC3 register.
/// </summary>
public long AC3
{
get { return Read(48); }
set { Write(48, value); }
}
/// <summary>
/// Gets or sets the value of CC0 register.
/// </summary>
public long CC0
{
get { return Read(49); }
set { Write(49, value); }
}
/// <summary>
/// Gets or sets the value of CC1 register.
/// </summary>
public long CC1
{
get { return Read(50); }
set { Write(50, value); }
}
/// <summary>
/// Gets or sets the value of CC2 register.
/// </summary>
public long CC2
{
get { return Read(51); }
set { Write(51, value); }
}
/// <summary>
/// Gets or sets the value of CC3 register.
/// </summary>
public long CC3
{
get { return Read(52); }
set { Write(52, value); }
}
/// <summary>
/// Gets or sets the value of CC4 register.
/// </summary>
public long CC4
{
get { return Read(53); }
set { Write(53, value); }
}
/// <summary>
/// Gets or sets the value of CC5 register.
/// </summary>
public long CC5
{
get { return Read(54); }
set { Write(54, value); }
}
/// <summary>
/// Gets or sets the value of CC6 register.
/// </summary>
public long CC6
{
get { return Read(55); }
set { Write(55, value); }
}
/// <summary>
/// Gets or sets the value of CC7 register.
/// </summary>
public long CC7
{
get { return Read(56); }
set { Write(56, value); }
}
/// <summary>
/// Gets or sets the value of F0 register.
/// </summary>
public long F0
{
get { return Read(57); }
set { Write(57, value); }
}
/// <summary>
/// Gets or sets the value of F1 register.
/// </summary>
public long F1
{
get { return Read(58); }
set { Write(58, value); }
}
/// <summary>
/// Gets or sets the value of F2 register.
/// </summary>
public long F2
{
get { return Read(59); }
set { Write(59, value); }
}
/// <summary>
/// Gets or sets the value of F3 register.
/// </summary>
public long F3
{
get { return Read(60); }
set { Write(60, value); }
}
/// <summary>
/// Gets or sets the value of F4 register.
/// </summary>
public long F4
{
get { return Read(61); }
set { Write(61, value); }
}
/// <summary>
/// Gets or sets the value of F5 register.
/// </summary>
public long F5
{
get { return Read(62); }
set { Write(62, value); }
}
/// <summary>
/// Gets or sets the value of F6 register.
/// </summary>
public long F6
{
get { return Read(63); }
set { Write(63, value); }
}
/// <summary>
/// Gets or sets the value of F7 register.
/// </summary>
public long F7
{
get { return Read(64); }
set { Write(64, value); }
}
/// <summary>
/// Gets or sets the value of F8 register.
/// </summary>
public long F8
{
get { return Read(65); }
set { Write(65, value); }
}
/// <summary>
/// Gets or sets the value of F9 register.
/// </summary>
public long F9
{
get { return Read(66); }
set { Write(66, value); }
}
/// <summary>
/// Gets or sets the value of F10 register.
/// </summary>
public long F10
{
get { return Read(67); }
set { Write(67, value); }
}
/// <summary>
/// Gets or sets the value of F11 register.
/// </summary>
public long F11
{
get { return Read(68); }
set { Write(68, value); }
}
/// <summary>
/// Gets or sets the value of F12 register.
/// </summary>
public long F12
{
get { return Read(69); }
set { Write(69, value); }
}
/// <summary>
/// Gets or sets the value of F13 register.
/// </summary>
public long F13
{
get { return Read(70); }
set { Write(70, value); }
}
/// <summary>
/// Gets or sets the value of F14 register.
/// </summary>
public long F14
{
get { return Read(71); }
set { Write(71, value); }
}
/// <summary>
/// Gets or sets the value of F15 register.
/// </summary>
public long F15
{
get { return Read(72); }
set { Write(72, value); }
}
/// <summary>
/// Gets or sets the value of F16 register.
/// </summary>
public long F16
{
get { return Read(73); }
set { Write(73, value); }
}
/// <summary>
/// Gets or sets the value of F17 register.
/// </summary>
public long F17
{
get { return Read(74); }
set { Write(74, value); }
}
/// <summary>
/// Gets or sets the value of F18 register.
/// </summary>
public long F18
{
get { return Read(75); }
set { Write(75, value); }
}
/// <summary>
/// Gets or sets the value of F19 register.
/// </summary>
public long F19
{
get { return Read(76); }
set { Write(76, value); }
}
/// <summary>
/// Gets or sets the value of F20 register.
/// </summary>
public long F20
{
get { return Read(77); }
set { Write(77, value); }
}
/// <summary>
/// Gets or sets the value of F21 register.
/// </summary>
public long F21
{
get { return Read(78); }
set { Write(78, value); }
}
/// <summary>
/// Gets or sets the value of F22 register.
/// </summary>
public long F22
{
get { return Read(79); }
set { Write(79, value); }
}
/// <summary>
/// Gets or sets the value of F23 register.
/// </summary>
public long F23
{
get { return Read(80); }
set { Write(80, value); }
}
/// <summary>
/// Gets or sets the value of F24 register.
/// </summary>
public long F24
{
get { return Read(81); }
set { Write(81, value); }
}
/// <summary>
/// Gets or sets the value of F25 register.
/// </summary>
public long F25
{
get { return Read(82); }
set { Write(82, value); }
}
/// <summary>
/// Gets or sets the value of F26 register.
/// </summary>
public long F26
{
get { return Read(83); }
set { Write(83, value); }
}
/// <summary>
/// Gets or sets the value of F27 register.
/// </summary>
public long F27
{
get { return Read(84); }
set { Write(84, value); }
}
/// <summary>
/// Gets or sets the value of F28 register.
/// </summary>
public long F28
{
get { return Read(85); }
set { Write(85, value); }
}
/// <summary>
/// Gets or sets the value of F29 register.
/// </summary>
public long F29
{
get { return Read(86); }
set { Write(86, value); }
}
/// <summary>
/// Gets or sets the value of F30 register.
/// </summary>
public long F30
{
get { return Read(87); }
set { Write(87, value); }
}
/// <summary>
/// Gets or sets the value of F31 register.
/// </summary>
public long F31
{
get { return Read(88); }
set { Write(88, value); }
}
/// <summary>
/// Gets or sets the value of FCC0 register.
/// </summary>
public long FCC0
{
get { return Read(89); }
set { Write(89, value); }
}
/// <summary>
/// Gets or sets the value of FCC1 register.
/// </summary>
public long FCC1
{
get { return Read(90); }
set { Write(90, value); }
}
/// <summary>
/// Gets or sets the value of FCC2 register.
/// </summary>
public long FCC2
{
get { return Read(91); }
set { Write(91, value); }
}
/// <summary>
/// Gets or sets the value of FCC3 register.
/// </summary>
public long FCC3
{
get { return Read(92); }
set { Write(92, value); }
}
/// <summary>
/// Gets or sets the value of FCC4 register.
/// </summary>
public long FCC4
{
get { return Read(93); }
set { Write(93, value); }
}
/// <summary>
/// Gets or sets the value of FCC5 register.
/// </summary>
public long FCC5
{
get { return Read(94); }
set { Write(94, value); }
}
/// <summary>
/// Gets or sets the value of FCC6 register.
/// </summary>
public long FCC6
{
get { return Read(95); }
set { Write(95, value); }
}
/// <summary>
/// Gets or sets the value of FCC7 register.
/// </summary>
public long FCC7
{
get { return Read(96); }
set { Write(96, value); }
}
/// <summary>
/// Gets or sets the value of W0 register.
/// </summary>
public long W0
{
get { return Read(97); }
set { Write(97, value); }
}
/// <summary>
/// Gets or sets the value of W1 register.
/// </summary>
public long W1
{
get { return Read(98); }
set { Write(98, value); }
}
/// <summary>
/// Gets or sets the value of W2 register.
/// </summary>
public long W2
{
get { return Read(99); }
set { Write(99, value); }
}
/// <summary>
/// Gets or sets the value of W3 register.
/// </summary>
public long W3
{
get { return Read(100); }
set { Write(100, value); }
}
/// <summary>
/// Gets or sets the value of W4 register.
/// </summary>
public long W4
{
get { return Read(101); }
set { Write(101, value); }
}
/// <summary>
/// Gets or sets the value of W5 register.
/// </summary>
public long W5
{
get { return Read(102); }
set { Write(102, value); }
}
/// <summary>
/// Gets or sets the value of W6 register.
/// </summary>
public long W6
{
get { return Read(103); }
set { Write(103, value); }
}
/// <summary>
/// Gets or sets the value of W7 register.
/// </summary>
public long W7
{
get { return Read(104); }
set { Write(104, value); }
}
/// <summary>
/// Gets or sets the value of W8 register.
/// </summary>
public long W8
{
get { return Read(105); }
set { Write(105, value); }
}
/// <summary>
/// Gets or sets the value of W9 register.
/// </summary>
public long W9
{
get { return Read(106); }
set { Write(106, value); }
}
/// <summary>
/// Gets or sets the value of W10 register.
/// </summary>
public long W10
{
get { return Read(107); }
set { Write(107, value); }
}
/// <summary>
/// Gets or sets the value of W11 register.
/// </summary>
public long W11
{
get { return Read(108); }
set { Write(108, value); }
}
/// <summary>
/// Gets or sets the value of W12 register.
/// </summary>
public long W12
{
get { return Read(109); }
set { Write(109, value); }
}
/// <summary>
/// Gets or sets the value of W13 register.
/// </summary>
public long W13
{
get { return Read(110); }
set { Write(110, value); }
}
/// <summary>
/// Gets or sets the value of W14 register.
/// </summary>
public long W14
{
get { return Read(111); }
set { Write(111, value); }
}
/// <summary>
/// Gets or sets the value of W15 register.
/// </summary>
public long W15
{
get { return Read(112); }
set { Write(112, value); }
}
/// <summary>
/// Gets or sets the value of W16 register.
/// </summary>
public long W16
{
get { return Read(113); }
set { Write(113, value); }
}
/// <summary>
/// Gets or sets the value of W17 register.
/// </summary>
public long W17
{
get { return Read(114); }
set { Write(114, value); }
}
/// <summary>
/// Gets or sets the value of W18 register.
/// </summary>
public long W18
{
get { return Read(115); }
set { Write(115, value); }
}
/// <summary>
/// Gets or sets the value of W19 register.
/// </summary>
public long W19
{
get { return Read(116); }
set { Write(116, value); }
}
/// <summary>
/// Gets or sets the value of W20 register.
/// </summary>
public long W20
{
get { return Read(117); }
set { Write(117, value); }
}
/// <summary>
/// Gets or sets the value of W21 register.
/// </summary>
public long W21
{
get { return Read(118); }
set { Write(118, value); }
}
/// <summary>
/// Gets or sets the value of W22 register.
/// </summary>
public long W22
{
get { return Read(119); }
set { Write(119, value); }
}
/// <summary>
/// Gets or sets the value of W23 register.
/// </summary>
public long W23
{
get { return Read(120); }
set { Write(120, value); }
}
/// <summary>
/// Gets or sets the value of W24 register.
/// </summary>
public long W24
{
get { return Read(121); }
set { Write(121, value); }
}
/// <summary>
/// Gets or sets the value of W25 register.
/// </summary>
public long W25
{
get { return Read(122); }
set { Write(122, value); }
}
/// <summary>
/// Gets or sets the value of W26 register.
/// </summary>
public long W26
{
get { return Read(123); }
set { Write(123, value); }
}
/// <summary>
/// Gets or sets the value of W27 register.
/// </summary>
public long W27
{
get { return Read(124); }
set { Write(124, value); }
}
/// <summary>
/// Gets or sets the value of W28 register.
/// </summary>
public long W28
{
get { return Read(125); }
set { Write(125, value); }
}
/// <summary>
/// Gets or sets the value of W29 register.
/// </summary>
public long W29
{
get { return Read(126); }
set { Write(126, value); }
}
/// <summary>
/// Gets or sets the value of W30 register.
/// </summary>
public long W30
{
get { return Read(127); }
set { Write(127, value); }
}
/// <summary>
/// Gets or sets the value of W31 register.
/// </summary>
public long W31
{
get { return Read(128); }
set { Write(128, value); }
}
/// <summary>
/// Gets or sets the value of HI register.
/// </summary>
public long HI
{
get { return Read(129); }
set { Write(129, value); }
}
/// <summary>
/// Gets or sets the value of LO register.
/// </summary>
public long LO
{
get { return Read(130); }
set { Write(130, value); }
}
/// <summary>
/// Gets or sets the value of P0 register.
/// </summary>
public long P0
{
get { return Read(131); }
set { Write(131, value); }
}
/// <summary>
/// Gets or sets the value of P1 register.
/// </summary>
public long P1
{
get { return Read(132); }
set { Write(132, value); }
}
/// <summary>
/// Gets or sets the value of P2 register.
/// </summary>
public long P2
{
get { return Read(133); }
set { Write(133, value); }
}
/// <summary>
/// Gets or sets the value of MPL0 register.
/// </summary>
public long MPL0
{
get { return Read(134); }
set { Write(134, value); }
}
/// <summary>
/// Gets or sets the value of MPL1 register.
/// </summary>
public long MPL1
{
get { return Read(135); }
set { Write(135, value); }
}
/// <summary>
/// Gets or sets the value of MPL2 register.
/// </summary>
public long MPL2
{
get { return Read(136); }
set { Write(136, value); }
}
/// <summary>
/// Gets or sets the value of ZERO register.
/// </summary>
public long ZERO
{
get { return Read(2); }
set { Write(2, value); }
}
/// <summary>
/// Gets or sets the value of AT register.
/// </summary>
public long AT
{
get { return Read(3); }
set { Write(3, value); }
}
/// <summary>
/// Gets or sets the value of V0 register.
/// </summary>
public long V0
{
get { return Read(4); }
set { Write(4, value); }
}
/// <summary>
/// Gets or sets the value of V1 register.
/// </summary>
public long V1
{
get { return Read(5); }
set { Write(5, value); }
}
/// <summary>
/// Gets or sets the value of A0 register.
/// </summary>
public long A0
{
get { return Read(6); }
set { Write(6, value); }
}
/// <summary>
/// Gets or sets the value of A1 register.
/// </summary>
public long A1
{
get { return Read(7); }
set { Write(7, value); }
}
/// <summary>
/// Gets or sets the value of A2 register.
/// </summary>
public long A2
{
get { return Read(8); }
set { Write(8, value); }
}
/// <summary>
/// Gets or sets the value of A3 register.
/// </summary>
public long A3
{
get { return Read(9); }
set { Write(9, value); }
}
/// <summary>
/// Gets or sets the value of T0 register.
/// </summary>
public long T0
{
get { return Read(10); }
set { Write(10, value); }
}
/// <summary>
/// Gets or sets the value of T1 register.
/// </summary>
public long T1
{
get { return Read(11); }
set { Write(11, value); }
}
/// <summary>
/// Gets or sets the value of T2 register.
/// </summary>
public long T2
{
get { return Read(12); }
set { Write(12, value); }
}
/// <summary>
/// Gets or sets the value of T3 register.
/// </summary>
public long T3
{
get { return Read(13); }
set { Write(13, value); }
}
/// <summary>
/// Gets or sets the value of T4 register.
/// </summary>
public long T4
{
get { return Read(14); }
set { Write(14, value); }
}
/// <summary>
/// Gets or sets the value of T5 register.
/// </summary>
public long T5
{
get { return Read(15); }
set { Write(15, value); }
}
/// <summary>
/// Gets or sets the value of T6 register.
/// </summary>
public long T6
{
get { return Read(16); }
set { Write(16, value); }
}
/// <summary>
/// Gets or sets the value of T7 register.
/// </summary>
public long T7
{
get { return Read(17); }
set { Write(17, value); }
}
/// <summary>
/// Gets or sets the value of S0 register.
/// </summary>
public long S0
{
get { return Read(18); }
set { Write(18, value); }
}
/// <summary>
/// Gets or sets the value of S1 register.
/// </summary>
public long S1
{
get { return Read(19); }
set { Write(19, value); }
}
/// <summary>
/// Gets or sets the value of S2 register.
/// </summary>
public long S2
{
get { return Read(20); }
set { Write(20, value); }
}
/// <summary>
/// Gets or sets the value of S3 register.
/// </summary>
public long S3
{
get { return Read(21); }
set { Write(21, value); }
}
/// <summary>
/// Gets or sets the value of S4 register.
/// </summary>
public long S4
{
get { return Read(22); }
set { Write(22, value); }
}
/// <summary>
/// Gets or sets the value of S5 register.
/// </summary>
public long S5
{
get { return Read(23); }
set { Write(23, value); }
}
/// <summary>
/// Gets or sets the value of S6 register.
/// </summary>
public long S6
{
get { return Read(24); }
set { Write(24, value); }
}
/// <summary>
/// Gets or sets the value of S7 register.
/// </summary>
public long S7
{
get { return Read(25); }
set { Write(25, value); }
}
/// <summary>
/// Gets or sets the value of T8 register.
/// </summary>
public long T8
{
get { return Read(26); }
set { Write(26, value); }
}
/// <summary>
/// Gets or sets the value of T9 register.
/// </summary>
public long T9
{
get { return Read(27); }
set { Write(27, value); }
}
/// <summary>
/// Gets or sets the value of K0 register.
/// </summary>
public long K0
{
get { return Read(28); }
set { Write(28, value); }
}
/// <summary>
/// Gets or sets the value of K1 register.
/// </summary>
public long K1
{
get { return Read(29); }
set { Write(29, value); }
}
/// <summary>
/// Gets or sets the value of GP register.
/// </summary>
public long GP
{
get { return Read(30); }
set { Write(30, value); }
}
/// <summary>
/// Gets or sets the value of SP register.
/// </summary>
public long SP
{
get { return Read(31); }
set { Write(31, value); }
}
/// <summary>
/// Gets or sets the value of FP register.
/// </summary>
public long FP
{
get { return Read(32); }
set { Write(32, value); }
}
/// <summary>
/// Gets or sets the value of S8 register.
/// </summary>
public long S8
{
get { return Read(32); }
set { Write(32, value); }
}
/// <summary>
/// Gets or sets the value of RA register.
/// </summary>
public long RA
{
get { return Read(33); }
set { Write(33, value); }
}
/// <summary>
/// Gets or sets the value of HI0 register.
/// </summary>
public long HI0
{
get { return Read(45); }
set { Write(45, value); }
}
/// <summary>
/// Gets or sets the value of HI1 register.
/// </summary>
public long HI1
{
get { return Read(46); }
set { Write(46, value); }
}
/// <summary>
/// Gets or sets the value of HI2 register.
/// </summary>
public long HI2
{
get { return Read(47); }
set { Write(47, value); }
}
/// <summary>
/// Gets or sets the value of HI3 register.
/// </summary>
public long HI3
{
get { return Read(48); }
set { Write(48, value); }
}
/// <summary>
/// Gets or sets the value of LO0 register.
/// </summary>
public long LO0
{
get { return Read(45); }
set { Write(45, value); }
}
/// <summary>
/// Gets or sets the value of LO1 register.
/// </summary>
public long LO1
{
get { return Read(46); }
set { Write(46, value); }
}
/// <summary>
/// Gets or sets the value of LO2 register.
/// </summary>
public long LO2
{
get { return Read(47); }
set { Write(47, value); }
}
/// <summary>
/// Gets or sets the value of LO3 register.
/// </summary>
public long LO3
{
get { return Read(48); }
set { Write(48, value); }
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculus.com/licenses/LICENSE-3.3
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.Runtime.InteropServices;
// Internal C# wrapper for OVRPlugin.
internal static class OVRPlugin
{
public static readonly System.Version wrapperVersion = OVRP_1_12_0.version;
private static System.Version _version;
public static System.Version version
{
get {
if (_version == null)
{
try
{
string pluginVersion = OVRP_1_1_0.ovrp_GetVersion();
if (pluginVersion != null)
{
// Truncate unsupported trailing version info for System.Version. Original string is returned if not present.
pluginVersion = pluginVersion.Split('-')[0];
_version = new System.Version(pluginVersion);
}
else
{
_version = _versionZero;
}
}
catch
{
_version = _versionZero;
}
// Unity 5.1.1f3-p3 have OVRPlugin version "0.5.0", which isn't accurate.
if (_version == OVRP_0_5_0.version)
_version = OVRP_0_1_0.version;
if (_version > _versionZero && _version < OVRP_1_3_0.version)
throw new PlatformNotSupportedException("Oculus Utilities version " + wrapperVersion + " is too new for OVRPlugin version " + _version.ToString () + ". Update to the latest version of Unity.");
}
return _version;
}
}
private static System.Version _nativeSDKVersion;
public static System.Version nativeSDKVersion
{
get {
if (_nativeSDKVersion == null)
{
try
{
string sdkVersion = string.Empty;
if (version >= OVRP_1_1_0.version)
sdkVersion = OVRP_1_1_0.ovrp_GetNativeSDKVersion();
else
sdkVersion = _versionZero.ToString();
if (sdkVersion != null)
{
// Truncate unsupported trailing version info for System.Version. Original string is returned if not present.
sdkVersion = sdkVersion.Split('-')[0];
_nativeSDKVersion = new System.Version(sdkVersion);
}
else
{
_nativeSDKVersion = _versionZero;
}
}
catch
{
_nativeSDKVersion = _versionZero;
}
}
return _nativeSDKVersion;
}
}
[StructLayout(LayoutKind.Sequential)]
private struct GUID
{
public int a;
public short b;
public short c;
public byte d0;
public byte d1;
public byte d2;
public byte d3;
public byte d4;
public byte d5;
public byte d6;
public byte d7;
}
public enum Bool
{
False = 0,
True
}
public enum Eye
{
None = -1,
Left = 0,
Right = 1,
Count = 2
}
public enum Tracker
{
None = -1,
Zero = 0,
One = 1,
Two = 2,
Three = 3,
Count,
}
public enum Node
{
None = -1,
EyeLeft = 0,
EyeRight = 1,
EyeCenter = 2,
HandLeft = 3,
HandRight = 4,
TrackerZero = 5,
TrackerOne = 6,
TrackerTwo = 7,
TrackerThree = 8,
Head = 9,
Count,
}
public enum Controller
{
None = 0,
LTouch = 0x00000001,
RTouch = 0x00000002,
Touch = LTouch | RTouch,
Remote = 0x00000004,
Gamepad = 0x00000010,
Touchpad = 0x08000000,
LTrackedRemote = 0x01000000,
RTrackedRemote = 0x02000000,
Active = unchecked((int)0x80000000),
All = ~None,
}
public enum TrackingOrigin
{
EyeLevel = 0,
FloorLevel = 1,
Count,
}
public enum RecenterFlags
{
Default = 0,
Controllers = 0x40000000,
IgnoreAll = unchecked((int)0x80000000),
Count,
}
public enum BatteryStatus
{
Charging = 0,
Discharging,
Full,
NotCharging,
Unknown,
}
public enum EyeTextureFormat
{
Default = 0,
R16G16B16A16_FP = 2,
R11G11B10_FP = 3,
}
public enum PlatformUI
{
None = -1,
GlobalMenu = 0,
ConfirmQuit,
GlobalMenuTutorial,
}
public enum SystemRegion
{
Unspecified = 0,
Japan,
China,
}
public enum SystemHeadset
{
None = 0,
GearVR_R320, // Note4 Innovator
GearVR_R321, // S6 Innovator
GearVR_R322, // Commercial 1
GearVR_R323, // Commercial 2 (USB Type C)
Rift_DK1 = 0x1000,
Rift_DK2,
Rift_CV1,
}
public enum OverlayShape
{
Quad = 0,
Cylinder = 1,
Cubemap = 2,
OffcenterCubemap = 4,
}
public enum Step
{
Render = -1,
Physics = 0,
}
private const int OverlayShapeFlagShift = 4;
private enum OverlayFlag
{
None = unchecked((int)0x00000000),
OnTop = unchecked((int)0x00000001),
HeadLocked = unchecked((int)0x00000002),
// Using the 5-8 bits for shapes, total 16 potential shapes can be supported 0x000000[0]0 -> 0x000000[F]0
ShapeFlag_Quad = unchecked((int)OverlayShape.Quad << OverlayShapeFlagShift),
ShapeFlag_Cylinder = unchecked((int)OverlayShape.Cylinder << OverlayShapeFlagShift),
ShapeFlag_Cubemap = unchecked((int)OverlayShape.Cubemap << OverlayShapeFlagShift),
ShapeFlag_OffcenterCubemap = unchecked((int)OverlayShape.OffcenterCubemap << OverlayShapeFlagShift),
ShapeFlagRangeMask = unchecked((int)0xF << OverlayShapeFlagShift),
}
[StructLayout(LayoutKind.Sequential)]
public struct Vector2f
{
public float x;
public float y;
}
[StructLayout(LayoutKind.Sequential)]
public struct Vector3f
{
public float x;
public float y;
public float z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Quatf
{
public float x;
public float y;
public float z;
public float w;
}
[StructLayout(LayoutKind.Sequential)]
public struct Posef
{
public Quatf Orientation;
public Vector3f Position;
}
[StructLayout(LayoutKind.Sequential)]
public struct PoseStatef
{
public Posef Pose;
public Vector3f Velocity;
public Vector3f Acceleration;
public Vector3f AngularVelocity;
public Vector3f AngularAcceleration;
double Time;
}
[StructLayout(LayoutKind.Sequential)]
public struct ControllerState2
{
public uint ConnectedControllers;
public uint Buttons;
public uint Touches;
public uint NearTouches;
public float LIndexTrigger;
public float RIndexTrigger;
public float LHandTrigger;
public float RHandTrigger;
public Vector2f LThumbstick;
public Vector2f RThumbstick;
public Vector2f LTouchpad;
public Vector2f RTouchpad;
public ControllerState2(ControllerState cs)
{
ConnectedControllers = cs.ConnectedControllers;
Buttons = cs.Buttons;
Touches = cs.Touches;
NearTouches = cs.NearTouches;
LIndexTrigger = cs.LIndexTrigger;
RIndexTrigger = cs.RIndexTrigger;
LHandTrigger = cs.LHandTrigger;
RHandTrigger = cs.RHandTrigger;
LThumbstick = cs.LThumbstick;
RThumbstick = cs.RThumbstick;
LTouchpad = new Vector2f() { x = 0.0f, y = 0.0f };
RTouchpad = new Vector2f() { x = 0.0f, y = 0.0f };
}
}
[StructLayout(LayoutKind.Sequential)]
public struct ControllerState
{
public uint ConnectedControllers;
public uint Buttons;
public uint Touches;
public uint NearTouches;
public float LIndexTrigger;
public float RIndexTrigger;
public float LHandTrigger;
public float RHandTrigger;
public Vector2f LThumbstick;
public Vector2f RThumbstick;
}
[StructLayout(LayoutKind.Sequential)]
public struct HapticsBuffer
{
public IntPtr Samples;
public int SamplesCount;
}
[StructLayout(LayoutKind.Sequential)]
public struct HapticsState
{
public int SamplesAvailable;
public int SamplesQueued;
}
[StructLayout(LayoutKind.Sequential)]
public struct HapticsDesc
{
public int SampleRateHz;
public int SampleSizeInBytes;
public int MinimumSafeSamplesQueued;
public int MinimumBufferSamplesCount;
public int OptimalBufferSamplesCount;
public int MaximumBufferSamplesCount;
}
[StructLayout(LayoutKind.Sequential)]
public struct AppPerfFrameStats
{
public int HmdVsyncIndex;
public int AppFrameIndex;
public int AppDroppedFrameCount;
public float AppMotionToPhotonLatency;
public float AppQueueAheadTime;
public float AppCpuElapsedTime;
public float AppGpuElapsedTime;
public int CompositorFrameIndex;
public int CompositorDroppedFrameCount;
public float CompositorLatency;
public float CompositorCpuElapsedTime;
public float CompositorGpuElapsedTime;
public float CompositorCpuStartToGpuEndElapsedTime;
public float CompositorGpuEndToVsyncElapsedTime;
}
public const int AppPerfFrameStatsMaxCount = 5;
[StructLayout(LayoutKind.Sequential)]
public struct AppPerfStats
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst=AppPerfFrameStatsMaxCount)]
public AppPerfFrameStats[] FrameStats;
public int FrameStatsCount;
public Bool AnyFrameStatsDropped;
public float AdaptiveGpuPerformanceScale;
}
[StructLayout(LayoutKind.Sequential)]
public struct Sizei
{
public int w;
public int h;
}
[StructLayout(LayoutKind.Sequential)]
public struct Frustumf
{
public float zNear;
public float zFar;
public float fovX;
public float fovY;
}
public enum BoundaryType
{
OuterBoundary = 0x0001,
PlayArea = 0x0100,
}
[StructLayout(LayoutKind.Sequential)]
public struct BoundaryTestResult
{
public Bool IsTriggering;
public float ClosestDistance;
public Vector3f ClosestPoint;
public Vector3f ClosestPointNormal;
}
[StructLayout(LayoutKind.Sequential)]
public struct BoundaryLookAndFeel
{
public Colorf Color;
}
[StructLayout(LayoutKind.Sequential)]
public struct BoundaryGeometry
{
public BoundaryType BoundaryType;
[MarshalAs(UnmanagedType.ByValArray, SizeConst=256)]
public Vector3f[] Points;
public int PointsCount;
}
[StructLayout(LayoutKind.Sequential)]
public struct Colorf
{
public float r;
public float g;
public float b;
public float a;
}
public static bool initialized
{
get {
return OVRP_1_1_0.ovrp_GetInitialized() == OVRPlugin.Bool.True;
}
}
public static bool chromatic
{
get {
if (version >= OVRP_1_7_0.version)
return OVRP_1_7_0.ovrp_GetAppChromaticCorrection() == OVRPlugin.Bool.True;
#if UNITY_ANDROID && !UNITY_EDITOR
return false;
#else
return true;
#endif
}
set {
if (version >= OVRP_1_7_0.version)
OVRP_1_7_0.ovrp_SetAppChromaticCorrection(ToBool(value));
}
}
public static bool monoscopic
{
get { return OVRP_1_1_0.ovrp_GetAppMonoscopic() == OVRPlugin.Bool.True; }
set { OVRP_1_1_0.ovrp_SetAppMonoscopic(ToBool(value)); }
}
public static bool rotation
{
get { return OVRP_1_1_0.ovrp_GetTrackingOrientationEnabled() == Bool.True; }
set { OVRP_1_1_0.ovrp_SetTrackingOrientationEnabled(ToBool(value)); }
}
public static bool position
{
get { return OVRP_1_1_0.ovrp_GetTrackingPositionEnabled() == Bool.True; }
set { OVRP_1_1_0.ovrp_SetTrackingPositionEnabled(ToBool(value)); }
}
public static bool useIPDInPositionTracking
{
get {
if (version >= OVRP_1_6_0.version)
return OVRP_1_6_0.ovrp_GetTrackingIPDEnabled() == OVRPlugin.Bool.True;
return true;
}
set {
if (version >= OVRP_1_6_0.version)
OVRP_1_6_0.ovrp_SetTrackingIPDEnabled(ToBool(value));
}
}
public static bool positionSupported { get { return OVRP_1_1_0.ovrp_GetTrackingPositionSupported() == Bool.True; } }
public static bool positionTracked { get { return OVRP_1_1_0.ovrp_GetNodePositionTracked(Node.EyeCenter) == Bool.True; } }
public static bool powerSaving { get { return OVRP_1_1_0.ovrp_GetSystemPowerSavingMode() == Bool.True; } }
public static bool hmdPresent { get { return OVRP_1_1_0.ovrp_GetNodePresent(Node.EyeCenter) == Bool.True; } }
public static bool userPresent { get { return OVRP_1_1_0.ovrp_GetUserPresent() == Bool.True; } }
public static bool headphonesPresent { get { return OVRP_1_3_0.ovrp_GetSystemHeadphonesPresent() == OVRPlugin.Bool.True; } }
public static int recommendedMSAALevel
{
get {
if (version >= OVRP_1_6_0.version)
return OVRP_1_6_0.ovrp_GetSystemRecommendedMSAALevel ();
else
return 2;
}
}
public static SystemRegion systemRegion
{
get {
if (version >= OVRP_1_5_0.version)
return OVRP_1_5_0.ovrp_GetSystemRegion();
else
return SystemRegion.Unspecified;
}
}
private static Guid _cachedAudioOutGuid;
private static string _cachedAudioOutString;
public static string audioOutId
{
get
{
try
{
IntPtr ptr = OVRP_1_1_0.ovrp_GetAudioOutId();
if (ptr != IntPtr.Zero)
{
GUID nativeGuid = (GUID)Marshal.PtrToStructure(ptr, typeof(OVRPlugin.GUID));
Guid managedGuid = new Guid(
nativeGuid.a,
nativeGuid.b,
nativeGuid.c,
nativeGuid.d0,
nativeGuid.d1,
nativeGuid.d2,
nativeGuid.d3,
nativeGuid.d4,
nativeGuid.d5,
nativeGuid.d6,
nativeGuid.d7);
if (managedGuid != _cachedAudioOutGuid)
{
_cachedAudioOutGuid = managedGuid;
_cachedAudioOutString = _cachedAudioOutGuid.ToString();
}
return _cachedAudioOutString;
}
}
catch {}
return string.Empty;
}
}
private static Guid _cachedAudioInGuid;
private static string _cachedAudioInString;
public static string audioInId
{
get
{
try
{
IntPtr ptr = OVRP_1_1_0.ovrp_GetAudioInId();
if (ptr != IntPtr.Zero)
{
GUID nativeGuid = (GUID)Marshal.PtrToStructure(ptr, typeof(OVRPlugin.GUID));
Guid managedGuid = new Guid(
nativeGuid.a,
nativeGuid.b,
nativeGuid.c,
nativeGuid.d0,
nativeGuid.d1,
nativeGuid.d2,
nativeGuid.d3,
nativeGuid.d4,
nativeGuid.d5,
nativeGuid.d6,
nativeGuid.d7);
if (managedGuid != _cachedAudioInGuid)
{
_cachedAudioInGuid = managedGuid;
_cachedAudioInString = _cachedAudioInGuid.ToString();
}
return _cachedAudioInString;
}
}
catch {}
return string.Empty;
}
}
public static bool hasVrFocus { get { return OVRP_1_1_0.ovrp_GetAppHasVrFocus() == Bool.True; } }
public static bool shouldQuit { get { return OVRP_1_1_0.ovrp_GetAppShouldQuit() == Bool.True; } }
public static bool shouldRecenter { get { return OVRP_1_1_0.ovrp_GetAppShouldRecenter() == Bool.True; } }
public static string productName { get { return OVRP_1_1_0.ovrp_GetSystemProductName(); } }
public static string latency { get { return OVRP_1_1_0.ovrp_GetAppLatencyTimings(); } }
public static float eyeDepth
{
get { return OVRP_1_1_0.ovrp_GetUserEyeDepth(); }
set { OVRP_1_1_0.ovrp_SetUserEyeDepth(value); }
}
public static float eyeHeight
{
get { return OVRP_1_1_0.ovrp_GetUserEyeHeight(); }
set { OVRP_1_1_0.ovrp_SetUserEyeHeight(value); }
}
public static float batteryLevel
{
get { return OVRP_1_1_0.ovrp_GetSystemBatteryLevel(); }
}
public static float batteryTemperature
{
get { return OVRP_1_1_0.ovrp_GetSystemBatteryTemperature(); }
}
public static int cpuLevel
{
get { return OVRP_1_1_0.ovrp_GetSystemCpuLevel(); }
set { OVRP_1_1_0.ovrp_SetSystemCpuLevel(value); }
}
public static int gpuLevel
{
get { return OVRP_1_1_0.ovrp_GetSystemGpuLevel(); }
set { OVRP_1_1_0.ovrp_SetSystemGpuLevel(value); }
}
public static int vsyncCount
{
get { return OVRP_1_1_0.ovrp_GetSystemVSyncCount(); }
set { OVRP_1_2_0.ovrp_SetSystemVSyncCount(value); }
}
public static float systemVolume
{
get { return OVRP_1_1_0.ovrp_GetSystemVolume(); }
}
public static float ipd
{
get { return OVRP_1_1_0.ovrp_GetUserIPD(); }
set { OVRP_1_1_0.ovrp_SetUserIPD(value); }
}
public static bool occlusionMesh
{
get { return OVRP_1_3_0.ovrp_GetEyeOcclusionMeshEnabled() == Bool.True; }
set { OVRP_1_3_0.ovrp_SetEyeOcclusionMeshEnabled(ToBool(value)); }
}
public static BatteryStatus batteryStatus
{
get { return OVRP_1_1_0.ovrp_GetSystemBatteryStatus(); }
}
public static Frustumf GetEyeFrustum(Eye eyeId) { return OVRP_1_1_0.ovrp_GetNodeFrustum((Node)eyeId); }
public static Sizei GetEyeTextureSize(Eye eyeId) { return OVRP_0_1_0.ovrp_GetEyeTextureSize(eyeId); }
public static Posef GetTrackerPose(Tracker trackerId) { return GetNodePose((Node)((int)trackerId + (int)Node.TrackerZero), Step.Render); }
public static Frustumf GetTrackerFrustum(Tracker trackerId) { return OVRP_1_1_0.ovrp_GetNodeFrustum((Node)((int)trackerId + (int)Node.TrackerZero)); }
public static bool ShowUI(PlatformUI ui) { return OVRP_1_1_0.ovrp_ShowSystemUI(ui) == Bool.True; }
public static bool SetOverlayQuad(bool onTop, bool headLocked, IntPtr leftTexture, IntPtr rightTexture, IntPtr device, Posef pose, Vector3f scale, int layerIndex=0, OverlayShape shape=OverlayShape.Quad)
{
if (version >= OVRP_1_6_0.version)
{
uint flags = (uint)OverlayFlag.None;
if (onTop)
flags |= (uint)OverlayFlag.OnTop;
if (headLocked)
flags |= (uint)OverlayFlag.HeadLocked;
if (shape == OverlayShape.Cylinder || shape == OverlayShape.Cubemap)
{
#if UNITY_ANDROID
if (version >= OVRP_1_7_0.version)
flags |= (uint)(shape) << OverlayShapeFlagShift;
else
#else
if (shape == OverlayShape.Cubemap && version >= OVRP_1_10_0.version)
flags |= (uint)(shape) << OverlayShapeFlagShift;
else
#endif
return false;
}
if (shape == OverlayShape.OffcenterCubemap)
{
#if UNITY_ANDROID
if (version >= OVRP_1_11_0.version)
flags |= (uint)(shape) << OverlayShapeFlagShift;
else
#endif
return false;
}
return OVRP_1_6_0.ovrp_SetOverlayQuad3(flags, leftTexture, rightTexture, device, pose, scale, layerIndex) == Bool.True;
}
if (layerIndex != 0)
return false;
return OVRP_0_1_1.ovrp_SetOverlayQuad2(ToBool(onTop), ToBool(headLocked), leftTexture, device, pose, scale) == Bool.True;
}
public static bool UpdateNodePhysicsPoses(int frameIndex, double predictionSeconds)
{
if (version >= OVRP_1_8_0.version)
return OVRP_1_8_0.ovrp_Update2(0, frameIndex, predictionSeconds) == Bool.True;
return false;
}
public static Posef GetNodePose(Node nodeId, Step stepId)
{
if (version >= OVRP_1_12_0.version)
return OVRP_1_12_0.ovrp_GetNodePoseState (stepId, nodeId).Pose;
if (version >= OVRP_1_8_0.version && stepId == Step.Physics)
return OVRP_1_8_0.ovrp_GetNodePose2(0, nodeId);
return OVRP_0_1_2.ovrp_GetNodePose(nodeId);
}
public static Vector3f GetNodeVelocity(Node nodeId, Step stepId)
{
if (version >= OVRP_1_12_0.version)
return OVRP_1_12_0.ovrp_GetNodePoseState (stepId, nodeId).Velocity;
if (version >= OVRP_1_8_0.version && stepId == Step.Physics)
return OVRP_1_8_0.ovrp_GetNodeVelocity2(0, nodeId).Position;
return OVRP_0_1_3.ovrp_GetNodeVelocity(nodeId).Position;
}
public static Vector3f GetNodeAngularVelocity(Node nodeId, Step stepId)
{
if (version >= OVRP_1_12_0.version)
return OVRP_1_12_0.ovrp_GetNodePoseState(stepId, nodeId).AngularVelocity;
return new Vector3f(); //TODO: Convert legacy quat to vec3?
}
public static Vector3f GetNodeAcceleration(Node nodeId, Step stepId)
{
if (version >= OVRP_1_12_0.version)
return OVRP_1_12_0.ovrp_GetNodePoseState (stepId, nodeId).Acceleration;
if (version >= OVRP_1_8_0.version && stepId == Step.Physics)
return OVRP_1_8_0.ovrp_GetNodeAcceleration2(0, nodeId).Position;
return OVRP_0_1_3.ovrp_GetNodeAcceleration(nodeId).Position;
}
public static Vector3f GetNodeAngularAcceleration(Node nodeId, Step stepId)
{
if (version >= OVRP_1_12_0.version)
return OVRP_1_12_0.ovrp_GetNodePoseState(stepId, nodeId).AngularAcceleration;
return new Vector3f(); //TODO: Convert legacy quat to vec3?
}
public static bool GetNodePresent(Node nodeId)
{
return OVRP_1_1_0.ovrp_GetNodePresent(nodeId) == Bool.True;
}
public static bool GetNodeOrientationTracked(Node nodeId)
{
return OVRP_1_1_0.ovrp_GetNodeOrientationTracked(nodeId) == Bool.True;
}
public static bool GetNodePositionTracked(Node nodeId)
{
return OVRP_1_1_0.ovrp_GetNodePositionTracked(nodeId) == Bool.True;
}
public static ControllerState GetControllerState(uint controllerMask)
{
return OVRP_1_1_0.ovrp_GetControllerState(controllerMask);
}
public static ControllerState2 GetControllerState2(uint controllerMask)
{
if (version >= OVRP_1_12_0.version)
{
return OVRP_1_12_0.ovrp_GetControllerState2(controllerMask);
}
return new ControllerState2(OVRP_1_1_0.ovrp_GetControllerState(controllerMask));
}
public static bool SetControllerVibration(uint controllerMask, float frequency, float amplitude)
{
return OVRP_0_1_2.ovrp_SetControllerVibration(controllerMask, frequency, amplitude) == Bool.True;
}
public static HapticsDesc GetControllerHapticsDesc(uint controllerMask)
{
if (version >= OVRP_1_6_0.version)
{
return OVRP_1_6_0.ovrp_GetControllerHapticsDesc(controllerMask);
}
else
{
return new HapticsDesc();
}
}
public static HapticsState GetControllerHapticsState(uint controllerMask)
{
if (version >= OVRP_1_6_0.version)
{
return OVRP_1_6_0.ovrp_GetControllerHapticsState(controllerMask);
}
else
{
return new HapticsState();
}
}
public static bool SetControllerHaptics(uint controllerMask, HapticsBuffer hapticsBuffer)
{
if (version >= OVRP_1_6_0.version)
{
return OVRP_1_6_0.ovrp_SetControllerHaptics(controllerMask, hapticsBuffer) == Bool.True;
}
else
{
return false;
}
}
public static float GetEyeRecommendedResolutionScale()
{
if (version >= OVRP_1_6_0.version)
{
return OVRP_1_6_0.ovrp_GetEyeRecommendedResolutionScale();
}
else
{
return 1.0f;
}
}
public static float GetAppCpuStartToGpuEndTime()
{
if (version >= OVRP_1_6_0.version)
{
return OVRP_1_6_0.ovrp_GetAppCpuStartToGpuEndTime();
}
else
{
return 0.0f;
}
}
public static bool GetBoundaryConfigured()
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_GetBoundaryConfigured() == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static BoundaryTestResult TestBoundaryNode(Node nodeId, BoundaryType boundaryType)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_TestBoundaryNode(nodeId, boundaryType);
}
else
{
return new BoundaryTestResult();
}
}
public static BoundaryTestResult TestBoundaryPoint(Vector3f point, BoundaryType boundaryType)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_TestBoundaryPoint(point, boundaryType);
}
else
{
return new BoundaryTestResult();
}
}
public static bool SetBoundaryLookAndFeel(BoundaryLookAndFeel lookAndFeel)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_SetBoundaryLookAndFeel(lookAndFeel) == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static bool ResetBoundaryLookAndFeel()
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_ResetBoundaryLookAndFeel() == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static BoundaryGeometry GetBoundaryGeometry(BoundaryType boundaryType)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_GetBoundaryGeometry(boundaryType);
}
else
{
return new BoundaryGeometry();
}
}
public static bool GetBoundaryGeometry2(BoundaryType boundaryType, IntPtr points, ref int pointsCount)
{
if (version >= OVRP_1_9_0.version)
{
return OVRP_1_9_0.ovrp_GetBoundaryGeometry2(boundaryType, points, ref pointsCount) == OVRPlugin.Bool.True;
}
else
{
pointsCount = 0;
return false;
}
}
public static AppPerfStats GetAppPerfStats()
{
if (version >= OVRP_1_9_0.version)
{
return OVRP_1_9_0.ovrp_GetAppPerfStats();
}
else
{
return new AppPerfStats();
}
}
public static bool ResetAppPerfStats()
{
if (version >= OVRP_1_9_0.version)
{
return OVRP_1_9_0.ovrp_ResetAppPerfStats() == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static float GetAppFramerate()
{
if (version >= OVRP_1_12_0.version)
{
return OVRP_1_12_0.ovrp_GetAppFramerate();
}
else
{
return 0.0f;
}
}
public static EyeTextureFormat GetDesiredEyeTextureFormat()
{
if (version >= OVRP_1_11_0.version )
{
uint eyeTextureFormatValue = (uint) OVRP_1_11_0.ovrp_GetDesiredEyeTextureFormat();
// convert both R8G8B8A8 and R8G8B8A8_SRGB to R8G8B8A8 here for avoid confusing developers
if (eyeTextureFormatValue == 1)
eyeTextureFormatValue = 0;
return (EyeTextureFormat)eyeTextureFormatValue;
}
else
{
return EyeTextureFormat.Default;
}
}
public static bool SetDesiredEyeTextureFormat(EyeTextureFormat value)
{
if (version >= OVRP_1_11_0.version)
{
return OVRP_1_11_0.ovrp_SetDesiredEyeTextureFormat(value) == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static Vector3f GetBoundaryDimensions(BoundaryType boundaryType)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_GetBoundaryDimensions(boundaryType);
}
else
{
return new Vector3f();
}
}
public static bool GetBoundaryVisible()
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_GetBoundaryVisible() == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static bool SetBoundaryVisible(bool value)
{
if (version >= OVRP_1_8_0.version)
{
return OVRP_1_8_0.ovrp_SetBoundaryVisible(ToBool(value)) == OVRPlugin.Bool.True;
}
else
{
return false;
}
}
public static SystemHeadset GetSystemHeadsetType()
{
if (version >= OVRP_1_9_0.version)
return OVRP_1_9_0.ovrp_GetSystemHeadsetType();
return SystemHeadset.None;
}
public static Controller GetActiveController()
{
if (version >= OVRP_1_9_0.version)
return OVRP_1_9_0.ovrp_GetActiveController();
return Controller.None;
}
public static Controller GetConnectedControllers()
{
if (version >= OVRP_1_9_0.version)
return OVRP_1_9_0.ovrp_GetConnectedControllers();
return Controller.None;
}
private static Bool ToBool(bool b)
{
return (b) ? OVRPlugin.Bool.True : OVRPlugin.Bool.False;
}
public static TrackingOrigin GetTrackingOriginType()
{
return OVRP_1_0_0.ovrp_GetTrackingOriginType();
}
public static bool SetTrackingOriginType(TrackingOrigin originType)
{
return OVRP_1_0_0.ovrp_SetTrackingOriginType(originType) == Bool.True;
}
public static Posef GetTrackingCalibratedOrigin()
{
return OVRP_1_0_0.ovrp_GetTrackingCalibratedOrigin();
}
public static bool SetTrackingCalibratedOrigin()
{
return OVRP_1_2_0.ovrpi_SetTrackingCalibratedOrigin() == Bool.True;
}
public static bool RecenterTrackingOrigin(RecenterFlags flags)
{
return OVRP_1_0_0.ovrp_RecenterTrackingOrigin((uint)flags) == Bool.True;
}
private const string pluginName = "OVRPlugin";
private static Version _versionZero = new System.Version(0, 0, 0);
private static class OVRP_0_1_0
{
public static readonly System.Version version = new System.Version(0, 1, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Sizei ovrp_GetEyeTextureSize(Eye eyeId);
}
private static class OVRP_0_1_1
{
public static readonly System.Version version = new System.Version(0, 1, 1);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetOverlayQuad2(Bool onTop, Bool headLocked, IntPtr texture, IntPtr device, Posef pose, Vector3f scale);
}
private static class OVRP_0_1_2
{
public static readonly System.Version version = new System.Version(0, 1, 2);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodePose(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetControllerVibration(uint controllerMask, float frequency, float amplitude);
}
private static class OVRP_0_1_3
{
public static readonly System.Version version = new System.Version(0, 1, 3);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodeVelocity(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodeAcceleration(Node nodeId);
}
private static class OVRP_0_5_0
{
public static readonly System.Version version = new System.Version(0, 5, 0);
}
private static class OVRP_1_0_0
{
public static readonly System.Version version = new System.Version(1, 0, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern TrackingOrigin ovrp_GetTrackingOriginType();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetTrackingOriginType(TrackingOrigin originType);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetTrackingCalibratedOrigin();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_RecenterTrackingOrigin(uint flags);
}
private static class OVRP_1_1_0
{
public static readonly System.Version version = new System.Version(1, 1, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetInitialized();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetVersion")]
private static extern IntPtr _ovrp_GetVersion();
public static string ovrp_GetVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetVersion()); }
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetNativeSDKVersion")]
private static extern IntPtr _ovrp_GetNativeSDKVersion();
public static string ovrp_GetNativeSDKVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetNativeSDKVersion()); }
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr ovrp_GetAudioOutId();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr ovrp_GetAudioInId();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetEyeTextureScale();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetEyeTextureScale(float value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetTrackingOrientationSupported();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetTrackingOrientationEnabled();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetTrackingOrientationEnabled(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetTrackingPositionSupported();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetTrackingPositionEnabled();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetTrackingPositionEnabled(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetNodePresent(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetNodeOrientationTracked(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetNodePositionTracked(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Frustumf ovrp_GetNodeFrustum(Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern ControllerState ovrp_GetControllerState(uint controllerMask);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern int ovrp_GetSystemCpuLevel();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetSystemCpuLevel(int value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern int ovrp_GetSystemGpuLevel();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetSystemGpuLevel(int value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetSystemPowerSavingMode();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetSystemDisplayFrequency();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern int ovrp_GetSystemVSyncCount();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetSystemVolume();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern BatteryStatus ovrp_GetSystemBatteryStatus();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetSystemBatteryLevel();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetSystemBatteryTemperature();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetSystemProductName")]
private static extern IntPtr _ovrp_GetSystemProductName();
public static string ovrp_GetSystemProductName() { return Marshal.PtrToStringAnsi(_ovrp_GetSystemProductName()); }
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_ShowSystemUI(PlatformUI ui);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetAppMonoscopic();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetAppMonoscopic(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetAppHasVrFocus();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetAppShouldQuit();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetAppShouldRecenter();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetAppLatencyTimings")]
private static extern IntPtr _ovrp_GetAppLatencyTimings();
public static string ovrp_GetAppLatencyTimings() { return Marshal.PtrToStringAnsi(_ovrp_GetAppLatencyTimings()); }
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetUserPresent();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetUserIPD();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetUserIPD(float value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetUserEyeDepth();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetUserEyeDepth(float value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetUserEyeHeight();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetUserEyeHeight(float value);
}
private static class OVRP_1_2_0
{
public static readonly System.Version version = new System.Version(1, 2, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetSystemVSyncCount(int vsyncCount);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrpi_SetTrackingCalibratedOrigin();
}
private static class OVRP_1_3_0
{
public static readonly System.Version version = new System.Version(1, 3, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetEyeOcclusionMeshEnabled();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetEyeOcclusionMeshEnabled(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetSystemHeadphonesPresent();
}
private static class OVRP_1_5_0
{
public static readonly System.Version version = new System.Version(1, 5, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern SystemRegion ovrp_GetSystemRegion();
}
private static class OVRP_1_6_0
{
public static readonly System.Version version = new System.Version(1, 6, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetTrackingIPDEnabled();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetTrackingIPDEnabled(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern HapticsDesc ovrp_GetControllerHapticsDesc(uint controllerMask);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern HapticsState ovrp_GetControllerHapticsState(uint controllerMask);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetControllerHaptics(uint controllerMask, HapticsBuffer hapticsBuffer);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetOverlayQuad3(uint flags, IntPtr textureLeft, IntPtr textureRight, IntPtr device, Posef pose, Vector3f scale, int layerIndex);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetEyeRecommendedResolutionScale();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetAppCpuStartToGpuEndTime();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern int ovrp_GetSystemRecommendedMSAALevel();
}
private static class OVRP_1_7_0
{
public static readonly System.Version version = new System.Version(1, 7, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetAppChromaticCorrection();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetAppChromaticCorrection(Bool value);
}
private static class OVRP_1_8_0
{
public static readonly System.Version version = new System.Version(1, 8, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetBoundaryConfigured();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern BoundaryTestResult ovrp_TestBoundaryNode(Node nodeId, BoundaryType boundaryType);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern BoundaryTestResult ovrp_TestBoundaryPoint(Vector3f point, BoundaryType boundaryType);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetBoundaryLookAndFeel(BoundaryLookAndFeel lookAndFeel);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_ResetBoundaryLookAndFeel();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern BoundaryGeometry ovrp_GetBoundaryGeometry(BoundaryType boundaryType);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Vector3f ovrp_GetBoundaryDimensions(BoundaryType boundaryType);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetBoundaryVisible();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetBoundaryVisible(Bool value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_Update2(int stateId, int frameIndex, double predictionSeconds);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodePose2(int stateId, Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodeVelocity2(int stateId, Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Posef ovrp_GetNodeAcceleration2(int stateId, Node nodeId);
}
private static class OVRP_1_9_0
{
public static readonly System.Version version = new System.Version(1, 9, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern SystemHeadset ovrp_GetSystemHeadsetType();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Controller ovrp_GetActiveController();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Controller ovrp_GetConnectedControllers();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_GetBoundaryGeometry2(BoundaryType boundaryType, IntPtr points, ref int pointsCount);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern AppPerfStats ovrp_GetAppPerfStats();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_ResetAppPerfStats();
}
private static class OVRP_1_10_0
{
public static readonly System.Version version = new System.Version(1, 10, 0);
}
private static class OVRP_1_11_0
{
public static readonly System.Version version = new System.Version(1, 11, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern Bool ovrp_SetDesiredEyeTextureFormat(EyeTextureFormat value);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern EyeTextureFormat ovrp_GetDesiredEyeTextureFormat();
}
private static class OVRP_1_12_0
{
public static readonly System.Version version = new System.Version(1, 12, 0);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern float ovrp_GetAppFramerate();
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern PoseStatef ovrp_GetNodePoseState(Step stepId, Node nodeId);
[DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)]
public static extern ControllerState2 ovrp_GetControllerState2(uint controllerMask);
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file=ComponentCommands.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: The ComponentCommands class defines a standard set of commands that are required in Controls.
//
// See spec at : http://avalon/CoreUI/Specs%20%20Eventing%20and%20Commanding/CommandLibrarySpec.mht
//
//
// History:
// 03/31/2004 : chandras - Created
// 04/28/2004 : Added Accelerator table loading from Resource
// 02/02/2005 : Created ComponentCommands class from CommandLibrary class.
//
//---------------------------------------------------------------------------
using System;
using System.Windows;
using System.Windows.Input;
using System.Collections;
using System.ComponentModel;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Input
{
/// <summary>
/// ComponentCommands - Set of Standard Commands
/// </summary>
public static class ComponentCommands
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// ScrollPageUp Command
/// </summary>
public static RoutedUICommand ScrollPageUp
{
get { return _EnsureCommand(CommandId.ScrollPageUp); }
}
/// <summary>
/// ScrollPageDown Command
/// </summary>
public static RoutedUICommand ScrollPageDown
{
get { return _EnsureCommand(CommandId.ScrollPageDown); }
}
/// <summary>
/// ScrollPageLeft Command
/// </summary>
public static RoutedUICommand ScrollPageLeft
{
get { return _EnsureCommand(CommandId.ScrollPageLeft); }
}
/// <summary>
/// ScrollPageRight Command
/// </summary>
public static RoutedUICommand ScrollPageRight
{
get { return _EnsureCommand(CommandId.ScrollPageRight); }
}
/// <summary>
/// ScrollByLine Command
/// </summary>
public static RoutedUICommand ScrollByLine
{
get { return _EnsureCommand(CommandId.ScrollByLine); }
}
/// <summary>
/// MoveLeft Command
/// </summary>
public static RoutedUICommand MoveLeft
{
get { return _EnsureCommand(CommandId.MoveLeft); }
}
/// <summary>
/// MoveRight Command
/// </summary>
public static RoutedUICommand MoveRight
{
get { return _EnsureCommand(CommandId.MoveRight); }
}
/// <summary>
/// MoveUp Command
/// </summary>
public static RoutedUICommand MoveUp
{
get { return _EnsureCommand(CommandId.MoveUp); }
}
/// <summary>
/// MoveDown Command
/// </summary>
public static RoutedUICommand MoveDown
{
get { return _EnsureCommand(CommandId.MoveDown); }
}
/// <summary>
/// MoveToHome Command
/// </summary>
public static RoutedUICommand MoveToHome
{
get { return _EnsureCommand(CommandId.MoveToHome); }
}
/// <summary>
/// MoveToEnd Command
/// </summary>
public static RoutedUICommand MoveToEnd
{
get { return _EnsureCommand(CommandId.MoveToEnd); }
}
/// <summary>
/// MoveToPageUp Command
/// </summary>
public static RoutedUICommand MoveToPageUp
{
get { return _EnsureCommand(CommandId.MoveToPageUp); }
}
/// <summary>
/// MoveToPageDown Command
/// </summary>
public static RoutedUICommand MoveToPageDown
{
get { return _EnsureCommand(CommandId.MoveToPageDown); }
}
/// <summary>
/// Extend Selection Up Command
/// </summary>
public static RoutedUICommand ExtendSelectionUp
{
get { return _EnsureCommand(CommandId.ExtendSelectionUp); }
}
/// <summary>
/// ExtendSelectionDown Command
/// </summary>
public static RoutedUICommand ExtendSelectionDown
{
get { return _EnsureCommand(CommandId.ExtendSelectionDown); }
}
/// <summary>
/// ExtendSelectionLeft Command
/// </summary>
public static RoutedUICommand ExtendSelectionLeft
{
get { return _EnsureCommand(CommandId.ExtendSelectionLeft); }
}
/// <summary>
/// ExtendSelectionRight Command
/// </summary>
public static RoutedUICommand ExtendSelectionRight
{
get { return _EnsureCommand(CommandId.ExtendSelectionRight); }
}
/// <summary>
/// SelectToHome Command
/// </summary>
public static RoutedUICommand SelectToHome
{
get { return _EnsureCommand(CommandId.SelectToHome); }
}
/// <summary>
/// SelectToEnd Command
/// </summary>
public static RoutedUICommand SelectToEnd
{
get { return _EnsureCommand(CommandId.SelectToEnd); }
}
/// <summary>
/// SelectToPageUp Command
/// </summary>
public static RoutedUICommand SelectToPageUp
{
get { return _EnsureCommand(CommandId.SelectToPageUp); }
}
/// <summary>
/// SelectToPageDown Command
/// </summary>
public static RoutedUICommand SelectToPageDown
{
get { return _EnsureCommand(CommandId.SelectToPageDown); }
}
/// <summary>
/// MoveFocusUp Command
/// </summary>
public static RoutedUICommand MoveFocusUp
{
get { return _EnsureCommand(CommandId.MoveFocusUp); }
}
/// <summary>
/// MoveFocusDown Command
/// </summary>
public static RoutedUICommand MoveFocusDown
{
get { return _EnsureCommand(CommandId.MoveFocusDown); }
}
/// <summary>
/// MoveFocusForward Command
/// </summary>
public static RoutedUICommand MoveFocusForward
{
get { return _EnsureCommand(CommandId.MoveFocusForward); }
}
/// <summary>
/// MoveFocusBack
/// </summary>
public static RoutedUICommand MoveFocusBack
{
get { return _EnsureCommand(CommandId.MoveFocusBack); }
}
/// <summary>
/// MoveFocusPageUp Command
/// </summary>
public static RoutedUICommand MoveFocusPageUp
{
get { return _EnsureCommand(CommandId.MoveFocusPageUp); }
}
/// <summary>
/// MoveFocusPageDown
/// </summary>
public static RoutedUICommand MoveFocusPageDown
{
get { return _EnsureCommand(CommandId.MoveFocusPageDown); }
}
#endregion Public Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
private static string GetPropertyName(CommandId commandId)
{
string propertyName = String.Empty;
switch (commandId)
{
case CommandId.ScrollPageUp:propertyName = "ScrollPageUp"; break;
case CommandId.ScrollPageDown:propertyName = "ScrollPageDown"; break;
case CommandId.ScrollPageLeft: propertyName = "ScrollPageLeft"; break;
case CommandId.ScrollPageRight: propertyName = "ScrollPageRight"; break;
case CommandId.ScrollByLine:propertyName = "ScrollByLine"; break;
case CommandId.MoveLeft:propertyName = "MoveLeft";break;
case CommandId.MoveRight:propertyName = "MoveRight";break;
case CommandId.MoveUp:propertyName = "MoveUp"; break;
case CommandId.MoveDown:propertyName = "MoveDown"; break;
case CommandId.ExtendSelectionUp:propertyName = "ExtendSelectionUp"; break;
case CommandId.ExtendSelectionDown:propertyName = "ExtendSelectionDown"; break;
case CommandId.ExtendSelectionLeft:propertyName = "ExtendSelectionLeft"; break;
case CommandId.ExtendSelectionRight:propertyName = "ExtendSelectionRight"; break;
case CommandId.MoveToHome:propertyName = "MoveToHome"; break;
case CommandId.MoveToEnd:propertyName = "MoveToEnd"; break;
case CommandId.MoveToPageUp:propertyName = "MoveToPageUp"; break;
case CommandId.MoveToPageDown:propertyName = "MoveToPageDown"; break;
case CommandId.SelectToHome:propertyName = "SelectToHome"; break;
case CommandId.SelectToEnd:propertyName = "SelectToEnd"; break;
case CommandId.SelectToPageDown:propertyName = "SelectToPageDown"; break;
case CommandId.SelectToPageUp:propertyName = "SelectToPageUp"; break;
case CommandId.MoveFocusUp:propertyName = "MoveFocusUp"; break;
case CommandId.MoveFocusDown:propertyName = "MoveFocusDown"; break;
case CommandId.MoveFocusBack:propertyName = "MoveFocusBack"; break;
case CommandId.MoveFocusForward:propertyName = "MoveFocusForward"; break;
case CommandId.MoveFocusPageUp:propertyName = "MoveFocusPageUp"; break;
case CommandId.MoveFocusPageDown:propertyName = "MoveFocusPageDown"; break;
}
return propertyName;
}
internal static string GetUIText(byte commandId)
{
string uiText = String.Empty;
switch ((CommandId)commandId)
{
case CommandId.ScrollPageUp: uiText = SR.Get(SRID.ScrollPageUpText); break;
case CommandId.ScrollPageDown: uiText = SR.Get(SRID.ScrollPageDownText); break;
case CommandId.ScrollPageLeft: uiText = SR.Get(SRID.ScrollPageLeftText); break;
case CommandId.ScrollPageRight: uiText = SR.Get(SRID.ScrollPageRightText); break;
case CommandId.ScrollByLine: uiText = SR.Get(SRID.ScrollByLineText); break;
case CommandId.MoveLeft:uiText = SR.Get(SRID.MoveLeftText);break;
case CommandId.MoveRight:uiText = SR.Get(SRID.MoveRightText);break;
case CommandId.MoveUp: uiText = SR.Get(SRID.MoveUpText); break;
case CommandId.MoveDown: uiText = SR.Get(SRID.MoveDownText); break;
case CommandId.ExtendSelectionUp: uiText = SR.Get(SRID.ExtendSelectionUpText); break;
case CommandId.ExtendSelectionDown: uiText = SR.Get(SRID.ExtendSelectionDownText); break;
case CommandId.ExtendSelectionLeft: uiText = SR.Get(SRID.ExtendSelectionLeftText); break;
case CommandId.ExtendSelectionRight: uiText = SR.Get(SRID.ExtendSelectionRightText); break;
case CommandId.MoveToHome: uiText = SR.Get(SRID.MoveToHomeText); break;
case CommandId.MoveToEnd: uiText = SR.Get(SRID.MoveToEndText); break;
case CommandId.MoveToPageUp: uiText = SR.Get(SRID.MoveToPageUpText); break;
case CommandId.MoveToPageDown: uiText = SR.Get(SRID.MoveToPageDownText); break;
case CommandId.SelectToHome: uiText = SR.Get(SRID.SelectToHomeText); break;
case CommandId.SelectToEnd: uiText = SR.Get(SRID.SelectToEndText); break;
case CommandId.SelectToPageDown: uiText = SR.Get(SRID.SelectToPageDownText); break;
case CommandId.SelectToPageUp: uiText = SR.Get(SRID.SelectToPageUpText); break;
case CommandId.MoveFocusUp: uiText = SR.Get(SRID.MoveFocusUpText); break;
case CommandId.MoveFocusDown: uiText = SR.Get(SRID.MoveFocusDownText); break;
case CommandId.MoveFocusBack: uiText = SR.Get(SRID.MoveFocusBackText); break;
case CommandId.MoveFocusForward: uiText = SR.Get(SRID.MoveFocusForwardText); break;
case CommandId.MoveFocusPageUp: uiText = SR.Get(SRID.MoveFocusPageUpText); break;
case CommandId.MoveFocusPageDown: uiText = SR.Get(SRID.MoveFocusPageDownText); break;
}
return uiText;
}
internal static InputGestureCollection LoadDefaultGestureFromResource(byte commandId)
{
InputGestureCollection gestures = new InputGestureCollection();
//Standard Commands
switch ((CommandId)commandId)
{
case CommandId.ScrollPageUp:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.ScrollPageUpKey),
SR.Get(SRID.ScrollPageUpKeyDisplayString),
gestures);
break;
case CommandId.ScrollPageDown:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.ScrollPageDownKey),
SR.Get(SRID.ScrollPageDownKeyDisplayString),
gestures);
break;
case CommandId.ScrollPageLeft:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.ScrollPageLeftKey),
SR.Get(SRID.ScrollPageLeftKeyDisplayString),
gestures);
break;
case CommandId.ScrollPageRight:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.ScrollPageRightKey),
SR.Get(SRID.ScrollPageRightKeyDisplayString),
gestures);
break;
case CommandId.ScrollByLine:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.ScrollByLineKey),
SR.Get(SRID.ScrollByLineKeyDisplayString),
gestures);
break;
case CommandId.MoveLeft:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveLeftKey),
SR.Get(SRID.MoveLeftKeyDisplayString),
gestures);
break;
case CommandId.MoveRight:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveRightKey),
SR.Get(SRID.MoveRightKeyDisplayString),
gestures);
break;
case CommandId.MoveUp:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveUpKey),
SR.Get(SRID.MoveUpKeyDisplayString),
gestures);
break;
case CommandId.MoveDown:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveDownKey),
SR.Get(SRID.MoveDownKeyDisplayString),
gestures);
break;
case CommandId.ExtendSelectionUp:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.ExtendSelectionUpKey),
SR.Get(SRID.ExtendSelectionUpKeyDisplayString),
gestures);
break;
case CommandId.ExtendSelectionDown:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.ExtendSelectionDownKey),
SR.Get(SRID.ExtendSelectionDownKeyDisplayString),
gestures);
break;
case CommandId.ExtendSelectionLeft:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.ExtendSelectionLeftKey),
SR.Get(SRID.ExtendSelectionLeftKeyDisplayString),
gestures);
break;
case CommandId.ExtendSelectionRight:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.ExtendSelectionRightKey),
SR.Get(SRID.ExtendSelectionRightKeyDisplayString),
gestures);
break;
case CommandId.MoveToHome:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveToHomeKey),
SR.Get(SRID.MoveToHomeKeyDisplayString),
gestures);
break;
case CommandId.MoveToEnd:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveToEndKey),
SR.Get(SRID.MoveToEndKeyDisplayString),
gestures);
break;
case CommandId.MoveToPageUp:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveToPageUpKey),
SR.Get(SRID.MoveToPageUpKeyDisplayString),
gestures);
break;
case CommandId.MoveToPageDown:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveToPageDownKey),
SR.Get(SRID.MoveToPageDownKeyDisplayString),
gestures);
break;
case CommandId.SelectToHome:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.SelectToHomeKey),
SR.Get(SRID.SelectToHomeKeyDisplayString),
gestures);
break;
case CommandId.SelectToEnd:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.SelectToEndKey),
SR.Get(SRID.SelectToEndKeyDisplayString),
gestures);
break;
case CommandId.SelectToPageDown:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.SelectToPageDownKey),
SR.Get(SRID.SelectToPageDownKeyDisplayString),
gestures);
break;
case CommandId.SelectToPageUp:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.SelectToPageUpKey),
SR.Get(SRID.SelectToPageUpKeyDisplayString),
gestures);
break;
case CommandId.MoveFocusUp:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveFocusUpKey),
SR.Get(SRID.MoveFocusUpKeyDisplayString),
gestures);
break;
case CommandId.MoveFocusDown:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveFocusDownKey),
SR.Get(SRID.MoveFocusDownKeyDisplayString),
gestures);
break;
case CommandId.MoveFocusBack:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveFocusBackKey),
SR.Get(SRID.MoveFocusBackKeyDisplayString),
gestures);
break;
case CommandId.MoveFocusForward:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveFocusForwardKey),
SR.Get(SRID.MoveFocusForwardKeyDisplayString),
gestures);
break;
case CommandId.MoveFocusPageUp:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveFocusPageUpKey),
SR.Get(SRID.MoveFocusPageUpKeyDisplayString),
gestures);
break;
case CommandId.MoveFocusPageDown:
KeyGesture.AddGesturesFromResourceStrings(
SR.Get(SRID.MoveFocusPageDownKey),
SR.Get(SRID.MoveFocusPageDownKeyDisplayString),
gestures);
break;
}
return gestures;
}
private static RoutedUICommand _EnsureCommand(CommandId idCommand)
{
if (idCommand >= 0 && idCommand < CommandId.Last)
{
lock (_internalCommands.SyncRoot)
{
if (_internalCommands[(int)idCommand] == null)
{
RoutedUICommand newCommand = new RoutedUICommand(GetPropertyName(idCommand), typeof(ComponentCommands), (byte)idCommand);
newCommand.AreInputGesturesDelayLoaded = true;
_internalCommands[(int)idCommand] = newCommand;
}
}
return _internalCommands[(int)idCommand];
}
return null;
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// these constants will go away in future, its just to index into the right one.
private enum CommandId : byte
{
// Formatting
ScrollPageUp = 1,
ScrollPageDown = 2,
ScrollPageLeft = 3,
ScrollPageRight = 4,
ScrollByLine = 5,
MoveLeft = 6,
MoveRight = 7,
MoveUp = 8,
MoveDown = 9,
MoveToHome = 10,
MoveToEnd = 11,
MoveToPageUp = 12,
MoveToPageDown = 13,
SelectToHome = 14,
SelectToEnd = 15,
SelectToPageUp = 16,
SelectToPageDown = 17,
MoveFocusUp = 18,
MoveFocusDown = 19,
MoveFocusForward = 20,
MoveFocusBack = 21,
MoveFocusPageUp = 22,
MoveFocusPageDown = 23,
ExtendSelectionLeft = 24,
ExtendSelectionRight = 25,
ExtendSelectionUp = 26,
ExtendSelectionDown = 27,
// Last
Last = 28
}
private static RoutedUICommand[] _internalCommands = new RoutedUICommand[(int)CommandId.Last];
#endregion Private Fields
}
}
| |
using System;
using XPlatUtils;
namespace Toggl.Phoebe.Logging
{
public abstract class BaseLogger : ILogger
{
private readonly LogLevel threshold;
private readonly LogLevel consoleThreshold;
protected BaseLogger ()
{
#if DEBUG
threshold = LogLevel.Debug;
consoleThreshold = LogLevel.Debug;
#else
threshold = LogLevel.Info;
consoleThreshold = LogLevel.Warning;
#endif
}
protected BaseLogger (LogLevel threshold)
{
this.threshold = threshold;
}
private void Process (LogLevel level, string tag, string message, Exception exc = null)
{
LogToConsole (level, tag, message, exc);
LogToFile (level, tag, message, exc);
LogToLoggerClient (level, tag, message, exc);
}
private void LogToConsole (LogLevel level, string tag, string message, Exception exc)
{
if (level < consoleThreshold) {
return;
}
WriteConsole (level, tag, message, exc);
}
private void LogToFile (LogLevel level, string tag, string message, Exception exc)
{
var logStore = ServiceContainer.Resolve<LogStore> ();
if (logStore != null) {
logStore.Record (level, tag, message, exc);
}
}
private void LogToLoggerClient (LogLevel level, string tag, string message, Exception exc)
{
if (level == LogLevel.Error) {
ErrorSeverity severity = ErrorSeverity.Error;
var md = new Metadata ();
md.AddToTab ("Logger", "Tag", tag);
md.AddToTab ("Logger", "Message", message);
AddExtraMetadata (md);
var loggerClient = ServiceContainer.Resolve<ILoggerClient> ();
if (loggerClient != null) {
loggerClient.Notify (exc, severity, md);
}
}
}
protected abstract void AddExtraMetadata (Metadata md);
protected virtual void WriteConsole (LogLevel level, string tag, string message, Exception exc)
{
Console.WriteLine ("[{1}] {0}: {2}", level, tag, message);
if (exc != null) {
Console.WriteLine (exc.ToString ());
}
}
public void Debug (string tag, string message)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, message);
}
public void Debug (string tag, string message, object arg0)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, string.Format (message, arg0));
}
public void Debug (string tag, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, string.Format (message, arg0, arg1));
}
public void Debug (string tag, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, string.Format (message, arg0, arg1, arg2));
}
public void Debug (string tag, string message, params object[] args)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, string.Format (message, args));
}
public void Debug (string tag, Exception exc, string message)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, message, exc);
}
public void Debug (string tag, Exception exc, string message, object arg0)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, string.Format (message, arg0), exc);
}
public void Debug (string tag, Exception exc, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, string.Format (message, arg0, arg1), exc);
}
public void Debug (string tag, Exception exc, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, string.Format (message, arg0, arg1, arg2), exc);
}
public void Debug (string tag, Exception exc, string message, params object[] args)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, string.Format (message, args), exc);
}
public void Info (string tag, string message)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, message);
}
public void Info (string tag, string message, object arg0)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, string.Format (message, arg0));
}
public void Info (string tag, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, string.Format (message, arg0, arg1));
}
public void Info (string tag, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, string.Format (message, arg0, arg1, arg2));
}
public void Info (string tag, string message, params object[] args)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, string.Format (message, args));
}
public void Info (string tag, Exception exc, string message)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, message, exc);
}
public void Info (string tag, Exception exc, string message, object arg0)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, string.Format (message, arg0), exc);
}
public void Info (string tag, Exception exc, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, string.Format (message, arg0, arg1), exc);
}
public void Info (string tag, Exception exc, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, string.Format (message, arg0, arg1, arg2), exc);
}
public void Info (string tag, Exception exc, string message, params object[] args)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, string.Format (message, args), exc);
}
public void Warning (string tag, string message)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, message);
}
public void Warning (string tag, string message, object arg0)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, string.Format (message, arg0));
}
public void Warning (string tag, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, string.Format (message, arg0, arg1));
}
public void Warning (string tag, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, string.Format (message, arg0, arg1, arg2));
}
public void Warning (string tag, string message, params object[] args)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, string.Format (message, args));
}
public void Warning (string tag, Exception exc, string message)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, message, exc);
}
public void Warning (string tag, Exception exc, string message, object arg0)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, string.Format (message, arg0), exc);
}
public void Warning (string tag, Exception exc, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, string.Format (message, arg0, arg1), exc);
}
public void Warning (string tag, Exception exc, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, string.Format (message, arg0, arg1, arg2), exc);
}
public void Warning (string tag, Exception exc, string message, params object[] args)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, string.Format (message, args), exc);
}
public void Error (string tag, string message)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, message);
}
public void Error (string tag, string message, object arg0)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, string.Format (message, arg0));
}
public void Error (string tag, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, string.Format (message, arg0, arg1));
}
public void Error (string tag, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, string.Format (message, arg0, arg1, arg2));
}
public void Error (string tag, string message, params object[] args)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, string.Format (message, args));
}
public void Error (string tag, Exception exc, string message)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, message, exc);
}
public void Error (string tag, Exception exc, string message, object arg0)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, string.Format (message, arg0), exc);
}
public void Error (string tag, Exception exc, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, string.Format (message, arg0, arg1), exc);
}
public void Error (string tag, Exception exc, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, string.Format (message, arg0, arg1, arg2), exc);
}
public void Error (string tag, Exception exc, string message, params object[] args)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, string.Format (message, args), exc);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeDom.Compiler
{
using System;
using Microsoft.CodeDom;
using System.Collections;
using System.Collections.Specialized;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
/// <devdoc>
/// <para>
/// Represents the parameters used in to invoke the compiler.
/// </para>
/// </devdoc>
// [Serializable],
public class CompilerParameters
{
// [OptionalField] // Not available in DNX (NetCore)
private string _coreAssemblyFileName = String.Empty;
private StringCollection _assemblyNames = new StringCollection();
// [OptionalField] // Not available in DNX (NetCore)
private StringCollection _embeddedResources = new StringCollection();
// [OptionalField] // Not available in DNX (NetCore)
private StringCollection _linkedResources = new StringCollection();
private string _outputName;
private string _mainClass;
private bool _generateInMemory = false;
private bool _includeDebugInformation = false;
private int _warningLevel = -1; // -1 means not set (use compiler default)
private string _compilerOptions;
private string _win32Resource;
private bool _treatWarningsAsErrors = false;
private bool _generateExecutable = false;
private TempFileCollection _tempFiles;
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='Microsoft.CodeDom.Compiler.CompilerParameters'/>.
/// </para>
/// </devdoc>
public CompilerParameters() :
this(null, null)
{
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='Microsoft.CodeDom.Compiler.CompilerParameters'/> using the specified
/// assembly names.
/// </para>
/// </devdoc>
public CompilerParameters(string[] assemblyNames) :
this(assemblyNames, null, false)
{
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='Microsoft.CodeDom.Compiler.CompilerParameters'/> using the specified
/// assembly names and output name.
/// </para>
/// </devdoc>
public CompilerParameters(string[] assemblyNames, string outputName) :
this(assemblyNames, outputName, false)
{
}
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='Microsoft.CodeDom.Compiler.CompilerParameters'/> using the specified
/// assembly names, output name and a whether to include debug information flag.
/// </para>
/// </devdoc>
public CompilerParameters(string[] assemblyNames, string outputName, bool includeDebugInformation)
{
if (assemblyNames != null)
{
ReferencedAssemblies.AddRange(assemblyNames);
}
_outputName = outputName;
_includeDebugInformation = includeDebugInformation;
}
/// <summary>
/// The "core" or "standard" assembly that contains basic types such as <code>Object</code>, <code>Int32</code> and the like
/// that is to be used for the compilation.<br />
/// If the value of this property is an empty string (or <code>null</code>), the default core assembly will be used by the
/// compiler (depending on the compiler version this may be <code>mscorlib.dll</code> or <code>System.Runtime.dll</code> in
/// a Framework or reference assembly directory).<br />
/// If the value of this property is not empty, CodeDOM will emit compiler options to not reference <em>any</em> assemblies
/// implicitly during compilation. It will also explicitly reference the assembly file specified in this property.<br />
/// For compilers that only implicitly reference the "core" or "standard" assembly by default, this option can be used on its own.
/// For compilers that implicitly reference more assemblies on top of the "core" / "standard" assembly, using this option may require
/// specifying additional entries in the <code>Microsoft.CodeDom.Compiler.<bold>ReferencedAssemblies</bold></code> collection.<br />
/// Note: An <code>ICodeCompiler</code> / <code>CoodeDomProvider</code> implementation may choose to ignore this property.
/// </summary>
public string CoreAssemblyFileName
{
get
{
return _coreAssemblyFileName;
}
set
{
_coreAssemblyFileName = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether to generate an executable.
/// </para>
/// </devdoc>
public bool GenerateExecutable
{
get
{
return _generateExecutable;
}
set
{
_generateExecutable = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether to generate in memory.
/// </para>
/// </devdoc>
public bool GenerateInMemory
{
get
{
return _generateInMemory;
}
set
{
_generateInMemory = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the assemblies referenced by the source to compile.
/// </para>
/// </devdoc>
public StringCollection ReferencedAssemblies
{
get
{
return _assemblyNames;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the main class.
/// </para>
/// </devdoc>
public string MainClass
{
get
{
return _mainClass;
}
set
{
_mainClass = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the output assembly.
/// </para>
/// </devdoc>
public string OutputAssembly
{
get
{
return _outputName;
}
set
{
_outputName = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the temp files.
/// </para>
/// </devdoc>
public TempFileCollection TempFiles
{
get
{
if (_tempFiles == null)
_tempFiles = new TempFileCollection();
return _tempFiles;
}
set
{
_tempFiles = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets whether to include debug information in the compiled
/// executable.
/// </para>
/// </devdoc>
public bool IncludeDebugInformation
{
get
{
return _includeDebugInformation;
}
set
{
_includeDebugInformation = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool TreatWarningsAsErrors
{
get
{
return _treatWarningsAsErrors;
}
set
{
_treatWarningsAsErrors = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int WarningLevel
{
get
{
return _warningLevel;
}
set
{
_warningLevel = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string CompilerOptions
{
get
{
return _compilerOptions;
}
set
{
_compilerOptions = value;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public string Win32Resource
{
get
{
return _win32Resource;
}
set
{
_win32Resource = value;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the resources to be compiled into the target
/// </para>
/// </devdoc>
[ComVisible(false)]
public StringCollection EmbeddedResources
{
get
{
return _embeddedResources;
}
}
/// <devdoc>
/// <para>
/// Gets or sets the linked resources
/// </para>
/// </devdoc>
[ComVisible(false)]
public StringCollection LinkedResources
{
get
{
return _linkedResources;
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/logging.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 Google.Api {
/// <summary>Holder for reflection information generated from google/api/logging.proto</summary>
public static partial class LoggingReflection {
#region Descriptor
/// <summary>File descriptor for google/api/logging.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static LoggingReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chhnb29nbGUvYXBpL2xvZ2dpbmcucHJvdG8SCmdvb2dsZS5hcGkaHGdvb2ds",
"ZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8i1wEKB0xvZ2dpbmcSRQoVcHJvZHVj",
"ZXJfZGVzdGluYXRpb25zGAEgAygLMiYuZ29vZ2xlLmFwaS5Mb2dnaW5nLkxv",
"Z2dpbmdEZXN0aW5hdGlvbhJFChVjb25zdW1lcl9kZXN0aW5hdGlvbnMYAiAD",
"KAsyJi5nb29nbGUuYXBpLkxvZ2dpbmcuTG9nZ2luZ0Rlc3RpbmF0aW9uGj4K",
"EkxvZ2dpbmdEZXN0aW5hdGlvbhIaChJtb25pdG9yZWRfcmVzb3VyY2UYAyAB",
"KAkSDAoEbG9ncxgBIAMoCUJuCg5jb20uZ29vZ2xlLmFwaUIMTG9nZ2luZ1By",
"b3RvUAFaRWdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMv",
"YXBpL3NlcnZpY2Vjb25maWc7c2VydmljZWNvbmZpZ6ICBEdBUEliBnByb3Rv",
"Mw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Logging), global::Google.Api.Logging.Parser, new[]{ "ProducerDestinations", "ConsumerDestinations" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Logging.Types.LoggingDestination), global::Google.Api.Logging.Types.LoggingDestination.Parser, new[]{ "MonitoredResource", "Logs" }, null, null, null)})
}));
}
#endregion
}
#region Messages
/// <summary>
/// Logging configuration of the service.
///
/// The following example shows how to configure logs to be sent to the
/// producer and consumer projects. In the example, the `activity_history`
/// log is sent to both the producer and consumer projects, whereas the
/// `purchase_history` log is only sent to the producer project.
///
/// monitored_resources:
/// - type: library.googleapis.com/branch
/// labels:
/// - key: /city
/// description: The city where the library branch is located in.
/// - key: /name
/// description: The name of the branch.
/// logs:
/// - name: activity_history
/// labels:
/// - key: /customer_id
/// - name: purchase_history
/// logging:
/// producer_destinations:
/// - monitored_resource: library.googleapis.com/branch
/// logs:
/// - activity_history
/// - purchase_history
/// consumer_destinations:
/// - monitored_resource: library.googleapis.com/branch
/// logs:
/// - activity_history
/// </summary>
public sealed partial class Logging : pb::IMessage<Logging> {
private static readonly pb::MessageParser<Logging> _parser = new pb::MessageParser<Logging>(() => new Logging());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Logging> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.LoggingReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Logging() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Logging(Logging other) : this() {
producerDestinations_ = other.producerDestinations_.Clone();
consumerDestinations_ = other.consumerDestinations_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Logging Clone() {
return new Logging(this);
}
/// <summary>Field number for the "producer_destinations" field.</summary>
public const int ProducerDestinationsFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Api.Logging.Types.LoggingDestination> _repeated_producerDestinations_codec
= pb::FieldCodec.ForMessage(10, global::Google.Api.Logging.Types.LoggingDestination.Parser);
private readonly pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination> producerDestinations_ = new pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination>();
/// <summary>
/// Logging configurations for sending logs to the producer project.
/// There can be multiple producer destinations, each one must have a
/// different monitored resource type. A log can be used in at most
/// one producer destination.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination> ProducerDestinations {
get { return producerDestinations_; }
}
/// <summary>Field number for the "consumer_destinations" field.</summary>
public const int ConsumerDestinationsFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Api.Logging.Types.LoggingDestination> _repeated_consumerDestinations_codec
= pb::FieldCodec.ForMessage(18, global::Google.Api.Logging.Types.LoggingDestination.Parser);
private readonly pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination> consumerDestinations_ = new pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination>();
/// <summary>
/// Logging configurations for sending logs to the consumer project.
/// There can be multiple consumer destinations, each one must have a
/// different monitored resource type. A log can be used in at most
/// one consumer destination.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Api.Logging.Types.LoggingDestination> ConsumerDestinations {
get { return consumerDestinations_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Logging);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Logging other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!producerDestinations_.Equals(other.producerDestinations_)) return false;
if(!consumerDestinations_.Equals(other.consumerDestinations_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= producerDestinations_.GetHashCode();
hash ^= consumerDestinations_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
producerDestinations_.WriteTo(output, _repeated_producerDestinations_codec);
consumerDestinations_.WriteTo(output, _repeated_consumerDestinations_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += producerDestinations_.CalculateSize(_repeated_producerDestinations_codec);
size += consumerDestinations_.CalculateSize(_repeated_consumerDestinations_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Logging other) {
if (other == null) {
return;
}
producerDestinations_.Add(other.producerDestinations_);
consumerDestinations_.Add(other.consumerDestinations_);
}
[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: {
producerDestinations_.AddEntriesFrom(input, _repeated_producerDestinations_codec);
break;
}
case 18: {
consumerDestinations_.AddEntriesFrom(input, _repeated_consumerDestinations_codec);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the Logging message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Configuration of a specific logging destination (the producer project
/// or the consumer project).
/// </summary>
public sealed partial class LoggingDestination : pb::IMessage<LoggingDestination> {
private static readonly pb::MessageParser<LoggingDestination> _parser = new pb::MessageParser<LoggingDestination>(() => new LoggingDestination());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<LoggingDestination> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.Logging.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoggingDestination() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoggingDestination(LoggingDestination other) : this() {
monitoredResource_ = other.monitoredResource_;
logs_ = other.logs_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LoggingDestination Clone() {
return new LoggingDestination(this);
}
/// <summary>Field number for the "monitored_resource" field.</summary>
public const int MonitoredResourceFieldNumber = 3;
private string monitoredResource_ = "";
/// <summary>
/// The monitored resource type. The type must be defined in the
/// [Service.monitored_resources][google.api.Service.monitored_resources] section.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string MonitoredResource {
get { return monitoredResource_; }
set {
monitoredResource_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "logs" field.</summary>
public const int LogsFieldNumber = 1;
private static readonly pb::FieldCodec<string> _repeated_logs_codec
= pb::FieldCodec.ForString(10);
private readonly pbc::RepeatedField<string> logs_ = new pbc::RepeatedField<string>();
/// <summary>
/// Names of the logs to be sent to this destination. Each name must
/// be defined in the [Service.logs][google.api.Service.logs] section. If the log name is
/// not a domain scoped name, it will be automatically prefixed with
/// the service name followed by "/".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> Logs {
get { return logs_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as LoggingDestination);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(LoggingDestination other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (MonitoredResource != other.MonitoredResource) return false;
if(!logs_.Equals(other.logs_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (MonitoredResource.Length != 0) hash ^= MonitoredResource.GetHashCode();
hash ^= logs_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
logs_.WriteTo(output, _repeated_logs_codec);
if (MonitoredResource.Length != 0) {
output.WriteRawTag(26);
output.WriteString(MonitoredResource);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (MonitoredResource.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(MonitoredResource);
}
size += logs_.CalculateSize(_repeated_logs_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(LoggingDestination other) {
if (other == null) {
return;
}
if (other.MonitoredResource.Length != 0) {
MonitoredResource = other.MonitoredResource;
}
logs_.Add(other.logs_);
}
[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: {
logs_.AddEntriesFrom(input, _repeated_logs_codec);
break;
}
case 26: {
MonitoredResource = input.ReadString();
break;
}
}
}
}
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.DocumentationCommentFormatting;
using Microsoft.CodeAnalysis.DocumentationCommentFormatting;
using Microsoft.CodeAnalysis.MetadataAsSource;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.VisualBasic.DocumentationCommentFormatting;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource
{
public class DocCommentFormatterTests
{
private CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService();
private VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService();
private void TestFormat(string docCommentXmlFragment, string expected)
{
TestFormat(docCommentXmlFragment, expected, expected);
}
private void TestFormat(string docCommentXmlFragment, string expectedCSharp, string expectedVB)
{
var docComment = DocumentationComment.FromXmlFragment(docCommentXmlFragment);
var csharpFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_csharpService, docComment));
var vbFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_vbService, docComment));
Assert.Equal(expectedCSharp, csharpFormattedComment);
Assert.Equal(expectedVB, vbFormattedComment);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void Summary()
{
var comment = "<summary>This is a summary.</summary>";
var expected =
@"Summary:
This is a summary.";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void Wrapping1()
{
var comment = "<summary>I am the very model of a modern major general. This is a very long comment. And getting longer by the minute.</summary>";
var expected =
@"Summary:
I am the very model of a modern major general. This is a very long comment. And
getting longer by the minute.";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void Wrapping2()
{
var comment = "<summary>I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute.</summary>";
var expected =
@"Summary:
I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe
minute.";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void Exception()
{
var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception>";
var expected =
@"Exceptions:
T:System.NotImplementedException:
throws NotImplementedException";
TestFormat(comment, expected);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void MultipleExceptionTags()
{
var comment =
@"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception>
<exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception>";
var expected =
@"Exceptions:
T:System.NotImplementedException:
throws NotImplementedException
T:System.InvalidOperationException:
throws InvalidOperationException";
TestFormat(comment, expected);
}
[Fact, WorkItem(530760)]
[Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void MultipleExceptionTagsWithSameType()
{
var comment =
@"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException for reason X</exception>
<exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception>
<exception cref=""T:System.NotImplementedException"">also throws NotImplementedException for reason Y</exception>";
var expected =
@"Exceptions:
T:System.NotImplementedException:
throws NotImplementedException for reason X
T:System.NotImplementedException:
also throws NotImplementedException for reason Y
T:System.InvalidOperationException:
throws InvalidOperationException";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void Returns()
{
var comment = @"<returns>A string is returned</returns>";
var expected =
@"Returns:
A string is returned";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void SummaryAndParams()
{
var comment =
@"<summary>This is the summary.</summary>
<param name=""a"">The param named 'a'</param>
<param name=""b"">The param named 'b'</param>";
var expected =
@"Summary:
This is the summary.
Parameters:
a:
The param named 'a'
b:
The param named 'b'";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void TypeParameters()
{
var comment =
@"<typeparam name=""T"">The type param named 'T'</typeparam>
<typeparam name=""U"">The type param named 'U'</typeparam>";
var expected =
@"Type parameters:
T:
The type param named 'T'
U:
The type param named 'U'";
TestFormat(comment, expected);
}
[Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)]
public void FormatEverything()
{
var comment =
@"<summary>
This is a summary of something.
</summary>
<param name=""a"">The param named 'a'.</param>
<param name=""b""></param>
<param name=""c"">The param named 'c'.</param>
<typeparam name=""T"">A type parameter.</typeparam>
<typeparam name=""U""></typeparam>
<typeparam name=""V"">Another type parameter.</typeparam>
<returns>This returns nothing.</returns>
<exception cref=""System.FooException"">Thrown for an unknown reason</exception>
<exception cref=""System.BarException""></exception>
<exception cref=""System.BlahException"">Thrown when blah blah blah</exception>
<remarks>This doc comment is really not very remarkable.</remarks>";
var expected =
@"Summary:
This is a summary of something.
Parameters:
a:
The param named 'a'.
b:
c:
The param named 'c'.
Type parameters:
T:
A type parameter.
U:
V:
Another type parameter.
Returns:
This returns nothing.
Exceptions:
System.FooException:
Thrown for an unknown reason
System.BarException:
System.BlahException:
Thrown when blah blah blah
Remarks:
This doc comment is really not very remarkable.";
TestFormat(comment, expected);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/appengine/v1/application.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 Google.Appengine.V1 {
/// <summary>Holder for reflection information generated from google/appengine/v1/application.proto</summary>
public static partial class ApplicationReflection {
#region Descriptor
/// <summary>File descriptor for google/appengine/v1/application.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ApplicationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiVnb29nbGUvYXBwZW5naW5lL3YxL2FwcGxpY2F0aW9uLnByb3RvEhNnb29n",
"bGUuYXBwZW5naW5lLnYxGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3Rv",
"Gh5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8ilAIKC0FwcGxpY2F0",
"aW9uEgwKBG5hbWUYASABKAkSCgoCaWQYAiABKAkSPAoOZGlzcGF0Y2hfcnVs",
"ZXMYAyADKAsyJC5nb29nbGUuYXBwZW5naW5lLnYxLlVybERpc3BhdGNoUnVs",
"ZRITCgthdXRoX2RvbWFpbhgGIAEoCRITCgtsb2NhdGlvbl9pZBgHIAEoCRIT",
"Cgtjb2RlX2J1Y2tldBgIIAEoCRI8ChlkZWZhdWx0X2Nvb2tpZV9leHBpcmF0",
"aW9uGAkgASgLMhkuZ29vZ2xlLnByb3RvYnVmLkR1cmF0aW9uEhgKEGRlZmF1",
"bHRfaG9zdG5hbWUYCyABKAkSFgoOZGVmYXVsdF9idWNrZXQYDCABKAkiQAoP",
"VXJsRGlzcGF0Y2hSdWxlEg4KBmRvbWFpbhgBIAEoCRIMCgRwYXRoGAIgASgJ",
"Eg8KB3NlcnZpY2UYAyABKAlCawoXY29tLmdvb2dsZS5hcHBlbmdpbmUudjFC",
"EEFwcGxpY2F0aW9uUHJvdG9QAVo8Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJv",
"dG8vZ29vZ2xlYXBpcy9hcHBlbmdpbmUvdjE7YXBwZW5naW5lYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Appengine.V1.Application), global::Google.Appengine.V1.Application.Parser, new[]{ "Name", "Id", "DispatchRules", "AuthDomain", "LocationId", "CodeBucket", "DefaultCookieExpiration", "DefaultHostname", "DefaultBucket" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Appengine.V1.UrlDispatchRule), global::Google.Appengine.V1.UrlDispatchRule.Parser, new[]{ "Domain", "Path", "Service" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// An Application resource contains the top-level configuration of an App
/// Engine application.
/// </summary>
public sealed partial class Application : pb::IMessage<Application> {
private static readonly pb::MessageParser<Application> _parser = new pb::MessageParser<Application>(() => new Application());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Application> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Appengine.V1.ApplicationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Application() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Application(Application other) : this() {
name_ = other.name_;
id_ = other.id_;
dispatchRules_ = other.dispatchRules_.Clone();
authDomain_ = other.authDomain_;
locationId_ = other.locationId_;
codeBucket_ = other.codeBucket_;
DefaultCookieExpiration = other.defaultCookieExpiration_ != null ? other.DefaultCookieExpiration.Clone() : null;
defaultHostname_ = other.defaultHostname_;
defaultBucket_ = other.defaultBucket_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Application Clone() {
return new Application(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// Full path to the Application resource in the API.
/// Example: `apps/myapp`.
///
/// @OutputOnly
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 2;
private string id_ = "";
/// <summary>
/// Identifier of the Application resource. This identifier is equivalent
/// to the project ID of the Google Cloud Platform project where you want to
/// deploy your application.
/// Example: `myapp`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Id {
get { return id_; }
set {
id_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "dispatch_rules" field.</summary>
public const int DispatchRulesFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Appengine.V1.UrlDispatchRule> _repeated_dispatchRules_codec
= pb::FieldCodec.ForMessage(26, global::Google.Appengine.V1.UrlDispatchRule.Parser);
private readonly pbc::RepeatedField<global::Google.Appengine.V1.UrlDispatchRule> dispatchRules_ = new pbc::RepeatedField<global::Google.Appengine.V1.UrlDispatchRule>();
/// <summary>
/// HTTP path dispatch rules for requests to the application that do not
/// explicitly target a service or version. Rules are order-dependent.
///
/// @OutputOnly
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Appengine.V1.UrlDispatchRule> DispatchRules {
get { return dispatchRules_; }
}
/// <summary>Field number for the "auth_domain" field.</summary>
public const int AuthDomainFieldNumber = 6;
private string authDomain_ = "";
/// <summary>
/// Google Apps authentication domain that controls which users can access
/// this application.
///
/// Defaults to open access for any Google Account.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string AuthDomain {
get { return authDomain_; }
set {
authDomain_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "location_id" field.</summary>
public const int LocationIdFieldNumber = 7;
private string locationId_ = "";
/// <summary>
/// Location from which this application will be run. Application instances
/// will run out of data centers in the chosen location, which is also where
/// all of the application's end user content is stored.
///
/// Defaults to `us-central`.
///
/// Options are:
///
/// `us-central` - Central US
///
/// `europe-west` - Western Europe
///
/// `us-east1` - Eastern US
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string LocationId {
get { return locationId_; }
set {
locationId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "code_bucket" field.</summary>
public const int CodeBucketFieldNumber = 8;
private string codeBucket_ = "";
/// <summary>
/// Google Cloud Storage bucket that can be used for storing files
/// associated with this application. This bucket is associated with the
/// application and can be used by the gcloud deployment commands.
///
/// @OutputOnly
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string CodeBucket {
get { return codeBucket_; }
set {
codeBucket_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "default_cookie_expiration" field.</summary>
public const int DefaultCookieExpirationFieldNumber = 9;
private global::Google.Protobuf.WellKnownTypes.Duration defaultCookieExpiration_;
/// <summary>
/// Cookie expiration policy for this application.
///
/// @OutputOnly
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Duration DefaultCookieExpiration {
get { return defaultCookieExpiration_; }
set {
defaultCookieExpiration_ = value;
}
}
/// <summary>Field number for the "default_hostname" field.</summary>
public const int DefaultHostnameFieldNumber = 11;
private string defaultHostname_ = "";
/// <summary>
/// Hostname used to reach this application, as resolved by App Engine.
///
/// @OutputOnly
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DefaultHostname {
get { return defaultHostname_; }
set {
defaultHostname_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "default_bucket" field.</summary>
public const int DefaultBucketFieldNumber = 12;
private string defaultBucket_ = "";
/// <summary>
/// Google Cloud Storage bucket that can be used by this application to store
/// content.
///
/// @OutputOnly
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DefaultBucket {
get { return defaultBucket_; }
set {
defaultBucket_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Application);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Application other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Id != other.Id) return false;
if(!dispatchRules_.Equals(other.dispatchRules_)) return false;
if (AuthDomain != other.AuthDomain) return false;
if (LocationId != other.LocationId) return false;
if (CodeBucket != other.CodeBucket) return false;
if (!object.Equals(DefaultCookieExpiration, other.DefaultCookieExpiration)) return false;
if (DefaultHostname != other.DefaultHostname) return false;
if (DefaultBucket != other.DefaultBucket) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Id.Length != 0) hash ^= Id.GetHashCode();
hash ^= dispatchRules_.GetHashCode();
if (AuthDomain.Length != 0) hash ^= AuthDomain.GetHashCode();
if (LocationId.Length != 0) hash ^= LocationId.GetHashCode();
if (CodeBucket.Length != 0) hash ^= CodeBucket.GetHashCode();
if (defaultCookieExpiration_ != null) hash ^= DefaultCookieExpiration.GetHashCode();
if (DefaultHostname.Length != 0) hash ^= DefaultHostname.GetHashCode();
if (DefaultBucket.Length != 0) hash ^= DefaultBucket.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Id.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Id);
}
dispatchRules_.WriteTo(output, _repeated_dispatchRules_codec);
if (AuthDomain.Length != 0) {
output.WriteRawTag(50);
output.WriteString(AuthDomain);
}
if (LocationId.Length != 0) {
output.WriteRawTag(58);
output.WriteString(LocationId);
}
if (CodeBucket.Length != 0) {
output.WriteRawTag(66);
output.WriteString(CodeBucket);
}
if (defaultCookieExpiration_ != null) {
output.WriteRawTag(74);
output.WriteMessage(DefaultCookieExpiration);
}
if (DefaultHostname.Length != 0) {
output.WriteRawTag(90);
output.WriteString(DefaultHostname);
}
if (DefaultBucket.Length != 0) {
output.WriteRawTag(98);
output.WriteString(DefaultBucket);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Id.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Id);
}
size += dispatchRules_.CalculateSize(_repeated_dispatchRules_codec);
if (AuthDomain.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(AuthDomain);
}
if (LocationId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(LocationId);
}
if (CodeBucket.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(CodeBucket);
}
if (defaultCookieExpiration_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(DefaultCookieExpiration);
}
if (DefaultHostname.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DefaultHostname);
}
if (DefaultBucket.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DefaultBucket);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Application other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Id.Length != 0) {
Id = other.Id;
}
dispatchRules_.Add(other.dispatchRules_);
if (other.AuthDomain.Length != 0) {
AuthDomain = other.AuthDomain;
}
if (other.LocationId.Length != 0) {
LocationId = other.LocationId;
}
if (other.CodeBucket.Length != 0) {
CodeBucket = other.CodeBucket;
}
if (other.defaultCookieExpiration_ != null) {
if (defaultCookieExpiration_ == null) {
defaultCookieExpiration_ = new global::Google.Protobuf.WellKnownTypes.Duration();
}
DefaultCookieExpiration.MergeFrom(other.DefaultCookieExpiration);
}
if (other.DefaultHostname.Length != 0) {
DefaultHostname = other.DefaultHostname;
}
if (other.DefaultBucket.Length != 0) {
DefaultBucket = other.DefaultBucket;
}
}
[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: {
Name = input.ReadString();
break;
}
case 18: {
Id = input.ReadString();
break;
}
case 26: {
dispatchRules_.AddEntriesFrom(input, _repeated_dispatchRules_codec);
break;
}
case 50: {
AuthDomain = input.ReadString();
break;
}
case 58: {
LocationId = input.ReadString();
break;
}
case 66: {
CodeBucket = input.ReadString();
break;
}
case 74: {
if (defaultCookieExpiration_ == null) {
defaultCookieExpiration_ = new global::Google.Protobuf.WellKnownTypes.Duration();
}
input.ReadMessage(defaultCookieExpiration_);
break;
}
case 90: {
DefaultHostname = input.ReadString();
break;
}
case 98: {
DefaultBucket = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// Rules to match an HTTP request and dispatch that request to a service.
/// </summary>
public sealed partial class UrlDispatchRule : pb::IMessage<UrlDispatchRule> {
private static readonly pb::MessageParser<UrlDispatchRule> _parser = new pb::MessageParser<UrlDispatchRule>(() => new UrlDispatchRule());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UrlDispatchRule> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Appengine.V1.ApplicationReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UrlDispatchRule() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UrlDispatchRule(UrlDispatchRule other) : this() {
domain_ = other.domain_;
path_ = other.path_;
service_ = other.service_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UrlDispatchRule Clone() {
return new UrlDispatchRule(this);
}
/// <summary>Field number for the "domain" field.</summary>
public const int DomainFieldNumber = 1;
private string domain_ = "";
/// <summary>
/// Domain name to match against. The wildcard "`*`" is supported if
/// specified before a period: "`*.`".
///
/// Defaults to matching all domains: "`*`".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Domain {
get { return domain_; }
set {
domain_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "path" field.</summary>
public const int PathFieldNumber = 2;
private string path_ = "";
/// <summary>
/// Pathname within the host. Must start with a "`/`". A
/// single "`*`" can be included at the end of the path. The sum
/// of the lengths of the domain and path may not exceed 100
/// characters.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Path {
get { return path_; }
set {
path_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "service" field.</summary>
public const int ServiceFieldNumber = 3;
private string service_ = "";
/// <summary>
/// Resource ID of a service in this application that should
/// serve the matched request. The service must already
/// exist. Example: `default`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Service {
get { return service_; }
set {
service_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UrlDispatchRule);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UrlDispatchRule other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Domain != other.Domain) return false;
if (Path != other.Path) return false;
if (Service != other.Service) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Domain.Length != 0) hash ^= Domain.GetHashCode();
if (Path.Length != 0) hash ^= Path.GetHashCode();
if (Service.Length != 0) hash ^= Service.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Domain.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Domain);
}
if (Path.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Path);
}
if (Service.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Service);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Domain.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Domain);
}
if (Path.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Path);
}
if (Service.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Service);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UrlDispatchRule other) {
if (other == null) {
return;
}
if (other.Domain.Length != 0) {
Domain = other.Domain;
}
if (other.Path.Length != 0) {
Path = other.Path;
}
if (other.Service.Length != 0) {
Service = other.Service;
}
}
[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: {
Domain = input.ReadString();
break;
}
case 18: {
Path = input.ReadString();
break;
}
case 26: {
Service = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
#region namespace
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using System.Configuration;
using umbraco.BusinessLogic;
using System.Security.Cryptography;
using System.Web.Util;
using System.Collections.Specialized;
using System.Configuration.Provider;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.member;
using System.Collections;
#endregion
namespace umbraco.providers.members {
public class UmbracoRoleProvider : RoleProvider {
#region
private string _ApplicationName = Member.UmbracoRoleProviderName;
#endregion
#region Properties
/// <summary>
/// Gets or sets the name of the application to store and retrieve role information for.
/// </summary>
/// <value></value>
/// <returns>The name of the application to store and retrieve role information for.</returns>
public override string ApplicationName {
get {
return _ApplicationName;
}
set {
if (string.IsNullOrEmpty(value))
throw new ProviderException("ApplicationName cannot be empty.");
if (value.Length > 0x100)
throw new ProviderException("Provider application name too long.");
_ApplicationName = value;
}
}
#endregion
#region Initialization Method
/// <summary>
/// Initializes the provider.
/// </summary>
/// <param name="name">The friendly name of the provider.</param>
/// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
/// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
/// <exception cref="T:System.InvalidOperationException">An attempt is made to call
/// <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider
/// after the provider has already been initialized.</exception>
/// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
public override void Initialize(string name, NameValueCollection config) {
// Initialize values from web.config
if (config == null) throw new ArgumentNullException("config");
if (name == null || name.Length == 0) name = "UmbracoMemberRoleProvider";
if (String.IsNullOrEmpty(config["description"])) {
config.Remove("description");
config.Add("description", "Umbraco Member Role provider");
}
// Initialize the abstract base class.
base.Initialize(name, config);
this._ApplicationName = config["applicationName"];
if (string.IsNullOrEmpty(this._ApplicationName))
this._ApplicationName = SecUtility.GetDefaultAppName();
}
#endregion
#region Methods
/// <summary>
/// Adds the specified user names to the specified roles for the configured applicationName.
/// </summary>
/// <param name="usernames">A string array of user names to be added to the specified roles.</param>
/// <param name="roleNames">A string array of the role names to add the specified user names to.</param>
public override void AddUsersToRoles(string[] usernames, string[] roleNames) {
ArrayList roles = new ArrayList();
foreach (string role in roleNames)
try {
roles.Add(MemberGroup.GetByName(role).Id);
} catch {
throw new ProviderException(String.Format("No role with name '{0}' exists", role));
}
foreach (string username in usernames) {
Member m = Member.GetMemberFromLoginName(username);
foreach (int roleId in roles)
m.AddGroup(roleId);
}
}
/// <summary>
/// Adds a new role to the data source for the configured applicationName.
/// </summary>
/// <param name="roleName">The name of the role to create.</param>
public override void CreateRole(string roleName) {
MemberGroup.MakeNew(roleName, User.GetUser(0));
}
/// <summary>
/// Removes a role from the data source for the configured applicationName.
/// </summary>
/// <param name="roleName">The name of the role to delete.</param>
/// <param name="throwOnPopulatedRole">If true, throw an exception if roleName has one or more members and do not delete roleName.</param>
/// <returns>
/// true if the role was successfully deleted; otherwise, false.
/// </returns>
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) {
MemberGroup group = MemberGroup.GetByName(roleName);
if (group == null)
throw new ProviderException(String.Format("No role with name '{0}' exists", roleName));
else if (throwOnPopulatedRole && group.GetMembersAsIds().Length > 0)
throw new ProviderException(String.Format("Can't delete role '{0}', there are members assigned to the role", roleName));
else {
foreach (Member m in group.GetMembers())
m.RemoveGroup(group.Id);
group.delete();
return true;
}
}
/// <summary>
/// Gets an array of user names in a role where the user name contains the specified user name to match.
/// </summary>
/// <param name="roleName">The role to search in.</param>
/// <param name="usernameToMatch">The user name to search for.</param>
/// <returns>
/// A string array containing the names of all the users where the user name matches usernameToMatch and the user is a member of the specified role.
/// </returns>
public override string[] FindUsersInRole(string roleName, string usernameToMatch) {
ArrayList members = new ArrayList();
MemberGroup group = MemberGroup.GetByName(roleName);
if (group == null)
throw new ProviderException(String.Format("No role with name '{0}' exists", roleName));
else {
foreach (Member m in group.GetMembers(usernameToMatch))
members.Add(m.LoginName);
return (string[])members.ToArray(typeof(string));
}
}
/// <summary>
/// Gets a list of all the roles for the configured applicationName.
/// </summary>
/// <returns>
/// A string array containing the names of all the roles stored in the data source for the configured applicationName.
/// </returns>
public override string[] GetAllRoles() {
ArrayList roles = new ArrayList();
foreach (MemberGroup mg in MemberGroup.GetAll)
roles.Add(mg.Text);
return (string[])roles.ToArray(typeof(string));
}
/// <summary>
/// Gets a list of the roles that a specified user is in for the configured applicationName.
/// </summary>
/// <param name="username">The user to return a list of roles for.</param>
/// <returns>
/// A string array containing the names of all the roles that the specified user is in for the configured applicationName.
/// </returns>
public override string[] GetRolesForUser(string username) {
ArrayList roles = new ArrayList();
Member m = Member.GetMemberFromLoginName(username);
if (m != null) {
IDictionaryEnumerator ide = m.Groups.GetEnumerator();
while (ide.MoveNext())
roles.Add(((MemberGroup)ide.Value).Text);
return (string[])roles.ToArray(typeof(string));
} else
throw new ProviderException(String.Format("No member with username '{0}' exists", username));
}
/// <summary>
/// Gets a list of users in the specified role for the configured applicationName.
/// </summary>
/// <param name="roleName">The name of the role to get the list of users for.</param>
/// <returns>
/// A string array containing the names of all the users who are members of the specified role for the configured applicationName.
/// </returns>
public override string[] GetUsersInRole(string roleName) {
ArrayList members = new ArrayList();
MemberGroup group = MemberGroup.GetByName(roleName);
if (group == null)
throw new ProviderException(String.Format("No role with name '{0}' exists", roleName));
else {
foreach (Member m in group.GetMembers())
members.Add(m.LoginName);
return (string[])members.ToArray(typeof(string));
}
}
/// <summary>
/// Gets a value indicating whether the specified user is in the specified role for the configured applicationName.
/// </summary>
/// <param name="username">The user name to search for.</param>
/// <param name="roleName">The role to search in.</param>
/// <returns>
/// true if the specified user is in the specified role for the configured applicationName; otherwise, false.
/// </returns>
public override bool IsUserInRole(string username, string roleName) {
Member m = Member.GetMemberFromLoginName(username);
if (m == null)
throw new ProviderException(String.Format("No user with name '{0}' exists", username));
else {
MemberGroup mg = MemberGroup.GetByName(roleName);
if (mg == null)
throw new ProviderException(String.Format("No Membergroup with name '{0}' exists", roleName));
else
return mg.HasMember(m.Id);
}
}
/// <summary>
/// Removes the specified user names from the specified roles for the configured applicationName.
/// </summary>
/// <param name="usernames">A string array of user names to be removed from the specified roles.</param>
/// <param name="roleNames">A string array of role names to remove the specified user names from.</param>
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) {
ArrayList roles = new ArrayList();
foreach (string role in roleNames)
try {
roles.Add(MemberGroup.GetByName(role).Id);
} catch {
throw new ProviderException(String.Format("No role with name '{0}' exists", role));
}
foreach (string username in usernames) {
Member m = Member.GetMemberFromLoginName(username);
foreach (int roleId in roles)
m.RemoveGroup(roleId);
}
}
/// <summary>
/// Gets a value indicating whether the specified role name already exists in the role data source for the configured applicationName.
/// </summary>
/// <param name="roleName">The name of the role to search for in the data source.</param>
/// <returns>
/// true if the role name already exists in the data source for the configured applicationName; otherwise, false.
/// </returns>
public override bool RoleExists(string roleName) {
MemberGroup mg = MemberGroup.GetByName(roleName);
return mg != null;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GitVersion;
using GitVersion.Extensions;
using GitVersion.Logging;
using GitVersion.OutputVariables;
using GitVersion.VersionCalculation;
using GitVersion.VersionConverters.AssemblyInfo;
using GitVersionCore.Tests.Helpers;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace GitVersionCore.Tests
{
[TestFixture]
[Parallelizable(ParallelScope.None)]
public class AssemblyInfoFileUpdaterTests : TestBase
{
private IVariableProvider variableProvider;
private ILog log;
private IFileSystem fileSystem;
[SetUp]
public void Setup()
{
ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute<TestCaseAttribute>();
var sp = ConfigureServices();
log = sp.GetService<ILog>();
fileSystem = sp.GetService<IFileSystem>();
variableProvider = sp.GetService<IVariableProvider>();
}
[TestCase("cs")]
[TestCase("fs")]
[TestCase("vb")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void ShouldCreateAssemblyInfoFileWhenNotExistsAndEnsureAssemblyInfo(string fileExtension)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "VersionAssemblyInfo." + fileExtension;
var fullPath = Path.Combine(workingDir, assemblyInfoFile);
var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false);
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, true, assemblyInfoFile));
fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension)));
}
[TestCase("cs")]
[TestCase("fs")]
[TestCase("vb")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void ShouldCreateAssemblyInfoFileAtPathWhenNotExistsAndEnsureAssemblyInfo(string fileExtension)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = Path.Combine("src", "Project", "Properties", "VersionAssemblyInfo." + fileExtension);
var fullPath = Path.Combine(workingDir, assemblyInfoFile);
var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false);
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, true, assemblyInfoFile));
fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension)));
}
[TestCase("cs")]
[TestCase("fs")]
[TestCase("vb")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void ShouldCreateAssemblyInfoFilesAtPathWhenNotExistsAndEnsureAssemblyInfo(string fileExtension)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFiles = new HashSet<string>
{
"AssemblyInfo." + fileExtension,
Path.Combine("src", "Project", "Properties", "VersionAssemblyInfo." + fileExtension)
};
var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false);
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, true, assemblyInfoFiles.ToArray()));
foreach (var item in assemblyInfoFiles)
{
var fullPath = Path.Combine(workingDir, item);
fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension)));
}
}
[TestCase("cs")]
[TestCase("fs")]
[TestCase("vb")]
public void ShouldNotCreateAssemblyInfoFileWhenNotExistsAndNotEnsureAssemblyInfo(string fileExtension)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "VersionAssemblyInfo." + fileExtension;
var fullPath = Path.Combine(workingDir, assemblyInfoFile);
var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false);
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
fileSystem.Exists(fullPath).ShouldBeFalse();
}
[Test]
public void ShouldNotCreateAssemblyInfoFileForUnknownSourceCodeAndEnsureAssemblyInfo()
{
fileSystem = Substitute.For<IFileSystem>();
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "VersionAssemblyInfo.js";
var fullPath = Path.Combine(workingDir, assemblyInfoFile);
var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false);
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, true, assemblyInfoFile));
fileSystem.Received(0).WriteAllText(fullPath, Arg.Any<string>());
}
[Test]
public void ShouldStartSearchFromWorkingDirectory()
{
fileSystem = Substitute.For<IFileSystem>();
var workingDir = Path.GetTempPath();
var assemblyInfoFiles = Array.Empty<string>();
var variables = variableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false);
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fileSystem);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFiles.ToArray()));
fileSystem.Received().DirectoryEnumerateFiles(Arg.Is(workingDir), Arg.Any<string>(), Arg.Any<SearchOption>());
}
[TestCase("cs", "[assembly: AssemblyVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyInformationalVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]")]
[TestCase("fs", "[<assembly: AssemblyVersion(\"1.0.0.0\")>]\r\n[<assembly: AssemblyInformationalVersion(\"1.0.0.0\")>]\r\n[<assembly: AssemblyFileVersion(\"1.0.0.0\")>]")]
[TestCase("vb", "<Assembly: AssemblyVersion(\"1.0.0.0\")>\r\n<Assembly: AssemblyInformationalVersion(\"1.0.0.0\")>\r\n<Assembly: AssemblyFileVersion(\"1.0.0.0\")>")]
public void ShouldReplaceAssemblyVersion(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "AssemblyInfo." + fileExtension;
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
fs.Received().WriteAllText(fileName, Arg.Is<string>(s =>
s.Contains(@"AssemblyVersion(""2.3.0.0"")") &&
s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") &&
s.Contains(@"AssemblyFileVersion(""2.3.1.0"")")));
});
}
[TestCase("cs", "[assembly: AssemblyFileVersion(\"1.0.0.0\")]")]
[TestCase("fs", "[<assembly: AssemblyFileVersion(\"1.0.0.0\")>]")]
[TestCase("vb", "<Assembly: AssemblyFileVersion(\"1.0.0.0\")>")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void ShouldNotReplaceAssemblyVersionWhenVersionSchemeIsNone(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "AssemblyInfo." + fileExtension;
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.None, verify: (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
assemblyFileContent = fs.ReadAllText(fileName);
assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension)));
});
}
[TestCase("cs", "[assembly: AssemblyVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyInformationalVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]")]
[TestCase("fs", "[<assembly: AssemblyVersion(\"1.0.0.0\")>]\r\n[<assembly: AssemblyInformationalVersion(\"1.0.0.0\")>]\r\n[<assembly: AssemblyFileVersion(\"1.0.0.0\")>]")]
[TestCase("vb", "<Assembly: AssemblyVersion(\"1.0.0.0\")>\r\n<Assembly: AssemblyInformationalVersion(\"1.0.0.0\")>\r\n<Assembly: AssemblyFileVersion(\"1.0.0.0\")>")]
public void ShouldReplaceAssemblyVersionInRelativePath(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = Path.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension);
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
fs.Received().WriteAllText(fileName, Arg.Is<string>(s =>
s.Contains(@"AssemblyVersion(""2.3.0.0"")") &&
s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") &&
s.Contains(@"AssemblyFileVersion(""2.3.1.0"")")));
});
}
[TestCase("cs", "[assembly: AssemblyVersion ( \"1.0.0.0\") ]\r\n[assembly: AssemblyInformationalVersion\t(\t\"1.0.0.0\"\t)]\r\n[assembly: AssemblyFileVersion\r\n(\r\n\"1.0.0.0\"\r\n)]")]
[TestCase("fs", "[<assembly: AssemblyVersion ( \"1.0.0.0\" )>]\r\n[<assembly: AssemblyInformationalVersion\t(\t\"1.0.0.0\"\t)>]\r\n[<assembly: AssemblyFileVersion\r\n(\r\n\"1.0.0.0\"\r\n)>]")]
[TestCase("vb", "<Assembly: AssemblyVersion ( \"1.0.0.0\" )>\r\n<Assembly: AssemblyInformationalVersion\t(\t\"1.0.0.0\"\t)>\r\n<Assembly: AssemblyFileVersion\r\n(\r\n\"1.0.0.0\"\r\n)>")]
public void ShouldReplaceAssemblyVersionInRelativePathWithWhiteSpace(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = Path.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension);
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
fs.Received().WriteAllText(fileName, Arg.Is<string>(s =>
s.Contains(@"AssemblyVersion(""2.3.0.0"")") &&
s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") &&
s.Contains(@"AssemblyFileVersion(""2.3.1.0"")")));
});
}
[TestCase("cs", "[assembly: AssemblyVersion(\"1.0.0.*\")]\r\n[assembly: AssemblyInformationalVersion(\"1.0.0.*\")]\r\n[assembly: AssemblyFileVersion(\"1.0.0.*\")]")]
[TestCase("fs", "[<assembly: AssemblyVersion(\"1.0.0.*\")>]\r\n[<assembly: AssemblyInformationalVersion(\"1.0.0.*\")>]\r\n[<assembly: AssemblyFileVersion(\"1.0.0.*\")>]")]
[TestCase("vb", "<Assembly: AssemblyVersion(\"1.0.0.*\")>\r\n<Assembly: AssemblyInformationalVersion(\"1.0.0.*\")>\r\n<Assembly: AssemblyFileVersion(\"1.0.0.*\")>")]
public void ShouldReplaceAssemblyVersionWithStar(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "AssemblyInfo." + fileExtension;
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
fs.Received().WriteAllText(fileName, Arg.Is<string>(s =>
s.Contains(@"AssemblyVersion(""2.3.0.0"")") &&
s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") &&
s.Contains(@"AssemblyFileVersion(""2.3.1.0"")")));
});
}
[TestCase("cs", "[assembly: AssemblyVersionAttribute(\"1.0.0.0\")]\r\n[assembly: AssemblyInformationalVersionAttribute(\"1.0.0.0\")]\r\n[assembly: AssemblyFileVersionAttribute(\"1.0.0.0\")]")]
[TestCase("fs", "[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\n[<assembly: AssemblyInformationalVersionAttribute(\"1.0.0.0\")>]\r\n[<assembly: AssemblyFileVersionAttribute(\"1.0.0.0\")>]")]
[TestCase("vb", "<Assembly: AssemblyVersionAttribute(\"1.0.0.0\")>\r\n<Assembly: AssemblyInformationalVersionAttribute(\"1.0.0.0\")>\r\n<Assembly: AssemblyFileVersionAttribute(\"1.0.0.0\")>")]
public void ShouldReplaceAssemblyVersionWithAtttributeSuffix(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "AssemblyInfo." + fileExtension;
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
fs.Received().WriteAllText(fileName, Arg.Is<string>(s =>
!s.Contains(@"AssemblyVersionAttribute(""1.0.0.0"")") &&
!s.Contains(@"AssemblyInformationalVersionAttribute(""1.0.0.0"")") &&
!s.Contains(@"AssemblyFileVersionAttribute(""1.0.0.0"")") &&
s.Contains(@"AssemblyVersion(""2.3.1.0"")") &&
s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") &&
s.Contains(@"AssemblyFileVersion(""2.3.1.0"")")));
});
}
[TestCase("cs")]
[TestCase("fs")]
[TestCase("vb")]
public void ShouldAddAssemblyVersionIfMissingFromInfoFile(string fileExtension)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "AssemblyInfo." + fileExtension;
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile("", fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
fs.Received().WriteAllText(fileName, Arg.Is<string>(s =>
s.Contains(@"AssemblyVersion(""2.3.0.0"")") &&
s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") &&
s.Contains(@"AssemblyFileVersion(""2.3.1.0"")")));
});
}
[TestCase("cs", "[assembly: AssemblyVersion(\"2.2.0.0\")]\r\n[assembly: AssemblyInformationalVersion(\"2.2.0+5.Branch.foo.Sha.hash\")]\r\n[assembly: AssemblyFileVersion(\"2.2.0.0\")]")]
[TestCase("fs", "[<assembly: AssemblyVersion(\"2.2.0.0\")>]\r\n[<assembly: AssemblyInformationalVersion(\"2.2.0+5.Branch.foo.Sha.hash\")>]\r\n[<assembly: AssemblyFileVersion(\"2.2.0.0\")>]")]
[TestCase("vb", "<Assembly: AssemblyVersion(\"2.2.0.0\")>\r\n<Assembly: AssemblyInformationalVersion(\"2.2.0+5.Branch.foo.Sha.hash\")>\r\n<Assembly: AssemblyFileVersion(\"2.2.0.0\")>")]
public void ShouldReplaceAlreadySubstitutedValues(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "AssemblyInfo." + fileExtension;
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
fs.Received().WriteAllText(fileName, Arg.Is<string>(s =>
s.Contains(@"AssemblyVersion(""2.3.0.0"")") &&
s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") &&
s.Contains(@"AssemblyFileVersion(""2.3.1.0"")")));
});
}
[TestCase("cs", "[assembly: AssemblyVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyInformationalVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]")]
[TestCase("fs", "[<assembly: AssemblyVersion(\"1.0.0.0\")>]\r\n[<assembly: AssemblyInformationalVersion(\"1.0.0.0\")>]\r\n[<assembly: AssemblyFileVersion(\"1.0.0.0\")>]")]
[TestCase("vb", "<Assembly: AssemblyVersion(\"1.0.0.0\")>\r\n<Assembly: AssemblyInformationalVersion(\"1.0.0.0\")>\r\n<Assembly: AssemblyFileVersion(\"1.0.0.0\")>")]
public void ShouldReplaceAssemblyVersionWhenCreatingAssemblyVersionFileAndEnsureAssemblyInfo(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "AssemblyInfo." + fileExtension;
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
fs.Received().WriteAllText(fileName, Arg.Is<string>(s =>
s.Contains(@"AssemblyVersion(""2.3.1.0"")") &&
s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") &&
s.Contains(@"AssemblyFileVersion(""2.3.1.0"")")));
});
}
[TestCase("cs", "[assembly: AssemblyVersion (AssemblyInfo.Version) ]\r\n[assembly: AssemblyInformationalVersion(AssemblyInfo.InformationalVersion)]\r\n[assembly: AssemblyFileVersion(AssemblyInfo.FileVersion)]")]
[TestCase("fs", "[<assembly: AssemblyVersion (AssemblyInfo.Version)>]\r\n[<assembly: AssemblyInformationalVersion(AssemblyInfo.InformationalVersion)>]\r\n[<assembly: AssemblyFileVersion(AssemblyInfo.FileVersion)>]")]
[TestCase("vb", "<Assembly: AssemblyVersion (AssemblyInfo.Version)>\r\n<Assembly: AssemblyInformationalVersion(AssemblyInfo.InformationalVersion)>\r\n<Assembly: AssemblyFileVersion(AssemblyInfo.FileVersion)>")]
public void ShouldReplaceAssemblyVersionInRelativePathWithVariables(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = Path.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension);
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
fs.Received().WriteAllText(fileName, Arg.Is<string>(s =>
s.Contains(@"AssemblyVersion(""2.3.0.0"")") &&
s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") &&
s.Contains(@"AssemblyFileVersion(""2.3.1.0"")")));
});
}
[TestCase("cs", "[assembly: AssemblyVersion ( AssemblyInfo.VersionInfo ) ]\r\n[assembly: AssemblyInformationalVersion\t(\tAssemblyInfo.InformationalVersion\t)]\r\n[assembly: AssemblyFileVersion\r\n(\r\nAssemblyInfo.FileVersion\r\n)]")]
[TestCase("fs", "[<assembly: AssemblyVersion ( AssemblyInfo.VersionInfo )>]\r\n[<assembly: AssemblyInformationalVersion\t(\tAssemblyInfo.InformationalVersion\t)>]\r\n[<assembly: AssemblyFileVersion\r\n(\r\nAssemblyInfo.FileVersion\r\n)>]")]
[TestCase("vb", "<Assembly: AssemblyVersion ( AssemblyInfo.VersionInfo )>\r\n<Assembly: AssemblyInformationalVersion\t(\tAssemblyInfo.InformationalVersion\t)>\r\n<Assembly: AssemblyFileVersion\r\n(\r\nAssemblyInfo.FileVersion\r\n)>")]
public void ShouldReplaceAssemblyVersionInRelativePathWithVariablesAndWhiteSpace(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = Path.Combine("Project", "src", "Properties", "AssemblyInfo." + fileExtension);
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.MajorMinor, (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
fs.Received().WriteAllText(fileName, Arg.Is<string>(s =>
s.Contains(@"AssemblyVersion(""2.3.0.0"")") &&
s.Contains(@"AssemblyInformationalVersion(""2.3.1+3.Branch.foo.Sha.hash"")") &&
s.Contains(@"AssemblyFileVersion(""2.3.1.0"")")));
});
}
[TestCase("cs", "[assembly: AssemblyVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]")]
[TestCase("fs", "[<assembly: AssemblyVersion(\"1.0.0.0\")>]\r\n[<assembly: AssemblyFileVersion(\"1.0.0.0\")>]")]
[TestCase("vb", "<Assembly: AssemblyVersion(\"1.0.0.0\")>\r\n<Assembly: AssemblyFileVersion(\"1.0.0.0\")>")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void ShouldAddAssemblyInformationalVersionWhenUpdatingAssemblyVersionFile(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "AssemblyInfo." + fileExtension;
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
assemblyFileContent = fs.ReadAllText(fileName);
assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension)));
});
}
[TestCase("cs", "[assembly: AssemblyVersion(\"1.0.0.0\")]\r\n[assembly: AssemblyFileVersion(\"1.0.0.0\")]\r\n// comment\r\n")]
[TestCase("fs", "[<assembly: AssemblyVersion(\"1.0.0.0\")>]\r\n[<assembly: AssemblyFileVersion(\"1.0.0.0\")>]\r\ndo\r\n()\r\n")]
[TestCase("vb", "<Assembly: AssemblyVersion(\"1.0.0.0\")>\r\n<Assembly: AssemblyFileVersion(\"1.0.0.0\")>\r\n' comment\r\n")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void Issue1183ShouldAddFSharpAssemblyInformationalVersionBesideOtherAttributes(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "AssemblyInfo." + fileExtension;
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, verify: (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
assemblyFileContent = fs.ReadAllText(fileName);
assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension)));
});
}
[TestCase("cs", "[assembly: AssemblyFileVersion(\"1.0.0.0\")]")]
[TestCase("fs", "[<assembly: AssemblyFileVersion(\"1.0.0.0\")>]")]
[TestCase("vb", "<Assembly: AssemblyFileVersion(\"1.0.0.0\")>")]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void ShouldNotAddAssemblyInformationalVersionWhenVersionSchemeIsNone(string fileExtension, string assemblyFileContent)
{
var workingDir = Path.GetTempPath();
var assemblyInfoFile = "AssemblyInfo." + fileExtension;
var fileName = Path.Combine(workingDir, assemblyInfoFile);
VerifyAssemblyInfoFile(assemblyFileContent, fileName, AssemblyVersioningScheme.None, verify: (fs, variables) =>
{
using var assemblyInfoFileUpdater = new AssemblyInfoFileUpdater(log, fs);
assemblyInfoFileUpdater.Execute(variables, new AssemblyInfoContext(workingDir, false, assemblyInfoFile));
assemblyFileContent = fs.ReadAllText(fileName);
assemblyFileContent.ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension)));
});
}
private void VerifyAssemblyInfoFile(
string assemblyFileContent,
string fileName,
AssemblyVersioningScheme versioningScheme = AssemblyVersioningScheme.MajorMinorPatch,
Action<IFileSystem, VersionVariables> verify = null)
{
fileSystem = Substitute.For<IFileSystem>();
var version = new SemanticVersion
{
BuildMetaData = new SemanticVersionBuildMetaData("versionSourceHash", 3, "foo", "hash", "shortHash", DateTimeOffset.Now, 0),
Major = 2,
Minor = 3,
Patch = 1
};
fileSystem.Exists(fileName).Returns(true);
fileSystem.ReadAllText(fileName).Returns(assemblyFileContent);
fileSystem.When(f => f.WriteAllText(fileName, Arg.Any<string>())).Do(c =>
{
assemblyFileContent = c.ArgAt<string>(1);
fileSystem.ReadAllText(fileName).Returns(assemblyFileContent);
});
var config = new TestEffectiveConfiguration(assemblyVersioningScheme: versioningScheme);
var variables = variableProvider.GetVariablesFor(version, config, false);
verify?.Invoke(fileSystem, variables);
}
}
}
| |
using System;
using System.Globalization;
/// <summary>
/// System.Globalization.StringInfo.GetNextTestElement(string,int32)
/// </summary>
public class StringInfoGetNextTextElement2
{
private const int c_MINI_STRING_LENGTH = 8;
private const int c_MAX_STRING_LENGTH = 256;
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Get the text element from a random index in a string");
try
{
string str = TestLibrary.Generator.GetString(-55, true, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
int index = this.GetInt32(8, str.Length);
string result = StringInfo.GetNextTextElement(str, index);
if (result != str[index].ToString())
{
TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,the result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: The first element is a surrogate pair");
try
{
string str = "\uDBFF\uDFFF";
string result = StringInfo.GetNextTextElement("ef45-;\uDBFF\uDFFFabcde", 6);
if (result.Length != 2)
{
TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
retVal = false;
}
if (result != str)
{
TestLibrary.TestFramework.LogError("004", "The result is not the value as expected,the result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: The element is a combining character");
try
{
string str = "a\u20D1";
string result = StringInfo.GetNextTextElement("13229^a\u20D1abcde", 6);
if (result != str)
{
TestLibrary.TestFramework.LogError("006", "The result is not the value as expected,the result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("007", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: The element is a combination of base character and several combining characters");
try
{
string str = "z\uFE22\u20D1\u20EB";
string result = StringInfo.GetNextTextElement("az\uFE22\u20D1\u20EBabcde", 1);
if (result.Length != 4)
{
TestLibrary.TestFramework.LogError("008", "The result is not the value as expected,length is: " + result.Length);
retVal = false;
}
if (result != str)
{
TestLibrary.TestFramework.LogError("009", "The result is not the value as expected,the result is: " + result);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: The string is a null reference");
try
{
string str = null;
string result = StringInfo.GetNextTextElement(str, 0);
TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: The index is out of the range of the string");
try
{
string str = "abc";
string result = StringInfo.GetNextTextElement(str, -4);
TestLibrary.TestFramework.LogError("103", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: The index is a negative number");
try
{
string str = "df8%^dk";
string result = StringInfo.GetNextTextElement(str, -1);
TestLibrary.TestFramework.LogError("105", "The ArgumentOutOfRangeException was not thrown as expected");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
StringInfoGetNextTextElement2 test = new StringInfoGetNextTextElement2();
TestLibrary.TestFramework.BeginTestCase("StringInfoGetNextTextElement2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
}
| |
/*
* 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 System.Collections.Generic;
using System.Threading;
using Thrift.Collections;
using Thrift.Protocol;
using Thrift.Transport;
using Thrift.Test;
namespace Test
{
public class TestClient
{
private static int numIterations = 1;
private static string protocol = "";
public static bool Execute(string[] args)
{
try
{
string host = "localhost";
int port = 9090;
string url = null, pipe = null;
int numThreads = 1;
bool buffered = false, framed = false, encrypted = false;
string certPath = "../../../../../keys/server.pem";
try
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-u")
{
url = args[++i];
}
else if (args[i] == "-n")
{
numIterations = Convert.ToInt32(args[++i]);
}
else if (args[i] == "-pipe") // -pipe <name>
{
pipe = args[++i];
Console.WriteLine("Using named pipes transport");
}
else if (args[i].Contains("--host="))
{
host = args[i].Substring(args[i].IndexOf("=") + 1);
}
else if (args[i].Contains("--port="))
{
port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1));
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
buffered = true;
Console.WriteLine("Using buffered sockets");
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
framed = true;
Console.WriteLine("Using framed transport");
}
else if (args[i] == "-t")
{
numThreads = Convert.ToInt32(args[++i]);
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
protocol = "compact";
Console.WriteLine("Using compact protocol");
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
protocol = "json";
Console.WriteLine("Using JSON protocol");
}
else if (args[i] == "--ssl")
{
encrypted = true;
Console.WriteLine("Using encrypted transport");
}
else if (args[i].StartsWith("--cert="))
{
certPath = args[i].Substring("--cert=".Length);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
//issue tests on separate threads simultaneously
Thread[] threads = new Thread[numThreads];
DateTime start = DateTime.Now;
for (int test = 0; test < numThreads; test++)
{
Thread t = new Thread(new ParameterizedThreadStart(ClientThread));
threads[test] = t;
if (url == null)
{
// endpoint transport
TTransport trans = null;
if (pipe != null)
trans = new TNamedPipeClientTransport(pipe);
else
{
if (encrypted)
trans = new TTLSSocket(host, port, certPath);
else
trans = new TSocket(host, port);
}
// layered transport
if (buffered)
trans = new TBufferedTransport(trans as TStreamTransport);
if (framed)
trans = new TFramedTransport(trans);
//ensure proper open/close of transport
trans.Open();
trans.Close();
t.Start(trans);
}
else
{
THttpClient http = new THttpClient(new Uri(url));
t.Start(http);
}
}
for (int test = 0; test < numThreads; test++)
{
threads[test].Join();
}
Console.Write("Total time: " + (DateTime.Now - start));
}
catch (Exception outerEx)
{
Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
return false;
}
Console.WriteLine();
Console.WriteLine();
return true;
}
public static void ClientThread(object obj)
{
TTransport transport = (TTransport)obj;
for (int i = 0; i < numIterations; i++)
{
ClientTest(transport);
}
transport.Close();
}
public static string BytesToHex(byte[] data) {
return BitConverter.ToString(data).Replace("-", string.Empty);
}
public static byte[] PrepareTestData(bool randomDist)
{
byte[] retval = new byte[0x100];
int initLen = Math.Min(0x100,retval.Length);
// linear distribution, unless random is requested
if (!randomDist) {
for (var i = 0; i < initLen; ++i) {
retval[i] = (byte)i;
}
return retval;
}
// random distribution
for (var i = 0; i < initLen; ++i) {
retval[i] = (byte)0;
}
var rnd = new Random();
for (var i = 1; i < initLen; ++i) {
while( true) {
int nextPos = rnd.Next() % initLen;
if (retval[nextPos] == 0) {
retval[nextPos] = (byte)i;
break;
}
}
}
return retval;
}
public static void ClientTest(TTransport transport)
{
TProtocol proto;
if (protocol == "compact")
proto = new TCompactProtocol(transport);
else if (protocol == "json")
proto = new TJSONProtocol(transport);
else
proto = new TBinaryProtocol(transport);
ThriftTest.Client client = new ThriftTest.Client(proto);
try
{
if (!transport.IsOpen)
{
transport.Open();
}
}
catch (TTransportException ttx)
{
Console.WriteLine("Connect failed: " + ttx.Message);
return;
}
long start = DateTime.Now.ToFileTime();
Console.Write("testVoid()");
client.testVoid();
Console.WriteLine(" = void");
Console.Write("testString(\"Test\")");
string s = client.testString("Test");
Console.WriteLine(" = \"" + s + "\"");
Console.Write("testBool(true)");
bool t = client.testBool((bool)true);
Console.WriteLine(" = " + t);
Console.Write("testBool(false)");
bool f = client.testBool((bool)false);
Console.WriteLine(" = " + f);
Console.Write("testByte(1)");
sbyte i8 = client.testByte((sbyte)1);
Console.WriteLine(" = " + i8);
Console.Write("testI32(-1)");
int i32 = client.testI32(-1);
Console.WriteLine(" = " + i32);
Console.Write("testI64(-34359738368)");
long i64 = client.testI64(-34359738368);
Console.WriteLine(" = " + i64);
Console.Write("testDouble(5.325098235)");
double dub = client.testDouble(5.325098235);
Console.WriteLine(" = " + dub);
byte[] binOut = PrepareTestData(true);
Console.Write("testBinary(" + BytesToHex(binOut) + ")");
try
{
byte[] binIn = client.testBinary(binOut);
Console.WriteLine(" = " + BytesToHex(binIn));
if (binIn.Length != binOut.Length)
throw new Exception("testBinary: length mismatch");
for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs)
if (binIn[ofs] != binOut[ofs])
throw new Exception("testBinary: content mismatch at offset " + ofs.ToString());
}
catch (Thrift.TApplicationException e)
{
Console.Write("testBinary(" + BytesToHex(binOut) + "): "+e.Message);
}
// binary equals? only with hashcode option enabled ...
if( typeof(CrazyNesting).GetMethod("Equals").DeclaringType == typeof(CrazyNesting))
{
CrazyNesting one = new CrazyNesting();
CrazyNesting two = new CrazyNesting();
one.String_field = "crazy";
two.String_field = "crazy";
one.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
if (!one.Equals(two))
throw new Exception("CrazyNesting.Equals failed");
}
Console.Write("testStruct({\"Zero\", 1, -3, -5})");
Xtruct o = new Xtruct();
o.String_thing = "Zero";
o.Byte_thing = (sbyte)1;
o.I32_thing = -3;
o.I64_thing = -5;
Xtruct i = client.testStruct(o);
Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}");
Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})");
Xtruct2 o2 = new Xtruct2();
o2.Byte_thing = (sbyte)1;
o2.Struct_thing = o;
o2.I32_thing = 5;
Xtruct2 i2 = client.testNest(o2);
i = i2.Struct_thing;
Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}");
Dictionary<int, int> mapout = new Dictionary<int, int>();
for (int j = 0; j < 5; j++)
{
mapout[j] = j - 10;
}
Console.Write("testMap({");
bool first = true;
foreach (int key in mapout.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapout[key]);
}
Console.Write("})");
Dictionary<int, int> mapin = client.testMap(mapout);
Console.Write(" = {");
first = true;
foreach (int key in mapin.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapin[key]);
}
Console.WriteLine("}");
List<int> listout = new List<int>();
for (int j = -2; j < 3; j++)
{
listout.Add(j);
}
Console.Write("testList({");
first = true;
foreach (int j in listout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
List<int> listin = client.testList(listout);
Console.Write(" = {");
first = true;
foreach (int j in listin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
//set
THashSet<int> setout = new THashSet<int>();
for (int j = -2; j < 3; j++)
{
setout.Add(j);
}
Console.Write("testSet({");
first = true;
foreach (int j in setout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
THashSet<int> setin = client.testSet(setout);
Console.Write(" = {");
first = true;
foreach (int j in setin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
Console.Write("testEnum(ONE)");
Numberz ret = client.testEnum(Numberz.ONE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(TWO)");
ret = client.testEnum(Numberz.TWO);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(THREE)");
ret = client.testEnum(Numberz.THREE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(FIVE)");
ret = client.testEnum(Numberz.FIVE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(EIGHT)");
ret = client.testEnum(Numberz.EIGHT);
Console.WriteLine(" = " + ret);
Console.Write("testTypedef(309858235082523)");
long uid = client.testTypedef(309858235082523L);
Console.WriteLine(" = " + uid);
Console.Write("testMapMap(1)");
Dictionary<int, Dictionary<int, int>> mm = client.testMapMap(1);
Console.Write(" = {");
foreach (int key in mm.Keys)
{
Console.Write(key + " => {");
Dictionary<int, int> m2 = mm[key];
foreach (int k2 in m2.Keys)
{
Console.Write(k2 + " => " + m2[k2] + ", ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
Insanity insane = new Insanity();
insane.UserMap = new Dictionary<Numberz, long>();
insane.UserMap[Numberz.FIVE] = 5000L;
Xtruct truck = new Xtruct();
truck.String_thing = "Truck";
truck.Byte_thing = (sbyte)8;
truck.I32_thing = 8;
truck.I64_thing = 8;
insane.Xtructs = new List<Xtruct>();
insane.Xtructs.Add(truck);
Console.Write("testInsanity()");
Dictionary<long, Dictionary<Numberz, Insanity>> whoa = client.testInsanity(insane);
Console.Write(" = {");
foreach (long key in whoa.Keys)
{
Dictionary<Numberz, Insanity> val = whoa[key];
Console.Write(key + " => {");
foreach (Numberz k2 in val.Keys)
{
Insanity v2 = val[k2];
Console.Write(k2 + " => {");
Dictionary<Numberz, long> userMap = v2.UserMap;
Console.Write("{");
if (userMap != null)
{
foreach (Numberz k3 in userMap.Keys)
{
Console.Write(k3 + " => " + userMap[k3] + ", ");
}
}
else
{
Console.Write("null");
}
Console.Write("}, ");
List<Xtruct> xtructs = v2.Xtructs;
Console.Write("{");
if (xtructs != null)
{
foreach (Xtruct x in xtructs)
{
Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, ");
}
}
else
{
Console.Write("null");
}
Console.Write("}");
Console.Write("}, ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
sbyte arg0 = 1;
int arg1 = 2;
long arg2 = long.MaxValue;
Dictionary<short, string> multiDict = new Dictionary<short, string>();
multiDict[1] = "one";
Numberz arg4 = Numberz.FIVE;
long arg5 = 5000000;
Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + "," + multiDict + "," + arg4 + "," + arg5 + ")");
Xtruct multiResponse = client.testMulti(arg0, arg1, arg2, multiDict, arg4, arg5);
Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing
+ ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n");
Console.WriteLine("Test Oneway(1)");
client.testOneway(1);
Console.Write("Test Calltime()");
var startt = DateTime.UtcNow;
for ( int k=0; k<1000; ++k )
client.testVoid();
Console.WriteLine(" = " + (DateTime.UtcNow - startt).TotalSeconds.ToString() + " ms a testVoid() call" );
}
}
}
| |
namespace XenAdmin.Dialogs
{
partial class RoleElevationDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RoleElevationDialog));
this.labelBlurb = new System.Windows.Forms.Label();
this.buttonCancel = new System.Windows.Forms.Button();
this.labelCurrentRoleValue = new System.Windows.Forms.Label();
this.labelCurrentRole = new System.Windows.Forms.Label();
this.labelCurrentUserValue = new System.Windows.Forms.Label();
this.labelCurrentUser = new System.Windows.Forms.Label();
this.labelRequiredRole = new System.Windows.Forms.Label();
this.labelRequiredRoleValue = new System.Windows.Forms.Label();
this.TextBoxUsername = new System.Windows.Forms.TextBox();
this.labelPassword = new System.Windows.Forms.Label();
this.labelUserName = new System.Windows.Forms.Label();
this.buttonAuthorize = new System.Windows.Forms.Button();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.labelCurrentAction = new System.Windows.Forms.Label();
this.labelCurrentActionValue = new System.Windows.Forms.Label();
this.labelServer = new System.Windows.Forms.Label();
this.labelServerValue = new System.Windows.Forms.Label();
this.divider = new System.Windows.Forms.GroupBox();
this.labelBlurb2 = new System.Windows.Forms.Label();
this.TextBoxPassword = new System.Windows.Forms.TextBox();
this.panel1 = new System.Windows.Forms.Panel();
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// labelBlurb
//
resources.ApplyResources(this.labelBlurb, "labelBlurb");
this.tableLayoutPanel1.SetColumnSpan(this.labelBlurb, 2);
this.labelBlurb.Name = "labelBlurb";
//
// buttonCancel
//
resources.ApplyResources(this.buttonCancel, "buttonCancel");
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// labelCurrentRoleValue
//
resources.ApplyResources(this.labelCurrentRoleValue, "labelCurrentRoleValue");
this.labelCurrentRoleValue.Name = "labelCurrentRoleValue";
//
// labelCurrentRole
//
resources.ApplyResources(this.labelCurrentRole, "labelCurrentRole");
this.labelCurrentRole.Name = "labelCurrentRole";
//
// labelCurrentUserValue
//
resources.ApplyResources(this.labelCurrentUserValue, "labelCurrentUserValue");
this.labelCurrentUserValue.Name = "labelCurrentUserValue";
//
// labelCurrentUser
//
resources.ApplyResources(this.labelCurrentUser, "labelCurrentUser");
this.labelCurrentUser.Name = "labelCurrentUser";
//
// labelRequiredRole
//
resources.ApplyResources(this.labelRequiredRole, "labelRequiredRole");
this.labelRequiredRole.Name = "labelRequiredRole";
//
// labelRequiredRoleValue
//
resources.ApplyResources(this.labelRequiredRoleValue, "labelRequiredRoleValue");
this.labelRequiredRoleValue.Name = "labelRequiredRoleValue";
//
// TextBoxUsername
//
resources.ApplyResources(this.TextBoxUsername, "TextBoxUsername");
this.TextBoxUsername.Name = "TextBoxUsername";
this.TextBoxUsername.TextChanged += new System.EventHandler(this.TextBoxUsername_TextChanged);
//
// labelPassword
//
resources.ApplyResources(this.labelPassword, "labelPassword");
this.labelPassword.Name = "labelPassword";
//
// labelUserName
//
resources.ApplyResources(this.labelUserName, "labelUserName");
this.labelUserName.Name = "labelUserName";
//
// buttonAuthorize
//
resources.ApplyResources(this.buttonAuthorize, "buttonAuthorize");
this.buttonAuthorize.Name = "buttonAuthorize";
this.buttonAuthorize.UseVisualStyleBackColor = true;
this.buttonAuthorize.Click += new System.EventHandler(this.buttonAuthorize_Click);
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.pictureBox1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.labelBlurb, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentAction, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentActionValue, 2, 1);
this.tableLayoutPanel1.Controls.Add(this.labelServer, 1, 2);
this.tableLayoutPanel1.Controls.Add(this.labelServerValue, 2, 2);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentUser, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentUserValue, 2, 3);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentRole, 1, 4);
this.tableLayoutPanel1.Controls.Add(this.labelCurrentRoleValue, 2, 4);
this.tableLayoutPanel1.Controls.Add(this.divider, 1, 5);
this.tableLayoutPanel1.Controls.Add(this.labelBlurb2, 1, 6);
this.tableLayoutPanel1.Controls.Add(this.labelRequiredRole, 1, 7);
this.tableLayoutPanel1.Controls.Add(this.labelRequiredRoleValue, 3, 7);
this.tableLayoutPanel1.Controls.Add(this.labelUserName, 1, 8);
this.tableLayoutPanel1.Controls.Add(this.TextBoxUsername, 2, 8);
this.tableLayoutPanel1.Controls.Add(this.labelPassword, 1, 9);
this.tableLayoutPanel1.Controls.Add(this.TextBoxPassword, 2, 9);
this.tableLayoutPanel1.Controls.Add(this.panel1, 2, 10);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// pictureBox1
//
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Image = global::XenAdmin.Properties.Resources._000_WarningAlert_h32bit_32;
this.pictureBox1.Name = "pictureBox1";
this.tableLayoutPanel1.SetRowSpan(this.pictureBox1, 2);
this.pictureBox1.TabStop = false;
//
// labelCurrentAction
//
resources.ApplyResources(this.labelCurrentAction, "labelCurrentAction");
this.labelCurrentAction.Name = "labelCurrentAction";
//
// labelCurrentActionValue
//
resources.ApplyResources(this.labelCurrentActionValue, "labelCurrentActionValue");
this.labelCurrentActionValue.Name = "labelCurrentActionValue";
//
// labelServer
//
resources.ApplyResources(this.labelServer, "labelServer");
this.labelServer.Name = "labelServer";
//
// labelServerValue
//
resources.ApplyResources(this.labelServerValue, "labelServerValue");
this.labelServerValue.Name = "labelServerValue";
//
// divider
//
this.tableLayoutPanel1.SetColumnSpan(this.divider, 2);
resources.ApplyResources(this.divider, "divider");
this.divider.Name = "divider";
this.divider.TabStop = false;
//
// labelBlurb2
//
resources.ApplyResources(this.labelBlurb2, "labelBlurb2");
this.tableLayoutPanel1.SetColumnSpan(this.labelBlurb2, 2);
this.labelBlurb2.Name = "labelBlurb2";
//
// TextBoxPassword
//
resources.ApplyResources(this.TextBoxPassword, "TextBoxPassword");
this.TextBoxPassword.Name = "TextBoxPassword";
this.TextBoxPassword.UseSystemPasswordChar = true;
this.TextBoxPassword.TextChanged += new System.EventHandler(this.TextBoxPassword_TextChanged);
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Controls.Add(this.buttonCancel);
this.panel1.Controls.Add(this.buttonAuthorize);
this.panel1.Name = "panel1";
//
// RoleElevationDialog
//
this.AcceptButton = this.buttonAuthorize;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.buttonCancel;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "RoleElevationDialog";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label labelBlurb;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Label labelCurrentRoleValue;
private System.Windows.Forms.Label labelCurrentRole;
private System.Windows.Forms.Label labelCurrentUserValue;
private System.Windows.Forms.Label labelCurrentUser;
private System.Windows.Forms.Label labelRequiredRole;
private System.Windows.Forms.Label labelRequiredRoleValue;
private System.Windows.Forms.TextBox TextBoxUsername;
private System.Windows.Forms.Label labelPassword;
private System.Windows.Forms.Label labelUserName;
private System.Windows.Forms.Button buttonAuthorize;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.TextBox TextBoxPassword;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label labelBlurb2;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.GroupBox divider;
private System.Windows.Forms.Label labelCurrentActionValue;
private System.Windows.Forms.Label labelCurrentAction;
private System.Windows.Forms.Label labelServer;
private System.Windows.Forms.Label labelServerValue;
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Element = Autodesk.Revit.DB.Element;
using GElement = Autodesk.Revit.DB.GeometryElement;
namespace Revit.SDK.Samples.WindowWizard.CS
{
/// <summary>
/// A object to help locating with geometry data.
/// </summary>
public class GeoHelper
{
/// <summary>
/// store the const precision
/// </summary>
private const double Precision = 0.0001;
/// <summary>
/// The method is used to get the wall face along the specified parameters
/// </summary>
/// <param name="wall">the wall</param>
/// <param name="view">the options view</param>
/// <param name="ExtOrInt">if true indicate that get exterior wall face, else false get the interior wall face</param>
/// <returns>the face</returns>
static public Face GetWallFace(Wall wall, View view, bool ExtOrInt)
{
FaceArray faces = null;
Face face = null;
Options options = new Options();
options.ComputeReferences = true;
options.View = view;
if (wall != null)
{
GeometryObjectArray geoArr = wall.get_Geometry(options).Objects;
foreach (GeometryObject geoObj in geoArr)
{
if (geoObj is Solid)
{
Solid s = geoObj as Solid;
faces = s.Faces;
}
}
}
if (ExtOrInt)
face = GetExteriorFace(faces);
else
face = GetInteriorFace(faces);
return face;
}
/// <summary>
/// The method is used to get extrusion's face along to the specified parameters
/// </summary>
/// <param name="extrusion">the extrusion</param>
/// <param name="view">options view</param>
/// <param name="ExtOrInt">If true indicate getting exterior extrusion face, else getting interior extrusion face</param>
/// <returns>the face</returns>
static public Face GetExtrusionFace(Extrusion extrusion, View view, bool ExtOrInt)
{
Face face = null;
FaceArray faces = null;
if (extrusion.IsSolid)
{
Options options = new Options();
options.ComputeReferences = true;
options.View = view;
GeometryObjectArray geoArr = extrusion.get_Geometry(options).Objects;
foreach (GeometryObject geoObj in geoArr)
{
if (geoObj is Solid)
{
Solid s = geoObj as Solid;
faces = s.Faces;
}
}
if (ExtOrInt)
face = GetExteriorFace(faces);
else
face = GetInteriorFace(faces);
}
return face;
}
/// <summary>
/// The assistant method is used for getting wall face and getting extrusion face
/// </summary>
/// <param name="faces">faces array</param>
/// <returns>the face</returns>
static private Face GetExteriorFace(FaceArray faces)
{
double elevation = 0;
double tempElevation = 0;
Mesh mesh = null;
Face face = null;
foreach (Face f in faces)
{
tempElevation = 0;
mesh = f.Triangulate();
foreach (Autodesk.Revit.DB.XYZ xyz in mesh.Vertices)
{
tempElevation = tempElevation + xyz.Y;
}
tempElevation = tempElevation / mesh.Vertices.Count;
if (elevation < tempElevation || null == face)
{
face = f;
elevation = tempElevation;
}
}
return face;
}
/// <summary>
/// The assistant method is used for getting wall face and getting extrusion face
/// </summary>
/// <param name="faces">faces array</param>
/// <returns>the face</returns>
static private Face GetInteriorFace(FaceArray faces)
{
double elevation = 0;
double tempElevation = 0;
Mesh mesh = null;
Face face = null;
foreach (Face f in faces)
{
tempElevation = 0;
mesh = f.Triangulate();
foreach (Autodesk.Revit.DB.XYZ xyz in mesh.Vertices)
{
tempElevation = tempElevation + xyz.Y;
}
tempElevation = tempElevation / mesh.Vertices.Count;
if (elevation > tempElevation || null == face)
{
face = f;
elevation = tempElevation;
}
}
return face;
}
/// <summary>
/// Find out the three points which made of a plane.
/// </summary>
/// <param name="mesh">A mesh contains many points.</param>
/// <param name="startPoint">Create a new instance of ReferencePlane.</param>
/// <param name="endPoint">The free end apply to reference plane.</param>
/// <param name="thirdPnt">A third point needed to define the reference plane.</param>
static public void Distribute(Mesh mesh, ref Autodesk.Revit.DB.XYZ startPoint, ref Autodesk.Revit.DB.XYZ endPoint, ref Autodesk.Revit.DB.XYZ thirdPnt)
{
int count = mesh.Vertices.Count;
startPoint = mesh.Vertices[0];
endPoint = mesh.Vertices[(int)(count / 3)];
thirdPnt = mesh.Vertices[(int)(count / 3 * 2)];
}
/// <summary>
/// Determines whether a edge is vertical.
/// </summary>
/// <param name="edge">The edge to be determined.</param>
/// <returns>Return true if this edge is vertical, or else return false.</returns>
static public bool IsVerticalEdge(Edge edge)
{
List<XYZ> polyline = edge.Tessellate() as List<XYZ>;
Autodesk.Revit.DB.XYZ verticalVct = new Autodesk.Revit.DB.XYZ (0, 0, 1);
Autodesk.Revit.DB.XYZ pointBuffer = polyline[0];
for (int i = 1; i < polyline.Count; i = i + 1)
{
Autodesk.Revit.DB.XYZ temp = polyline[i];
Autodesk.Revit.DB.XYZ vector = GetVector(pointBuffer, temp);
if (Equal(vector, verticalVct))
{
return true;
}
else
{
continue;
}
}
return false;
}
/// <summary>
/// Get the vector between two points.
/// </summary>
/// <param name="startPoint">The start point.</param>
/// <param name="endPoint">The end point.</param>
/// <returns>The vector between two points.</returns>
static public Autodesk.Revit.DB.XYZ GetVector(Autodesk.Revit.DB.XYZ startPoint, Autodesk.Revit.DB.XYZ endPoint)
{
return new Autodesk.Revit.DB.XYZ (endPoint.X - startPoint.X,
endPoint.Y - startPoint.Y, endPoint.Z - startPoint.Z);
}
/// <summary>
/// Determines whether two vector are equal in x and y axis.
/// </summary>
/// <param name="vectorA">The vector A.</param>
/// <param name="vectorB">The vector B.</param>
/// <returns>Return true if two vector are equals, or else return false.</returns>
static public bool Equal(Autodesk.Revit.DB.XYZ vectorA, Autodesk.Revit.DB.XYZ vectorB)
{
bool isNotEqual = (Precision < Math.Abs(vectorA.X - vectorB.X)) ||
(Precision < Math.Abs(vectorA.Y - vectorB.Y));
return isNotEqual ? false : true;
}
}
}
| |
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Reflection;
using OMV = OpenMetaverse;
namespace OpenSim.Region.Physics.BulletSPlugin
{
public sealed class BSCharacter : BSPhysObject
{
private const string AvatarMoveActorName = "BSCharacter.AvatarMove";
private static readonly string LogHeader = "[BULLETS CHAR]";
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private OMV.Vector3 _acceleration;
private float _avatarVolume;
private float _buoyancy;
private float _collisionScore;
private bool _floatOnWater;
private bool _flying;
private bool _grabbed;
private bool _isPhysical;
private bool _kinematic;
private float _mass;
private int _physicsActorType;
private OMV.Vector3 _PIDTarget;
private float _PIDTau;
private OMV.Vector3 _rotationalVelocity;
private bool _selected;
private bool _setAlwaysRun;
// private bool _stopped;
private OMV.Vector3 _size;
private bool _throttleUpdates;
private bool _usePID;
private BSActorAvatarMove m_moveActor;
public BSCharacter(uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size, bool isFlying)
: base(parent_scene, localID, avName, "BSCharacter")
{
_physicsActorType = (int)ActorTypes.Agent;
RawPosition = pos;
_flying = isFlying;
RawOrientation = OMV.Quaternion.Identity;
RawVelocity = OMV.Vector3.Zero;
_buoyancy = ComputeBuoyancyFromFlying(isFlying);
Friction = BSParam.AvatarStandingFriction;
Density = BSParam.AvatarDensity;
// Old versions of ScenePresence passed only the height. If width and/or depth are zero,
// replace with the default values.
_size = size;
if (_size.X == 0f) _size.X = BSParam.AvatarCapsuleDepth;
if (_size.Y == 0f) _size.Y = BSParam.AvatarCapsuleWidth;
// The dimensions of the physical capsule are kept in the scale.
// Physics creates a unit capsule which is scaled by the physics engine.
Scale = ComputeAvatarScale(_size);
// set _avatarVolume and _mass based on capsule size, _density and Scale
ComputeAvatarVolumeAndMass();
DetailLog("{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5},pos={6}",
LocalID, _size, Scale, Density, _avatarVolume, RawMass, pos);
// do actual creation in taint time
PhysScene.TaintedObject(LocalID, "BSCharacter.create", delegate()
{
DetailLog("{0},BSCharacter.create,taint", LocalID);
// New body and shape into PhysBody and PhysShape
PhysScene.Shapes.GetBodyAndShape(true, PhysScene.World, this);
// The avatar's movement is controlled by this motor that speeds up and slows down
// the avatar seeking to reach the motor's target speed.
// This motor runs as a prestep action for the avatar so it will keep the avatar
// standing as well as moving. Destruction of the avatar will destroy the pre-step action.
m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName);
PhysicalActors.Add(AvatarMoveActorName, m_moveActor);
SetPhysicalProperties();
IsInitialized = true;
});
return;
}
public override OMV.Vector3 Acceleration
{
get { return _acceleration; }
set { _acceleration = value; }
}
// neg=fall quickly, 0=1g, 1=0g, pos=float up
public override float Buoyancy
{
get { return _buoyancy; }
set
{
_buoyancy = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setBuoyancy", delegate()
{
DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
ForceBuoyancy = _buoyancy;
});
}
}
public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } }
public override float CollisionScore
{
get { return _collisionScore; }
set
{
_collisionScore = value;
}
}
public override bool FloatOnWater
{
set
{
_floatOnWater = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setFloatOnWater", delegate()
{
if (PhysBody.HasPhysicalBody)
{
if (_floatOnWater)
CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
else
CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
}
});
}
}
public override bool Flying
{
get { return _flying; }
set
{
_flying = value;
// simulate flying by changing the effect of gravity
Buoyancy = ComputeBuoyancyFromFlying(_flying);
}
}
public override OMV.Vector3 Force
{
get { return RawForce; }
set
{
RawForce = value;
// m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force);
PhysScene.TaintedObject(LocalID, "BSCharacter.SetForce", delegate()
{
DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, RawForce);
if (PhysBody.HasPhysicalBody)
PhysScene.PE.SetObjectForce(PhysBody, RawForce);
});
}
}
public override float ForceBuoyancy
{
get { return _buoyancy; }
set
{
PhysScene.AssertInTaintTime("BSCharacter.ForceBuoyancy");
_buoyancy = value;
DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
// Buoyancy is faked by changing the gravity applied to the object
float grav = BSParam.Gravity * (1f - _buoyancy);
Gravity = new OMV.Vector3(0f, 0f, grav);
if (PhysBody.HasPhysicalBody)
PhysScene.PE.SetGravity(PhysBody, Gravity);
}
}
// Go directly to Bullet to get/set the value.
public override OMV.Quaternion ForceOrientation
{
get
{
RawOrientation = PhysScene.PE.GetOrientation(PhysBody);
return RawOrientation;
}
set
{
RawOrientation = value;
if (PhysBody.HasPhysicalBody)
{
// RawPosition = PhysicsScene.PE.GetPosition(BSBody);
PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
}
}
}
public override OMV.Vector3 ForcePosition
{
get
{
RawPosition = PhysScene.PE.GetPosition(PhysBody);
return RawPosition;
}
set
{
RawPosition = value;
if (PhysBody.HasPhysicalBody)
{
PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
}
}
}
public override OMV.Vector3 ForceRotationalVelocity
{
get { return _rotationalVelocity; }
set { _rotationalVelocity = value; }
}
public override OMV.Vector3 ForceVelocity
{
get { return RawVelocity; }
set
{
PhysScene.AssertInTaintTime("BSCharacter.ForceVelocity");
RawVelocity = value;
PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity);
PhysScene.PE.Activate(PhysBody, true);
}
}
public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } }
public override bool Grabbed
{
set { _grabbed = value; }
}
public override bool IsPhysical
{
get { return _isPhysical; }
set
{
_isPhysical = value;
}
}
public override bool IsPhysicallyActive
{
get { return true; }
}
public override bool IsSelected
{
get { return _selected; }
}
public override bool IsSolid
{
get { return true; }
}
public override bool IsStatic
{
get { return false; }
}
public override bool IsVolumeDetect { get { return false; } }
public override bool Kinematic
{
get { return _kinematic; }
set { _kinematic = value; }
}
public override float Mass { get { return _mass; } }
public override OMV.Quaternion Orientation
{
get { return RawOrientation; }
set
{
// Orientation is set zillions of times when an avatar is walking. It's like
// the viewer doesn't trust us.
if (RawOrientation != value)
{
RawOrientation = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setOrientation", delegate()
{
// Bullet assumes we know what we are doing when forcing orientation
// so it lets us go against all the rules and just compensates for them later.
// This forces rotation to be only around the Z axis and doesn't change any of the other axis.
// This keeps us from flipping the capsule over which the veiwer does not understand.
float oRoll, oPitch, oYaw;
RawOrientation.GetEulerAngles(out oRoll, out oPitch, out oYaw);
OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw);
// DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}",
// LocalID, RawOrientation, OMV.Vector3.UnitX * RawOrientation,
// trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation);
ForceOrientation = trimmedOrientation;
});
}
}
}
public override int PhysicsActorType
{
get { return _physicsActorType; }
set
{
_physicsActorType = value;
}
}
public override bool PIDActive
{
set { _usePID = value; }
}
// Used for MoveTo
public override OMV.Vector3 PIDTarget
{
set { _PIDTarget = value; }
}
public override float PIDTau
{
set { _PIDTau = value; }
}
public override OMV.Vector3 Position
{
get
{
// Don't refetch the position because this function is called a zillion times
// RawPosition = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID);
return RawPosition;
}
set
{
RawPosition = value;
PhysScene.TaintedObject(LocalID, "BSCharacter.setPosition", delegate()
{
DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
PositionSanityCheck();
ForcePosition = RawPosition;
});
}
}
// used when we only want this prim's mass and not the linkset thing
public override float RawMass
{
get { return _mass; }
}
public override OMV.Vector3 RotationalVelocity
{
get { return _rotationalVelocity; }
set { _rotationalVelocity = value; }
}
public override bool Selected
{
set { _selected = value; }
}
public override bool
SetAlwaysRun
{
get { return _setAlwaysRun; }
set { _setAlwaysRun = value; }
}
public override PrimitiveBaseShape Shape
{
set { BaseShape = value; }
}
public override OMV.Vector3 Size
{
get
{
// Avatar capsule size is kept in the scale parameter.
return _size;
}
set
{
// This is how much the avatar size is changing. Positive means getting bigger.
// The avatar altitude must be adjusted for this change.
float heightChange = value.Z - _size.Z;
_size = value;
// Old versions of ScenePresence passed only the height. If width and/or depth are zero,
// replace with the default values.
if (_size.X == 0f) _size.X = BSParam.AvatarCapsuleDepth;
if (_size.Y == 0f) _size.Y = BSParam.AvatarCapsuleWidth;
Scale = ComputeAvatarScale(_size);
ComputeAvatarVolumeAndMass();
DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}",
LocalID, _size, Scale, Density, _avatarVolume, RawMass);
PhysScene.TaintedObject(LocalID, "BSCharacter.setSize", delegate()
{
if (PhysBody.HasPhysicalBody && PhysShape.physShapeInfo.HasPhysicalShape)
{
PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
UpdatePhysicalMassProperties(RawMass, true);
// Adjust the avatar's position to account for the increase/decrease in size
ForcePosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, RawPosition.Z + heightChange / 2f);
// Make sure this change appears as a property update event
PhysScene.PE.PushUpdate(PhysBody);
}
});
}
}
// No one calls this method so I don't know what it could possibly mean
public override bool Stopped { get { return false; } }
// Sets the target in the motor. This starts the changing of the avatar's velocity.
public override OMV.Vector3 TargetVelocity
{
get
{
return base.m_targetVelocity;
}
set
{
DetailLog("{0},BSCharacter.setTargetVelocity,call,vel={1}", LocalID, value);
m_targetVelocity = value;
OMV.Vector3 targetVel = value;
if (_setAlwaysRun && !_flying)
targetVel *= new OMV.Vector3(BSParam.AvatarAlwaysRunFactor, BSParam.AvatarAlwaysRunFactor, 1f);
if (m_moveActor != null)
m_moveActor.SetVelocityAndTarget(RawVelocity, targetVel, false /* inTaintTime */);
}
}
public override bool ThrottleUpdates
{
get { return _throttleUpdates; }
set { _throttleUpdates = value; }
}
public override OMV.Vector3 Torque
{
get { return RawTorque; }
set
{
RawTorque = value;
}
}
// Avatars don't do vehicles
public override int VehicleType { get { return (int)Vehicle.TYPE_NONE; } set { return; } }
// Directly setting velocity means this is what the user really wants now.
public override OMV.Vector3 Velocity
{
get { return RawVelocity; }
set
{
RawVelocity = value;
// m_log.DebugFormat("{0}: set velocity = {1}", LogHeader, RawVelocity);
PhysScene.TaintedObject(LocalID, "BSCharacter.setVelocity", delegate()
{
if (m_moveActor != null)
m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, true /* inTaintTime */);
DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, RawVelocity);
ForceVelocity = RawVelocity;
});
}
}
public override void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime)
{
}
public override void AddForce(OMV.Vector3 force, bool pushforce)
{
// Since this force is being applied in only one step, make this a force per second.
OMV.Vector3 addForce = force / PhysScene.LastTimeStep;
AddForce(addForce, pushforce, false);
}
public override void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime)
{
if (force.IsFinite())
{
OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude);
// DetailLog("{0},BSCharacter.addForce,call,force={1}", LocalID, addForce);
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.AddForce", delegate()
{
// Bullet adds this central force to the total force for this tick
// DetailLog("{0},BSCharacter.addForce,taint,force={1}", LocalID, addForce);
if (PhysBody.HasPhysicalBody)
{
PhysScene.PE.ApplyCentralForce(PhysBody, addForce);
}
});
}
else
{
m_log.WarnFormat("{0}: Got a NaN force applied to a character. LocalID={1}", LogHeader, LocalID);
return;
}
}
public override void CrossingFailure()
{
return;
}
public override void delink()
{
return;
}
// called when this character is being destroyed and the resources should be released
public override void Destroy()
{
IsInitialized = false;
base.Destroy();
DetailLog("{0},BSCharacter.Destroy", LocalID);
PhysScene.TaintedObject(LocalID, "BSCharacter.destroy", delegate()
{
PhysScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */);
PhysBody.Clear();
PhysShape.Dereference(PhysScene);
PhysShape = new BSShapeNull();
});
}
public override void link(PhysicsActor obj)
{
return;
}
public override void LockAngularMotion(OMV.Vector3 axis)
{
return;
}
public override void RequestPhysicsterseUpdate()
{
base.RequestPhysicsterseUpdate();
}
public override void SetMomentum(OMV.Vector3 momentum)
{
}
// Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more
public override void SetVolumeDetect(int param)
{
return;
}
public override void UpdatePhysicalMassProperties(float physMass, bool inWorld)
{
OMV.Vector3 localInertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass);
PhysScene.PE.SetMassProps(PhysBody, physMass, localInertia);
}
// The physics engine says that properties have updated. Update same and inform
// the world that things have changed.
public override void UpdateProperties(EntityProperties entprop)
{
// Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator.
TriggerPreUpdatePropertyAction(ref entprop);
RawPosition = entprop.Position;
RawOrientation = entprop.Rotation;
// Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar
// and will send agent updates to the clients if velocity changes by more than
// 0.001m/s. Bullet introduces a lot of jitter in the velocity which causes many
// extra updates.
if (!entprop.Velocity.ApproxEquals(RawVelocity, 0.1f))
RawVelocity = entprop.Velocity;
_acceleration = entprop.Acceleration;
_rotationalVelocity = entprop.RotationalVelocity;
// Do some sanity checking for the avatar. Make sure it's above ground and inbounds.
if (PositionSanityCheck(true))
{
DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, RawPosition);
entprop.Position = RawPosition;
}
// remember the current and last set values
LastEntityProperties = CurrentEntityProperties;
CurrentEntityProperties = entprop;
// Tell the linkset about value changes
// Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this);
// Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop.
// PhysScene.PostUpdate(this);
DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}",
LocalID, RawPosition, RawOrientation, RawVelocity, _acceleration, _rotationalVelocity);
}
public override void VehicleFlags(int param, bool remove)
{
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleRotationParam(int param, OMV.Quaternion rotation)
{
}
public override void VehicleVectorParam(int param, OMV.Vector3 value)
{
}
public override void ZeroAngularMotion(bool inTaintTime)
{
_rotationalVelocity = OMV.Vector3.Zero;
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
{
if (PhysBody.HasPhysicalBody)
{
PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, OMV.Vector3.Zero);
PhysScene.PE.SetAngularVelocity(PhysBody, OMV.Vector3.Zero);
// The next also get rid of applied linear force but the linear velocity is untouched.
PhysScene.PE.ClearForces(PhysBody);
}
});
}
// Set motion values to zero.
// Do it to the properties so the values get set in the physics engine.
// Push the setting of the values to the viewer.
// Called at taint time!
public override void ZeroMotion(bool inTaintTime)
{
RawVelocity = OMV.Vector3.Zero;
_acceleration = OMV.Vector3.Zero;
_rotationalVelocity = OMV.Vector3.Zero;
// Zero some other properties directly into the physics engine
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
{
if (PhysBody.HasPhysicalBody)
PhysScene.PE.ClearAllForces(PhysBody);
});
}
private OMV.Vector3 ComputeAvatarScale(OMV.Vector3 size)
{
OMV.Vector3 newScale = size;
// Bullet's capsule total height is the "passed height + radius * 2";
// The base capsule is 1 unit in diameter and 2 units in height (passed radius=0.5, passed height = 1)
// The number we pass in for 'scaling' is the multiplier to get that base
// shape to be the size desired.
// So, when creating the scale for the avatar height, we take the passed height
// (size.Z) and remove the caps.
// An oddity of the Bullet capsule implementation is that it presumes the Y
// dimension is the radius of the capsule. Even though some of the code allows
// for a asymmetrical capsule, other parts of the code presume it is cylindrical.
// Scale is multiplier of radius with one of "0.5"
float heightAdjust = BSParam.AvatarHeightMidFudge;
if (BSParam.AvatarHeightLowFudge != 0f || BSParam.AvatarHeightHighFudge != 0f)
{
const float AVATAR_LOW = 1.1f;
const float AVATAR_MID = 1.775f; // 1.87f
const float AVATAR_HI = 2.45f;
// An avatar is between 1.1 and 2.45 meters. Midpoint is 1.775m.
float midHeightOffset = size.Z - AVATAR_MID;
if (midHeightOffset < 0f)
{
// Small avatar. Add the adjustment based on the distance from midheight
heightAdjust += ((-1f * midHeightOffset) / (AVATAR_MID - AVATAR_LOW)) * BSParam.AvatarHeightLowFudge;
}
else
{
// Large avatar. Add the adjustment based on the distance from midheight
heightAdjust += ((midHeightOffset) / (AVATAR_HI - AVATAR_MID)) * BSParam.AvatarHeightHighFudge;
}
}
if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule)
{
newScale.X = size.X / 2f;
newScale.Y = size.Y / 2f;
// The total scale height is the central cylindar plus the caps on the two ends.
newScale.Z = (size.Z + (Math.Min(size.X, size.Y) * 2) + heightAdjust) / 2f;
}
else
{
newScale.Z = size.Z + heightAdjust;
}
// m_log.DebugFormat("{0} ComputeAvatarScale: size={1},adj={2},scale={3}", LogHeader, size, heightAdjust, newScale);
// If smaller than the endcaps, just fake like we're almost that small
if (newScale.Z < 0)
newScale.Z = 0.1f;
DetailLog("{0},BSCharacter.ComputerAvatarScale,size={1},lowF={2},midF={3},hiF={4},adj={5},newScale={6}",
LocalID, size, BSParam.AvatarHeightLowFudge, BSParam.AvatarHeightMidFudge, BSParam.AvatarHeightHighFudge, heightAdjust, newScale);
return newScale;
}
// set _avatarVolume and _mass based on capsule size, _density and Scale
private void ComputeAvatarVolumeAndMass()
{
_avatarVolume = (float)(
Math.PI
* Size.X / 2f
* Size.Y / 2f // the area of capsule cylinder
* Size.Z // times height of capsule cylinder
+ 1.33333333f
* Math.PI
* Size.X / 2f
* Math.Min(Size.X, Size.Y) / 2
* Size.Y / 2f // plus the volume of the capsule end caps
);
_mass = Density * BSParam.DensityScaleFactor * _avatarVolume;
}
// Flying is implimented by changing the avatar's buoyancy.
// Would this be done better with a vehicle type?
private float ComputeBuoyancyFromFlying(bool ifFlying)
{
return ifFlying ? 1f : 0f;
}
// Check that the current position is sane and, if not, modify the position to make it so.
// Check for being below terrain or on water.
// Returns 'true' of the position was made sane by some action.
private bool PositionSanityCheck()
{
bool ret = false;
// TODO: check for out of bounds
if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition))
{
// The character is out of the known/simulated area.
// Force the avatar position to be within known. ScenePresence will use the position
// plus the velocity to decide if the avatar is moving out of the region.
RawPosition = PhysScene.TerrainManager.ClampPositionIntoKnownTerrain(RawPosition);
DetailLog("{0},BSCharacter.PositionSanityCheck,notWithinKnownTerrain,clampedPos={1}", LocalID, RawPosition);
return true;
}
// If below the ground, move the avatar up
float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition);
if (Position.Z < terrainHeight)
{
DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight);
RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters);
ret = true;
}
if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0)
{
float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition);
if (Position.Z < waterHeight)
{
RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, waterHeight);
ret = true;
}
}
return ret;
}
// A version of the sanity check that also makes sure a new position value is
// pushed back to the physics engine. This routine would be used by anyone
// who is not already pushing the value.
private bool PositionSanityCheck(bool inTaintTime)
{
bool ret = false;
if (PositionSanityCheck())
{
// The new position value must be pushed into the physics engine but we can't
// just assign to "Position" because of potential call loops.
PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.PositionSanityCheck", delegate()
{
DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
ForcePosition = RawPosition;
});
ret = true;
}
return ret;
}
private void SetPhysicalProperties()
{
PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody);
ZeroMotion(true);
ForcePosition = RawPosition;
// Set the velocity
if (m_moveActor != null)
m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false);
ForceVelocity = RawVelocity;
// This will enable or disable the flying buoyancy of the avatar.
// Needs to be reset especially when an avatar is recreated after crossing a region boundry.
Flying = _flying;
PhysScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution);
PhysScene.PE.SetMargin(PhysShape.physShapeInfo, PhysScene.Params.collisionMargin);
PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold);
if (BSParam.CcdMotionThreshold > 0f)
{
PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold);
PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius);
}
UpdatePhysicalMassProperties(RawMass, false);
// Make so capsule does not fall over
PhysScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero);
// The avatar mover sets some parameters.
PhysicalActors.Refresh();
PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT);
PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody);
// PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG);
PhysScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_DEACTIVATION);
PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody);
// Do this after the object has been added to the world
PhysBody.collisionType = CollisionType.Avatar;
PhysBody.ApplyCollisionMask(PhysScene);
}
}
}
| |
namespace System.Diagnostics {
using System.Runtime.InteropServices;
using System.Globalization;
using System.Security.Permissions;
using System.Security;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.ComponentModel;
using System.Collections.Specialized;
using Microsoft.Win32;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
internal class PerformanceCounterLib {
internal const string PerfShimName = "netfxperf.dll";
private const string PerfShimFullNameSuffix = @"\netfxperf.dll";
private const string PerfShimPathExp = @"%systemroot%\system32\netfxperf.dll";
internal const string OpenEntryPoint = "OpenPerformanceData";
internal const string CollectEntryPoint = "CollectPerformanceData";
internal const string CloseEntryPoint = "ClosePerformanceData";
internal const string SingleInstanceName = "systemdiagnosticsperfcounterlibsingleinstance";
private const string PerflibPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib";
internal const string ServicePath = "SYSTEM\\CurrentControlSet\\Services";
private const string categorySymbolPrefix = "OBJECT_";
private const string conterSymbolPrefix = "DEVICE_COUNTER_";
private const string helpSufix = "_HELP";
private const string nameSufix = "_NAME";
private const string textDefinition = "[text]";
private const string infoDefinition = "[info]";
private const string languageDefinition = "[languages]";
private const string objectDefinition = "[objects]";
private const string driverNameKeyword = "drivername";
private const string symbolFileKeyword = "symbolfile";
private const string defineKeyword = "#define";
private const string languageKeyword = "language";
private const string DllName = "netfxperf.dll";
private const int EnglishLCID = 0x009;
private static volatile string computerName;
private static volatile string iniFilePath;
private static volatile string symbolFilePath;
private PerformanceMonitor performanceMonitor;
private string machineName;
private string perfLcid;
private Hashtable customCategoryTable;
private static volatile Hashtable libraryTable;
private Hashtable categoryTable;
private Hashtable nameTable;
private Hashtable helpTable;
private readonly object CategoryTableLock = new Object();
private readonly object NameTableLock = new Object();
private readonly object HelpTableLock = new Object();
private static Object s_InternalSyncObject;
private static Object InternalSyncObject {
get {
if (s_InternalSyncObject == null) {
Object o = new Object();
Interlocked.CompareExchange(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
internal PerformanceCounterLib(string machineName, string lcid) {
this.machineName = machineName;
this.perfLcid = lcid;
}
/// <internalonly/>
internal static string ComputerName {
get {
if (computerName == null) {
lock (InternalSyncObject) {
if (computerName == null) {
StringBuilder sb = new StringBuilder(256);
SafeNativeMethods.GetComputerName(sb, new int[] {sb.Capacity});
computerName = sb.ToString();
}
}
}
return computerName;
}
}
private unsafe Hashtable CategoryTable {
get {
if (this.categoryTable == null) {
lock (this.CategoryTableLock) {
if (this.categoryTable == null) {
byte[] perfData = GetPerformanceData("Global");
fixed (byte* perfDataPtr = perfData) {
IntPtr dataRef = new IntPtr( (void*) perfDataPtr);
NativeMethods.PERF_DATA_BLOCK dataBlock = new NativeMethods.PERF_DATA_BLOCK();
Marshal.PtrToStructure(dataRef, dataBlock);
dataRef = (IntPtr)((long)dataRef + dataBlock.HeaderLength);
int categoryNumber = dataBlock.NumObjectTypes;
// on some machines MSMQ claims to have 4 categories, even though it only has 2.
// This causes us to walk past the end of our data, potentially crashing or reading
// data we shouldn't. We use endPerfData to make sure we don't go past the end
// of the perf data. (ASURT 137097)
long endPerfData = (long)(new IntPtr((void*)perfDataPtr)) + dataBlock.TotalByteLength;
Hashtable tempCategoryTable = new Hashtable(categoryNumber, StringComparer.OrdinalIgnoreCase);
for (int index = 0; index < categoryNumber && ((long) dataRef < endPerfData); index++) {
NativeMethods.PERF_OBJECT_TYPE perfObject = new NativeMethods.PERF_OBJECT_TYPE();
Marshal.PtrToStructure(dataRef, perfObject);
CategoryEntry newCategoryEntry = new CategoryEntry(perfObject);
IntPtr nextRef = (IntPtr)((long)dataRef + perfObject.TotalByteLength);
dataRef = (IntPtr)((long)dataRef + perfObject.HeaderLength);
int index3 = 0;
int previousCounterIndex = -1;
//Need to filter out counters that are repeated, some providers might
//return several adyacent copies of the same counter.
for (int index2 = 0; index2 < newCategoryEntry.CounterIndexes.Length; ++ index2) {
NativeMethods.PERF_COUNTER_DEFINITION perfCounter = new NativeMethods.PERF_COUNTER_DEFINITION();
Marshal.PtrToStructure(dataRef, perfCounter);
if (perfCounter.CounterNameTitleIndex != previousCounterIndex) {
newCategoryEntry.CounterIndexes[index3] = perfCounter.CounterNameTitleIndex;
newCategoryEntry.HelpIndexes[index3] = perfCounter.CounterHelpTitleIndex;
previousCounterIndex = perfCounter.CounterNameTitleIndex;
++ index3;
}
dataRef = (IntPtr)((long)dataRef + perfCounter.ByteLength);
}
//Lets adjust the entry counter arrays in case there were repeated copies
if (index3 < newCategoryEntry.CounterIndexes.Length) {
int[] adjustedCounterIndexes = new int[index3];
int[] adjustedHelpIndexes = new int[index3];
Array.Copy(newCategoryEntry.CounterIndexes, adjustedCounterIndexes, index3);
Array.Copy(newCategoryEntry.HelpIndexes, adjustedHelpIndexes, index3);
newCategoryEntry.CounterIndexes = adjustedCounterIndexes;
newCategoryEntry.HelpIndexes = adjustedHelpIndexes;
}
string categoryName = (string)this.NameTable[newCategoryEntry.NameIndex];
if (categoryName != null)
tempCategoryTable[categoryName] = newCategoryEntry;
dataRef = nextRef;
}
this.categoryTable = tempCategoryTable;
}
}
}
}
return this.categoryTable;
}
}
internal Hashtable HelpTable {
get {
if (this.helpTable == null) {
lock(this.HelpTableLock) {
if (this.helpTable == null)
this.helpTable = GetStringTable(true);
}
}
return this.helpTable;
}
}
// Returns a temp file name
private static string IniFilePath {
[ResourceExposure(ResourceScope.AppDomain)]
[ResourceConsumption(ResourceScope.AppDomain)]
get {
if (iniFilePath == null) {
lock (InternalSyncObject) {
if (iniFilePath == null) {
// Need to assert Environment permissions here
// the environment check is not exposed as a public
// method
EnvironmentPermission environmentPermission = new EnvironmentPermission(PermissionState.Unrestricted);
environmentPermission.Assert();
try {
iniFilePath = Path.GetTempFileName();
}
finally {
EnvironmentPermission.RevertAssert();
}
}
}
}
return iniFilePath;
}
}
internal Hashtable NameTable {
get {
if (this.nameTable == null) {
lock(this.NameTableLock) {
if (this.nameTable == null)
this.nameTable = GetStringTable(false);
}
}
return this.nameTable;
}
}
// Returns a temp file name
private static string SymbolFilePath {
[ResourceExposure(ResourceScope.AppDomain)]
[ResourceConsumption(ResourceScope.AppDomain | ResourceScope.Machine)]
get {
if (symbolFilePath == null) {
lock (InternalSyncObject) {
if (symbolFilePath == null) {
string tempPath;
EnvironmentPermission environmentPermission = new EnvironmentPermission(PermissionState.Unrestricted);
environmentPermission.Assert();
tempPath = Path.GetTempPath();
EnvironmentPermission.RevertAssert();
// We need both FileIOPermission EvironmentPermission
PermissionSet ps = new PermissionSet(PermissionState.None);
ps.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
ps.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write, tempPath));
ps.Assert();
try {
symbolFilePath = Path.GetTempFileName();
}
finally {
PermissionSet.RevertAssert();
}
}
}
}
return symbolFilePath;
}
}
internal static bool CategoryExists(string machine, string category) {
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
if (library.CategoryExists(category))
return true;
if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture) {
library = GetPerformanceCounterLib(machine, culture);
if (library.CategoryExists(category))
return true;
culture = culture.Parent;
}
}
return false;
}
internal bool CategoryExists(string category) {
return CategoryTable.ContainsKey(category);
}
internal static void CloseAllLibraries() {
if (libraryTable != null) {
foreach (PerformanceCounterLib library in libraryTable.Values)
library.Close();
libraryTable = null;
}
}
internal static void CloseAllTables() {
if (libraryTable != null) {
foreach (PerformanceCounterLib library in libraryTable.Values)
library.CloseTables();
}
}
internal void CloseTables() {
this.nameTable = null;
this.helpTable = null;
this.categoryTable = null;
this.customCategoryTable = null;
}
internal void Close() {
if (this.performanceMonitor != null) {
this.performanceMonitor.Close();
this.performanceMonitor = null;
}
CloseTables();
}
internal static bool CounterExists(string machine, string category, string counter) {
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
bool categoryExists = false;
bool counterExists = library.CounterExists(category, counter, ref categoryExists);
if (!categoryExists && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture) {
library = GetPerformanceCounterLib(machine, culture);
counterExists = library.CounterExists(category, counter, ref categoryExists);
if (counterExists)
break;
culture = culture.Parent;
}
}
if (!categoryExists) {
// Consider adding diagnostic logic here, may be we can dump the nameTable...
throw new InvalidOperationException(SR.GetString(SR.MissingCategory));
}
return counterExists;
}
private bool CounterExists(string category, string counter, ref bool categoryExists) {
categoryExists = false;
if (!CategoryTable.ContainsKey(category))
return false;
else
categoryExists = true;
CategoryEntry entry = (CategoryEntry)this.CategoryTable[category];
for (int index = 0; index < entry.CounterIndexes.Length; ++ index) {
int counterIndex = entry.CounterIndexes[index];
string counterName = (string)this.NameTable[counterIndex];
if (counterName == null)
counterName = String.Empty;
if (String.Compare(counterName, counter, StringComparison.OrdinalIgnoreCase) == 0)
return true;
}
return false;
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static void CreateIniFile(string categoryName, string categoryHelp, CounterCreationDataCollection creationData, string[] languageIds) {
//SECREVIEW: PerformanceCounterPermission must have been demanded before
FileIOPermission permission = new FileIOPermission(PermissionState.Unrestricted);
permission.Assert();
try {
StreamWriter iniWriter = new StreamWriter(IniFilePath, false, Encoding.Unicode);
try {
//NT4 won't be able to parse Unicode ini files without this
//extra white space.
iniWriter.WriteLine("");
iniWriter.WriteLine(infoDefinition);
iniWriter.Write(driverNameKeyword);
iniWriter.Write("=");
iniWriter.WriteLine(categoryName);
iniWriter.Write(symbolFileKeyword);
iniWriter.Write("=");
iniWriter.WriteLine(Path.GetFileName(SymbolFilePath));
iniWriter.WriteLine("");
iniWriter.WriteLine(languageDefinition);
foreach (string languageId in languageIds) {
iniWriter.Write(languageId);
iniWriter.Write("=");
iniWriter.Write(languageKeyword);
iniWriter.WriteLine(languageId);
}
iniWriter.WriteLine("");
iniWriter.WriteLine(objectDefinition);
foreach (string languageId in languageIds) {
iniWriter.Write(categorySymbolPrefix);
iniWriter.Write("1_");
iniWriter.Write(languageId);
iniWriter.Write(nameSufix);
iniWriter.Write("=");
iniWriter.WriteLine(categoryName);
}
iniWriter.WriteLine("");
iniWriter.WriteLine(textDefinition);
foreach (string languageId in languageIds) {
iniWriter.Write(categorySymbolPrefix);
iniWriter.Write("1_");
iniWriter.Write(languageId);
iniWriter.Write(nameSufix);
iniWriter.Write("=");
iniWriter.WriteLine(categoryName);
iniWriter.Write(categorySymbolPrefix);
iniWriter.Write("1_");
iniWriter.Write(languageId);
iniWriter.Write(helpSufix);
iniWriter.Write("=");
if (categoryHelp == null || categoryHelp == String.Empty)
iniWriter.WriteLine(SR.GetString(SR.HelpNotAvailable));
else
iniWriter.WriteLine(categoryHelp);
int counterIndex = 0;
foreach (CounterCreationData counterData in creationData) {
++counterIndex;
iniWriter.WriteLine("");
iniWriter.Write(conterSymbolPrefix);
iniWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
iniWriter.Write("_");
iniWriter.Write(languageId);
iniWriter.Write(nameSufix);
iniWriter.Write("=");
iniWriter.WriteLine(counterData.CounterName);
iniWriter.Write(conterSymbolPrefix);
iniWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
iniWriter.Write("_");
iniWriter.Write(languageId);
iniWriter.Write(helpSufix);
iniWriter.Write("=");
Debug.Assert(!String.IsNullOrEmpty(counterData.CounterHelp), "CounterHelp should have been fixed up by the caller");
iniWriter.WriteLine(counterData.CounterHelp);
}
}
iniWriter.WriteLine("");
}
finally {
iniWriter.Close();
}
}
finally {
FileIOPermission.RevertAssert();
}
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static void CreateRegistryEntry(string categoryName, PerformanceCounterCategoryType categoryType, CounterCreationDataCollection creationData, ref bool iniRegistered) {
RegistryKey serviceParentKey = null;
RegistryKey serviceKey = null;
RegistryKey linkageKey = null;
//SECREVIEW: Whoever is able to call this function, must already
// have demmanded PerformanceCounterPermission
// we can therefore assert the RegistryPermission.
RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
registryPermission.Assert();
try {
serviceParentKey = Registry.LocalMachine.OpenSubKey(ServicePath, true);
serviceKey = serviceParentKey.OpenSubKey(categoryName + "\\Performance", true);
if (serviceKey == null)
serviceKey = serviceParentKey.CreateSubKey(categoryName + "\\Performance");
serviceKey.SetValue("Open","OpenPerformanceData");
serviceKey.SetValue("Collect", "CollectPerformanceData");
serviceKey.SetValue("Close","ClosePerformanceData");
serviceKey.SetValue("Library", DllName);
serviceKey.SetValue("IsMultiInstance", (int) categoryType, RegistryValueKind.DWord);
serviceKey.SetValue("CategoryOptions", 0x3, RegistryValueKind.DWord);
string [] counters = new string[creationData.Count];
string [] counterTypes = new string[creationData.Count];
for (int i = 0; i < creationData.Count; i++) {
counters[i] = creationData[i].CounterName;
counterTypes[i] = ((int) creationData[i].CounterType).ToString(CultureInfo.InvariantCulture);
}
linkageKey = serviceParentKey.OpenSubKey(categoryName + "\\Linkage" , true);
if (linkageKey == null)
linkageKey = serviceParentKey.CreateSubKey(categoryName + "\\Linkage" );
linkageKey.SetValue("Export", new string[]{categoryName});
serviceKey.SetValue("Counter Types", (object) counterTypes);
serviceKey.SetValue("Counter Names", (object) counters);
object firstID = serviceKey.GetValue("First Counter");
if (firstID != null)
iniRegistered = true;
else
iniRegistered = false;
}
finally {
if (serviceKey != null)
serviceKey.Close();
if (linkageKey != null)
linkageKey.Close();
if (serviceParentKey != null)
serviceParentKey.Close();
RegistryPermission.RevertAssert();
}
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static void CreateSymbolFile(CounterCreationDataCollection creationData) {
//SECREVIEW: PerformanceCounterPermission must have been demanded before
FileIOPermission permission = new FileIOPermission(PermissionState.Unrestricted);
permission.Assert();
try {
StreamWriter symbolWriter = new StreamWriter(SymbolFilePath);
try {
symbolWriter.Write(defineKeyword);
symbolWriter.Write(" ");
symbolWriter.Write(categorySymbolPrefix);
symbolWriter.WriteLine("1 0;");
for (int counterIndex = 1; counterIndex <= creationData.Count; ++ counterIndex) {
symbolWriter.Write(defineKeyword);
symbolWriter.Write(" ");
symbolWriter.Write(conterSymbolPrefix);
symbolWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
symbolWriter.Write(" ");
symbolWriter.Write((counterIndex * 2).ToString(CultureInfo.InvariantCulture));
symbolWriter.WriteLine(";");
}
symbolWriter.WriteLine("");
}
finally {
symbolWriter.Close();
}
}
finally {
FileIOPermission.RevertAssert();
}
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static void DeleteRegistryEntry(string categoryName) {
RegistryKey serviceKey = null;
//SECREVIEW: Whoever is able to call this function, must already
// have demmanded PerformanceCounterPermission
// we can therefore assert the RegistryPermission.
RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
registryPermission.Assert();
try {
serviceKey = Registry.LocalMachine.OpenSubKey(ServicePath, true);
bool deleteCategoryKey = false;
using (RegistryKey categoryKey = serviceKey.OpenSubKey(categoryName, true)) {
if (categoryKey != null) {
if (categoryKey.GetValueNames().Length == 0) {
deleteCategoryKey = true;
}
else {
categoryKey.DeleteSubKeyTree("Linkage");
categoryKey.DeleteSubKeyTree("Performance");
}
}
}
if (deleteCategoryKey)
serviceKey.DeleteSubKeyTree(categoryName);
}
finally {
if (serviceKey != null)
serviceKey.Close();
RegistryPermission.RevertAssert();
}
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static void DeleteTemporaryFiles() {
try {
File.Delete(IniFilePath);
}
catch {
}
try {
File.Delete(SymbolFilePath);
}
catch {
}
}
// Ensures that the customCategoryTable is initialized and decides whether the category passed in
// 1) is a custom category
// 2) is a multi instance custom category
// The return value is whether the category is a custom category or not.
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal bool FindCustomCategory(string category, out PerformanceCounterCategoryType categoryType) {
RegistryKey key = null;
RegistryKey baseKey = null;
categoryType = PerformanceCounterCategoryType.Unknown;
if (this.customCategoryTable == null) {
Interlocked.CompareExchange(ref this.customCategoryTable, new Hashtable(StringComparer.OrdinalIgnoreCase), null);
}
if (this.customCategoryTable.ContainsKey(category)) {
categoryType= (PerformanceCounterCategoryType) this.customCategoryTable[category];
return true;
}
else {
//SECREVIEW: Whoever is able to call this function, must already
// have demanded PerformanceCounterPermission
// we can therefore assert the RegistryPermission.
PermissionSet ps = new PermissionSet(PermissionState.None);
ps.AddPermission(new RegistryPermission(PermissionState.Unrestricted));
ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
ps.Assert();
try {
string keyPath = ServicePath + "\\" + category + "\\Performance";
if (machineName == "." || String.Compare(this.machineName, ComputerName, StringComparison.OrdinalIgnoreCase) == 0) {
key = Registry.LocalMachine.OpenSubKey(keyPath);
}
else {
baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, "\\\\" + this.machineName);
if (baseKey != null) {
try {
key = baseKey.OpenSubKey(keyPath);
} catch (SecurityException) {
// we may not have permission to read the registry key on the remote machine. The security exception
// is thrown when RegOpenKeyEx returns ERROR_ACCESS_DENIED or ERROR_BAD_IMPERSONATION_LEVEL
//
// In this case we return an 'Unknown' category type and 'false' to indicate the category is *not* custom.
//
categoryType = PerformanceCounterCategoryType.Unknown;
this.customCategoryTable[category] = categoryType;
return false;
}
}
}
if (key != null) {
object systemDllName = key.GetValue("Library", null, RegistryValueOptions.DoNotExpandEnvironmentNames);
if (systemDllName != null && systemDllName is string
&& (String.Compare((string)systemDllName, PerformanceCounterLib.PerfShimName, StringComparison.OrdinalIgnoreCase) == 0
|| ((string)systemDllName).EndsWith(PerformanceCounterLib.PerfShimFullNameSuffix, StringComparison.OrdinalIgnoreCase))) {
object isMultiInstanceObject = key.GetValue("IsMultiInstance");
if (isMultiInstanceObject != null) {
categoryType = (PerformanceCounterCategoryType) isMultiInstanceObject;
if (categoryType < PerformanceCounterCategoryType.Unknown || categoryType > PerformanceCounterCategoryType.MultiInstance)
categoryType = PerformanceCounterCategoryType.Unknown;
}
else
categoryType = PerformanceCounterCategoryType.Unknown;
object objectID = key.GetValue("First Counter");
if (objectID != null) {
int firstID = (int)objectID;
this.customCategoryTable[category] = categoryType;
return true;
}
}
}
}
finally {
if (key != null) key.Close();
if (baseKey != null) baseKey.Close();
PermissionSet.RevertAssert();
}
}
return false;
}
internal static string[] GetCategories(string machineName) {
PerformanceCounterLib library;
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture) {
library = GetPerformanceCounterLib(machineName, culture);
string[] categories = library.GetCategories();
if (categories.Length != 0 )
return categories;
culture = culture.Parent;
}
library = GetPerformanceCounterLib(machineName, new CultureInfo(EnglishLCID));
return library.GetCategories();
}
internal string[] GetCategories() {
ICollection keys = CategoryTable.Keys;
string[] categories = new string[keys.Count];
keys.CopyTo(categories, 0);
return categories;
}
internal static string GetCategoryHelp(string machine, string category) {
PerformanceCounterLib library;
string help;
//First check the current culture for the category. This will allow
//PerformanceCounterCategory.CategoryHelp to return localized strings.
if(CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture) {
library = GetPerformanceCounterLib(machine, culture);
help = library.GetCategoryHelp(category);
if (help != null)
return help;
culture = culture.Parent;
}
}
//We did not find the category walking up the culture hierarchy. Try looking
// for the category in the default culture English.
library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
help = library.GetCategoryHelp(category);
if (help == null)
throw new InvalidOperationException(SR.GetString(SR.MissingCategory));
return help;
}
private string GetCategoryHelp(string category) {
CategoryEntry entry = (CategoryEntry)this.CategoryTable[category];
if (entry == null)
return null;
return (string)this.HelpTable[entry.HelpIndex];
}
internal static CategorySample GetCategorySample(string machine, string category) {
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
CategorySample sample = library.GetCategorySample(category);
if (sample == null && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture) {
library = GetPerformanceCounterLib(machine, culture);
sample = library.GetCategorySample(category);
if (sample != null)
return sample;
culture = culture.Parent;
}
}
if (sample == null)
throw new InvalidOperationException(SR.GetString(SR.MissingCategory));
return sample;
}
private CategorySample GetCategorySample(string category) {
CategoryEntry entry = (CategoryEntry)this.CategoryTable[category];
if (entry == null)
return null;
CategorySample sample = null;
byte[] dataRef = GetPerformanceData(entry.NameIndex.ToString(CultureInfo.InvariantCulture));
if (dataRef == null)
throw new InvalidOperationException(SR.GetString(SR.CantReadCategory, category));
sample = new CategorySample(dataRef, entry, this);
return sample;
}
internal static string[] GetCounters(string machine, string category) {
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
bool categoryExists = false;
string[] counters = library.GetCounters(category, ref categoryExists);
if (!categoryExists && CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture) {
library = GetPerformanceCounterLib(machine, culture);
counters = library.GetCounters(category, ref categoryExists);
if (categoryExists)
return counters;
culture = culture.Parent;
}
}
if (!categoryExists)
throw new InvalidOperationException(SR.GetString(SR.MissingCategory));
return counters;
}
private string[] GetCounters(string category, ref bool categoryExists) {
categoryExists = false;
CategoryEntry entry = (CategoryEntry)this.CategoryTable[category];
if (entry == null)
return null;
else
categoryExists = true;
int index2 = 0;
string[] counters = new string[entry.CounterIndexes.Length];
for (int index = 0; index < counters.Length; ++ index) {
int counterIndex = entry.CounterIndexes[index];
string counterName = (string)this.NameTable[counterIndex];
if (counterName != null && counterName != String.Empty) {
counters[index2] = counterName;
++index2;
}
}
//Lets adjust the array in case there were null entries
if (index2 < counters.Length) {
string[] adjustedCounters = new string[index2];
Array.Copy(counters, adjustedCounters, index2);
counters = adjustedCounters;
}
return counters;
}
internal static string GetCounterHelp(string machine, string category, string counter) {
PerformanceCounterLib library;
bool categoryExists = false;
string help;
//First check the current culture for the counter. This will allow
//PerformanceCounter.CounterHelp to return localized strings.
if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture) {
library = GetPerformanceCounterLib(machine, culture);
help = library.GetCounterHelp(category, counter, ref categoryExists);
if (categoryExists)
return help;
culture = culture.Parent;
}
}
//We did not find the counter walking up the culture hierarchy. Try looking
// for the counter in the default culture English.
library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
help = library.GetCounterHelp(category, counter, ref categoryExists);
if (!categoryExists)
throw new InvalidOperationException(SR.GetString(SR.MissingCategoryDetail, category));
return help;
}
private string GetCounterHelp(string category, string counter, ref bool categoryExists) {
categoryExists = false;
CategoryEntry entry = (CategoryEntry)this.CategoryTable[category];
if (entry == null)
return null;
else
categoryExists = true;
int helpIndex = -1;
for (int index = 0; index < entry.CounterIndexes.Length; ++ index) {
int counterIndex = entry.CounterIndexes[index];
string counterName = (string)this.NameTable[counterIndex];
if (counterName == null)
counterName = String.Empty;
if (String.Compare(counterName, counter, StringComparison.OrdinalIgnoreCase) == 0) {
helpIndex = entry.HelpIndexes[index];
break;
}
}
if (helpIndex == -1)
throw new InvalidOperationException(SR.GetString(SR.MissingCounter, counter));
string help = (string)this.HelpTable[helpIndex];
if (help == null)
return String.Empty;
else
return help;
}
internal string GetCounterName(int index) {
if (this.NameTable.ContainsKey(index))
return (string)this.NameTable[index];
return "";
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static string[] GetLanguageIds() {
RegistryKey libraryParentKey = null;
string[] ids = new string[0];
new RegistryPermission(PermissionState.Unrestricted).Assert();
try {
libraryParentKey = Registry.LocalMachine.OpenSubKey(PerflibPath);
if (libraryParentKey != null)
ids = libraryParentKey.GetSubKeyNames();
}
finally {
if (libraryParentKey != null)
libraryParentKey.Close();
RegistryPermission.RevertAssert();
}
return ids;
}
internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture) {
SharedUtils.CheckEnvironment();
string lcidString = culture.LCID.ToString("X3", CultureInfo.InvariantCulture);
if (machineName.CompareTo(".") == 0)
machineName = ComputerName.ToLower(CultureInfo.InvariantCulture);
else
machineName = machineName.ToLower(CultureInfo.InvariantCulture);
if (PerformanceCounterLib.libraryTable == null) {
lock (InternalSyncObject) {
if (PerformanceCounterLib.libraryTable == null)
PerformanceCounterLib.libraryTable = new Hashtable();
}
}
string libraryKey = machineName + ":" + lcidString;
if (PerformanceCounterLib.libraryTable.Contains(libraryKey))
return (PerformanceCounterLib)PerformanceCounterLib.libraryTable[libraryKey];
else {
PerformanceCounterLib library = new PerformanceCounterLib(machineName, lcidString);
PerformanceCounterLib.libraryTable[libraryKey] = library;
return library;
}
}
internal byte[] GetPerformanceData(string item) {
if (this.performanceMonitor == null) {
lock (InternalSyncObject) {
if (this.performanceMonitor == null)
this.performanceMonitor = new PerformanceMonitor(this.machineName);
}
}
return this.performanceMonitor.GetData(item);
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private Hashtable GetStringTable(bool isHelp) {
Hashtable stringTable;
RegistryKey libraryKey;
PermissionSet ps = new PermissionSet(PermissionState.None);
ps.AddPermission(new RegistryPermission(PermissionState.Unrestricted));
ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
ps.Assert();
if (String.Compare(this.machineName, ComputerName, StringComparison.OrdinalIgnoreCase) == 0)
libraryKey = Registry.PerformanceData;
else {
libraryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, this.machineName);
}
try {
string[] names = null;
int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
int waitSleep = 0;
// In some stress situations, querying counter values from
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009
// often returns null/empty data back. We should build fault-tolerance logic to
// make it more reliable because getting null back once doesn't necessarily mean
// that the data is corrupted, most of the time we would get the data just fine
// in subsequent tries.
while (waitRetries > 0) {
try {
if (!isHelp)
names = (string[])libraryKey.GetValue("Counter " + perfLcid);
else
names = (string[])libraryKey.GetValue("Explain " + perfLcid);
if ((names == null) || (names.Length == 0)) {
--waitRetries;
if (waitSleep == 0)
waitSleep = 10;
else {
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
}
else
break;
}
catch (IOException) {
// RegistryKey throws if it can't find the value. We want to return an empty table
// and throw a different exception higher up the stack.
names = null;
break;
}
catch (InvalidCastException) {
// Unable to cast object of type 'System.Byte[]' to type 'System.String[]'.
// this happens when the registry data store is corrupt and the type is not even REG_MULTI_SZ
names = null;
break;
}
}
if (names == null)
stringTable = new Hashtable();
else {
stringTable = new Hashtable(names.Length/2);
for (int index = 0; index < (names.Length/2); ++ index) {
string nameString = names[(index *2) + 1];
if (nameString == null)
nameString = String.Empty;
int key;
if (!Int32.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key)) {
if (isHelp) {
// Category Help Table
throw new InvalidOperationException(SR.GetString(SR.CategoryHelpCorrupt, names[index * 2]));
}
else {
// Counter Name Table
throw new InvalidOperationException(SR.GetString(SR.CounterNameCorrupt, names[index * 2]));
}
}
stringTable[key] = nameString;
}
}
}
finally {
libraryKey.Close();
}
return stringTable;
}
internal static bool IsCustomCategory(string machine, string category) {
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
if (library.IsCustomCategory(category))
return true;
if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture) {
library = GetPerformanceCounterLib(machine, culture);
if (library.IsCustomCategory(category))
return true;
culture = culture.Parent;
}
}
return false;
}
internal static bool IsBaseCounter(int type) {
return (type == NativeMethods.PERF_AVERAGE_BASE ||
type == NativeMethods.PERF_COUNTER_MULTI_BASE ||
type == NativeMethods.PERF_RAW_BASE ||
type == NativeMethods.PERF_LARGE_RAW_BASE ||
type == NativeMethods.PERF_SAMPLE_BASE);
}
private bool IsCustomCategory(string category) {
PerformanceCounterCategoryType categoryType;
return FindCustomCategory(category, out categoryType);
}
internal static PerformanceCounterCategoryType GetCategoryType(string machine, string category) {
PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.Unknown;
PerformanceCounterLib library = GetPerformanceCounterLib(machine, new CultureInfo(EnglishLCID));
if (!library.FindCustomCategory(category, out categoryType)) {
if (CultureInfo.CurrentCulture.Parent.LCID != EnglishLCID) {
CultureInfo culture = CultureInfo.CurrentCulture;
while (culture != CultureInfo.InvariantCulture) {
library = GetPerformanceCounterLib(machine, culture);
if (library.FindCustomCategory(category, out categoryType))
return categoryType;
culture = culture.Parent;
}
}
}
return categoryType;
}
/*
// Creates a category with an ini file supplied by the user. Currently this is not available.
internal static void RegisterCategory(string machineName, string categoryName, string categoryHelp, CounterCreationDataCollection creationData, string localizedIniFilePath) {
bool iniRegistered = false;
CreateRegistryEntry(machineName, categoryName, creationData, ref iniRegistered);
if (!iniRegistered)
RegisterFiles(machineName, localizedIniFilePath, false);
CloseAllTables();
}
*/
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void RegisterCategory(string categoryName, PerformanceCounterCategoryType categoryType, string categoryHelp, CounterCreationDataCollection creationData) {
try {
bool iniRegistered = false;
CreateRegistryEntry(categoryName, categoryType, creationData, ref iniRegistered);
if (!iniRegistered) {
string[] languageIds = GetLanguageIds();
CreateIniFile(categoryName, categoryHelp, creationData, languageIds);
CreateSymbolFile(creationData);
RegisterFiles(IniFilePath, false);
}
CloseAllTables();
CloseAllLibraries();
}
finally {
DeleteTemporaryFiles();
}
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private static void RegisterFiles(string arg0, bool unregister) {
Process p;
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.UseShellExecute = false;
processStartInfo.CreateNoWindow = true;
processStartInfo.ErrorDialog = false;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.WorkingDirectory = Environment.SystemDirectory;
if (unregister)
processStartInfo.FileName = Environment.SystemDirectory + "\\unlodctr.exe";
else
processStartInfo.FileName = Environment.SystemDirectory + "\\lodctr.exe";
int res = 0;
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
try {
processStartInfo.Arguments = "\"" + arg0 + "\"";
p = Process.Start(processStartInfo);
p.WaitForExit();
res = p.ExitCode;
}
finally {
SecurityPermission.RevertAssert();
}
if (res == NativeMethods.ERROR_ACCESS_DENIED) {
throw new UnauthorizedAccessException(SR.GetString(SR.CantChangeCategoryRegistration, arg0));
}
// Look at Q269225, unlodctr might return 2 when WMI is not installed.
if (unregister && res == 2)
res = 0;
if (res != 0)
throw SharedUtils.CreateSafeWin32Exception(res);
}
internal static void UnregisterCategory(string categoryName) {
RegisterFiles(categoryName, true);
DeleteRegistryEntry(categoryName);
CloseAllTables();
CloseAllLibraries();
}
}
internal class PerformanceMonitor {
private RegistryKey perfDataKey = null;
private string machineName;
internal PerformanceMonitor(string machineName) {
this.machineName = machineName;
Init();
}
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
private void Init() {
try {
if (machineName != "." && String.Compare(machineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase) != 0) {
new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
perfDataKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, machineName);
}
else
perfDataKey = Registry.PerformanceData;
}
catch (UnauthorizedAccessException) {
// we need to do this for compatibility with v1.1 and v1.0.
throw new Win32Exception(NativeMethods.ERROR_ACCESS_DENIED);
}
catch (IOException e) {
// we need to do this for compatibility with v1.1 and v1.0.
throw new Win32Exception(Marshal.GetHRForException(e));
}
}
internal void Close() {
if( perfDataKey != null)
perfDataKey.Close();
perfDataKey = null;
}
// Win32 RegQueryValueEx for perf data could deadlock (for a Mutex) up to 2mins in some
// scenarios before they detect it and exit gracefully. In the mean time, ERROR_BUSY,
// ERROR_NOT_READY etc can be seen by other concurrent calls (which is the reason for the
// wait loop and switch case below). We want to wait most certainly more than a 2min window.
// The curent wait time of up to 10mins takes care of the known stress deadlock issues. In most
// cases we wouldn't wait for more than 2mins anyways but in worst cases how much ever time
// we wait may not be sufficient if the Win32 code keeps running into this deadlock again
// and again. A condition very rare but possible in theory. We would get back to the user
// in this case with InvalidOperationException after the wait time expires.
internal byte[] GetData(string item) {
int waitRetries = 17; //2^16*10ms == approximately 10mins
int waitSleep = 0;
byte[] data = null;
int error = 0;
// no need to revert here since we'll fall off the end of the method
new RegistryPermission(PermissionState.Unrestricted).Assert();
while (waitRetries > 0) {
try {
data = (byte[]) perfDataKey.GetValue(item);
return data;
}
catch (IOException e) {
error = Marshal.GetHRForException(e);
switch (error) {
case NativeMethods.RPC_S_CALL_FAILED:
case NativeMethods.ERROR_INVALID_HANDLE:
case NativeMethods.RPC_S_SERVER_UNAVAILABLE:
Init();
goto case NativeMethods.WAIT_TIMEOUT;
case NativeMethods.WAIT_TIMEOUT:
case NativeMethods.ERROR_NOT_READY:
case NativeMethods.ERROR_LOCK_FAILED:
case NativeMethods.ERROR_BUSY:
--waitRetries;
if (waitSleep == 0) {
waitSleep = 10;
}
else {
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
break;
default:
throw SharedUtils.CreateSafeWin32Exception(error);
}
}
catch (InvalidCastException e) {
throw new InvalidOperationException(SR.GetString(SR.CounterDataCorrupt, perfDataKey.ToString()), e);
}
}
throw SharedUtils.CreateSafeWin32Exception(error);
}
}
internal class CategoryEntry {
internal int NameIndex;
internal int HelpIndex;
internal int[] CounterIndexes;
internal int[] HelpIndexes;
internal CategoryEntry(NativeMethods.PERF_OBJECT_TYPE perfObject) {
this.NameIndex = perfObject.ObjectNameTitleIndex;
this.HelpIndex = perfObject.ObjectHelpTitleIndex;
this.CounterIndexes = new int[perfObject.NumCounters];
this.HelpIndexes = new int[perfObject.NumCounters];
}
}
internal class CategorySample {
internal readonly long SystemFrequency;
internal readonly long TimeStamp;
internal readonly long TimeStamp100nSec;
internal readonly long CounterFrequency;
internal readonly long CounterTimeStamp;
internal Hashtable CounterTable;
internal Hashtable InstanceNameTable;
internal bool IsMultiInstance;
private CategoryEntry entry;
private PerformanceCounterLib library;
internal unsafe CategorySample(byte[] data, CategoryEntry entry, PerformanceCounterLib library) {
this.entry = entry;
this.library = library;
int categoryIndex = entry.NameIndex;
NativeMethods.PERF_DATA_BLOCK dataBlock = new NativeMethods.PERF_DATA_BLOCK();
fixed (byte* dataPtr = data) {
IntPtr dataRef = new IntPtr((void*) dataPtr);
Marshal.PtrToStructure(dataRef, dataBlock);
this.SystemFrequency = dataBlock.PerfFreq;
this.TimeStamp = dataBlock.PerfTime;
this.TimeStamp100nSec = dataBlock.PerfTime100nSec;
dataRef = (IntPtr)((long)dataRef + dataBlock.HeaderLength);
int numPerfObjects = dataBlock.NumObjectTypes;
if (numPerfObjects == 0) {
this.CounterTable = new Hashtable();
this.InstanceNameTable = new Hashtable(StringComparer.OrdinalIgnoreCase);
return;
}
//Need to find the right category, GetPerformanceData might return
//several of them.
NativeMethods.PERF_OBJECT_TYPE perfObject = null;
bool foundCategory = false;
for (int index = 0; index < numPerfObjects; index++) {
perfObject = new NativeMethods.PERF_OBJECT_TYPE();
Marshal.PtrToStructure(dataRef, perfObject);
if (perfObject.ObjectNameTitleIndex == categoryIndex) {
foundCategory = true;
break;
}
dataRef = (IntPtr)((long)dataRef + perfObject.TotalByteLength);
}
if (!foundCategory)
throw new InvalidOperationException(SR.GetString(SR.CantReadCategoryIndex, categoryIndex.ToString(CultureInfo.CurrentCulture)));
this.CounterFrequency = perfObject.PerfFreq;
this.CounterTimeStamp = perfObject.PerfTime;
int counterNumber = perfObject.NumCounters;
int instanceNumber = perfObject.NumInstances;
if (instanceNumber == -1)
IsMultiInstance = false;
else
IsMultiInstance = true;
// Move pointer forward to end of PERF_OBJECT_TYPE
dataRef = (IntPtr)((long)dataRef + perfObject.HeaderLength);
CounterDefinitionSample[] samples = new CounterDefinitionSample[counterNumber];
this.CounterTable = new Hashtable(counterNumber);
for (int index = 0; index < samples.Length; ++ index) {
NativeMethods.PERF_COUNTER_DEFINITION perfCounter = new NativeMethods.PERF_COUNTER_DEFINITION();
Marshal.PtrToStructure(dataRef, perfCounter);
samples[index] = new CounterDefinitionSample(perfCounter, this, instanceNumber);
dataRef = (IntPtr)((long)dataRef + perfCounter.ByteLength);
int currentSampleType = samples[index].CounterType;
if (!PerformanceCounterLib.IsBaseCounter(currentSampleType)) {
// We'll put only non-base counters in the table.
if (currentSampleType != NativeMethods.PERF_COUNTER_NODATA)
this.CounterTable[samples[index].NameIndex] = samples[index];
}
else {
// it's a base counter, try to hook it up to the main counter.
Debug.Assert(index > 0, "Index > 0 because base counters should never be at index 0");
if (index > 0)
samples[index-1].BaseCounterDefinitionSample = samples[index];
}
}
// now set up the InstanceNameTable.
if (!IsMultiInstance) {
this.InstanceNameTable = new Hashtable(1, StringComparer.OrdinalIgnoreCase);
this.InstanceNameTable[PerformanceCounterLib.SingleInstanceName] = 0;
for (int index = 0; index < samples.Length; ++ index) {
samples[index].SetInstanceValue(0, dataRef);
}
}
else {
string[] parentInstanceNames = null;
this.InstanceNameTable = new Hashtable(instanceNumber, StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < instanceNumber; i++) {
NativeMethods.PERF_INSTANCE_DEFINITION perfInstance = new NativeMethods.PERF_INSTANCE_DEFINITION();
Marshal.PtrToStructure(dataRef, perfInstance);
if (perfInstance.ParentObjectTitleIndex > 0 && parentInstanceNames == null)
parentInstanceNames = GetInstanceNamesFromIndex(perfInstance.ParentObjectTitleIndex);
string instanceName;
if (parentInstanceNames != null && perfInstance.ParentObjectInstance >= 0 && perfInstance.ParentObjectInstance < parentInstanceNames.Length - 1)
instanceName = parentInstanceNames[perfInstance.ParentObjectInstance] + "/" + Marshal.PtrToStringUni((IntPtr)((long)dataRef + perfInstance.NameOffset));
else
instanceName = Marshal.PtrToStringUni((IntPtr)((long)dataRef + perfInstance.NameOffset));
//In some cases instance names are not unique (Process), same as perfmon
//generate a unique name.
string newInstanceName = instanceName;
int newInstanceNumber = 1;
while (true) {
if (!this.InstanceNameTable.ContainsKey(newInstanceName)) {
this.InstanceNameTable[newInstanceName] = i;
break;
}
else {
newInstanceName = instanceName + "#" + newInstanceNumber.ToString(CultureInfo.InvariantCulture);
++ newInstanceNumber;
}
}
dataRef = (IntPtr)((long)dataRef + perfInstance.ByteLength);
for (int index = 0; index < samples.Length; ++ index)
samples[index].SetInstanceValue(i, dataRef);
dataRef = (IntPtr)((long)dataRef + Marshal.ReadInt32(dataRef));
}
}
}
}
internal unsafe string[] GetInstanceNamesFromIndex(int categoryIndex) {
byte[] data = library.GetPerformanceData(categoryIndex.ToString(CultureInfo.InvariantCulture));
fixed (byte* dataPtr = data) {
IntPtr dataRef = new IntPtr((void*) dataPtr);
NativeMethods.PERF_DATA_BLOCK dataBlock = new NativeMethods.PERF_DATA_BLOCK();
Marshal.PtrToStructure(dataRef, dataBlock);
dataRef = (IntPtr)((long)dataRef + dataBlock.HeaderLength);
int numPerfObjects = dataBlock.NumObjectTypes;
NativeMethods.PERF_OBJECT_TYPE perfObject = null;
bool foundCategory = false;
for (int index = 0; index < numPerfObjects; index++) {
perfObject = new NativeMethods.PERF_OBJECT_TYPE();
Marshal.PtrToStructure(dataRef, perfObject);
if (perfObject.ObjectNameTitleIndex == categoryIndex) {
foundCategory = true;
break;
}
dataRef = (IntPtr)((long)dataRef + perfObject.TotalByteLength);
}
if (!foundCategory)
return new string[0];
int counterNumber = perfObject.NumCounters;
int instanceNumber = perfObject.NumInstances;
dataRef = (IntPtr)((long)dataRef + perfObject.HeaderLength);
if (instanceNumber == -1)
return new string[0];
CounterDefinitionSample[] samples = new CounterDefinitionSample[counterNumber];
for (int index = 0; index < samples.Length; ++ index) {
NativeMethods.PERF_COUNTER_DEFINITION perfCounter = new NativeMethods.PERF_COUNTER_DEFINITION();
Marshal.PtrToStructure(dataRef, perfCounter);
dataRef = (IntPtr)((long)dataRef + perfCounter.ByteLength);
}
string[] instanceNames = new string[instanceNumber];
for (int i = 0; i < instanceNumber; i++) {
NativeMethods.PERF_INSTANCE_DEFINITION perfInstance = new NativeMethods.PERF_INSTANCE_DEFINITION();
Marshal.PtrToStructure(dataRef, perfInstance);
instanceNames[i] = Marshal.PtrToStringUni((IntPtr)((long)dataRef + perfInstance.NameOffset));
dataRef = (IntPtr)((long)dataRef + perfInstance.ByteLength);
dataRef = (IntPtr)((long)dataRef + Marshal.ReadInt32(dataRef));
}
return instanceNames;
}
}
internal CounterDefinitionSample GetCounterDefinitionSample(string counter) {
for (int index = 0; index < this.entry.CounterIndexes.Length; ++ index) {
int counterIndex = entry.CounterIndexes[index];
string counterName = (string)this.library.NameTable[counterIndex];
if (counterName != null) {
if (String.Compare(counterName, counter, StringComparison.OrdinalIgnoreCase) == 0) {
CounterDefinitionSample sample = (CounterDefinitionSample)this.CounterTable[counterIndex];
if (sample == null) {
//This is a base counter and has not been added to the table
foreach (CounterDefinitionSample multiSample in this.CounterTable.Values) {
if (multiSample.BaseCounterDefinitionSample != null &&
multiSample.BaseCounterDefinitionSample.NameIndex == counterIndex)
return multiSample.BaseCounterDefinitionSample;
}
throw new InvalidOperationException(SR.GetString(SR.CounterLayout));
}
return sample;
}
}
}
throw new InvalidOperationException(SR.GetString(SR.CantReadCounter, counter));
}
internal InstanceDataCollectionCollection ReadCategory() {
#pragma warning disable 618
InstanceDataCollectionCollection data = new InstanceDataCollectionCollection();
#pragma warning restore 618
for (int index = 0; index < this.entry.CounterIndexes.Length; ++ index) {
int counterIndex = entry.CounterIndexes[index];
string name = (string)library.NameTable[counterIndex];
if (name != null && name != String.Empty) {
CounterDefinitionSample sample = (CounterDefinitionSample)this.CounterTable[counterIndex];
if (sample != null)
//If the current index refers to a counter base,
//the sample will be null
data.Add(name, sample.ReadInstanceData(name));
}
}
return data;
}
}
internal class CounterDefinitionSample {
internal readonly int NameIndex;
internal readonly int CounterType;
internal CounterDefinitionSample BaseCounterDefinitionSample;
private readonly int size;
private readonly int offset;
private long[] instanceValues;
private CategorySample categorySample;
internal CounterDefinitionSample(NativeMethods.PERF_COUNTER_DEFINITION perfCounter, CategorySample categorySample, int instanceNumber) {
this.NameIndex = perfCounter.CounterNameTitleIndex;
this.CounterType = perfCounter.CounterType;
this.offset = perfCounter.CounterOffset;
this.size = perfCounter.CounterSize;
if (instanceNumber == -1) {
this.instanceValues = new long[1];
}
else
this.instanceValues = new long[instanceNumber];
this.categorySample = categorySample;
}
private long ReadValue(IntPtr pointer) {
if (this.size == 4) {
return (long)(uint)Marshal.ReadInt32((IntPtr)((long)pointer + this.offset));
}
else if (this.size == 8) {
return (long)Marshal.ReadInt64((IntPtr)((long)pointer + this.offset));
}
return -1;
}
internal CounterSample GetInstanceValue(string instanceName) {
if (!categorySample.InstanceNameTable.ContainsKey(instanceName)) {
// Our native dll truncates instance names to 128 characters. If we can't find the instance
// with the full name, try truncating to 128 characters.
if (instanceName.Length > SharedPerformanceCounter.InstanceNameMaxLength)
instanceName = instanceName.Substring(0, SharedPerformanceCounter.InstanceNameMaxLength);
if (!categorySample.InstanceNameTable.ContainsKey(instanceName))
throw new InvalidOperationException(SR.GetString(SR.CantReadInstance, instanceName));
}
int index = (int)categorySample.InstanceNameTable[instanceName];
long rawValue = this.instanceValues[index];
long baseValue = 0;
if (this.BaseCounterDefinitionSample != null) {
CategorySample baseCategorySample = this.BaseCounterDefinitionSample.categorySample;
int baseIndex = (int)baseCategorySample.InstanceNameTable[instanceName];
baseValue = this.BaseCounterDefinitionSample.instanceValues[baseIndex];
}
return new CounterSample(rawValue,
baseValue,
categorySample.CounterFrequency,
categorySample.SystemFrequency,
categorySample.TimeStamp,
categorySample.TimeStamp100nSec,
(PerformanceCounterType)this.CounterType,
categorySample.CounterTimeStamp);
}
internal InstanceDataCollection ReadInstanceData(string counterName) {
#pragma warning disable 618
InstanceDataCollection data = new InstanceDataCollection(counterName);
#pragma warning restore 618
string[] keys = new string[categorySample.InstanceNameTable.Count];
categorySample.InstanceNameTable.Keys.CopyTo(keys, 0);
int[] indexes = new int[categorySample.InstanceNameTable.Count];
categorySample.InstanceNameTable.Values.CopyTo(indexes, 0);
for (int index = 0; index < keys.Length; ++ index) {
long baseValue = 0;
if (this.BaseCounterDefinitionSample != null) {
CategorySample baseCategorySample = this.BaseCounterDefinitionSample.categorySample;
int baseIndex = (int)baseCategorySample.InstanceNameTable[keys[index]];
baseValue = this.BaseCounterDefinitionSample.instanceValues[baseIndex];
}
CounterSample sample = new CounterSample(this.instanceValues[indexes[index]],
baseValue,
categorySample.CounterFrequency,
categorySample.SystemFrequency,
categorySample.TimeStamp,
categorySample.TimeStamp100nSec,
(PerformanceCounterType)this.CounterType,
categorySample.CounterTimeStamp);
data.Add(keys[index], new InstanceData(keys[index], sample));
}
return data;
}
internal CounterSample GetSingleValue() {
long rawValue = this.instanceValues[0];
long baseValue = 0;
if (this.BaseCounterDefinitionSample != null)
baseValue = this.BaseCounterDefinitionSample.instanceValues[0];
return new CounterSample(rawValue,
baseValue,
categorySample.CounterFrequency,
categorySample.SystemFrequency,
categorySample.TimeStamp,
categorySample.TimeStamp100nSec,
(PerformanceCounterType)this.CounterType,
categorySample.CounterTimeStamp);
}
internal void SetInstanceValue(int index, IntPtr dataRef) {
long rawValue = ReadValue(dataRef);
this.instanceValues[index] = rawValue;
}
}
}
| |
// 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.Net;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Serialization;
using System.Text;
// This HttpHandlerDiagnosticListener class is applicable only for .NET 4.6, and not for .NET core.
namespace System.Diagnostics
{
/// <summary>
/// A HttpHandlerDiagnosticListener is a DiagnosticListener for .NET 4.6 and above where
/// HttpClient doesn't have a DiagnosticListener built in. This class is not used for .NET Core
/// because HttpClient in .NET Core already emits DiagnosticSource events. This class compensates for
/// that in .NET 4.6 and above. HttpHandlerDiagnosticListener has no public constructor. To use this,
/// the application just needs to call <see cref="DiagnosticListener.AllListeners" /> and
/// <see cref="DiagnosticListener.AllListenerObservable.Subscribe(IObserver{DiagnosticListener})"/>,
/// then in the <see cref="IObserver{DiagnosticListener}.OnNext(DiagnosticListener)"/> method,
/// when it sees the System.Net.Http.Desktop source, subscribe to it. This will trigger the
/// initialization of this DiagnosticListener.
/// </summary>
internal sealed class HttpHandlerDiagnosticListener : DiagnosticListener
{
/// <summary>
/// Overriding base class implementation just to give us a chance to initialize.
/// </summary>
public override IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled)
{
IDisposable result = base.Subscribe(observer, isEnabled);
Initialize();
return result;
}
/// <summary>
/// Overriding base class implementation just to give us a chance to initialize.
/// </summary>
public override IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Func<string, object, object, bool> isEnabled)
{
IDisposable result = base.Subscribe(observer, isEnabled);
Initialize();
return result;
}
/// <summary>
/// Overriding base class implementation just to give us a chance to initialize.
/// </summary>
public override IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer)
{
IDisposable result = base.Subscribe(observer);
Initialize();
return result;
}
/// <summary>
/// Initializes all the reflection objects it will ever need. Reflection is costly, but it's better to take
/// this one time performance hit than to get it multiple times later, or do it lazily and have to worry about
/// threading issues. If Initialize has been called before, it will not doing anything.
/// </summary>
private void Initialize()
{
lock (this)
{
if (!this.initialized)
{
try
{
// This flag makes sure we only do this once. Even if we failed to initialize in an
// earlier time, we should not retry because this initialization is not cheap and
// the likelihood it will succeed the second time is very small.
this.initialized = true;
PrepareReflectionObjects();
PerformInjection();
}
catch (Exception ex)
{
// If anything went wrong, just no-op. Write an event so at least we can find out.
this.Write(InitializationFailed, new { Exception = ex });
}
}
}
}
#region private helper classes
private class HashtableWrapper : Hashtable, IEnumerable
{
protected Hashtable _table;
public override int Count
{
get
{
return this._table.Count;
}
}
public override bool IsReadOnly
{
get
{
return this._table.IsReadOnly;
}
}
public override bool IsFixedSize
{
get
{
return this._table.IsFixedSize;
}
}
public override bool IsSynchronized
{
get
{
return this._table.IsSynchronized;
}
}
public override object this[object key]
{
get
{
return this._table[key];
}
set
{
this._table[key] = value;
}
}
public override object SyncRoot
{
get
{
return this._table.SyncRoot;
}
}
public override ICollection Keys
{
get
{
return this._table.Keys;
}
}
public override ICollection Values
{
get
{
return this._table.Values;
}
}
internal HashtableWrapper(Hashtable table) : base()
{
this._table = table;
}
public override void Add(object key, object value)
{
this._table.Add(key, value);
}
public override void Clear()
{
this._table.Clear();
}
public override bool Contains(object key)
{
return this._table.Contains(key);
}
public override bool ContainsKey(object key)
{
return this._table.ContainsKey(key);
}
public override bool ContainsValue(object key)
{
return this._table.ContainsValue(key);
}
public override void CopyTo(Array array, int arrayIndex)
{
this._table.CopyTo(array, arrayIndex);
}
public override object Clone()
{
return new HashtableWrapper((Hashtable)this._table.Clone());
}
IEnumerator IEnumerable.GetEnumerator()
{
return this._table.GetEnumerator();
}
public override IDictionaryEnumerator GetEnumerator()
{
return this._table.GetEnumerator();
}
public override void Remove(object key)
{
this._table.Remove(key);
}
}
/// <summary>
/// Helper class used for ServicePointManager.s_ServicePointTable. The goal here is to
/// intercept each new ServicePoint object being added to ServicePointManager.s_ServicePointTable
/// and replace its ConnectionGroupList hashtable field.
/// </summary>
private sealed class ServicePointHashtable : HashtableWrapper
{
public ServicePointHashtable(Hashtable table) : base(table)
{
}
public override object this[object key]
{
get
{
return base[key];
}
set
{
WeakReference weakRef = value as WeakReference;
if (weakRef != null && weakRef.IsAlive)
{
ServicePoint servicePoint = weakRef.Target as ServicePoint;
if (servicePoint != null)
{
// Replace the ConnectionGroup hashtable inside this ServicePoint object,
// which allows us to intercept each new ConnectionGroup object added under
// this ServicePoint.
Hashtable originalTable = s_connectionGroupListField.GetValue(servicePoint) as Hashtable;
ConnectionGroupHashtable newTable = new ConnectionGroupHashtable(originalTable ?? new Hashtable());
s_connectionGroupListField.SetValue(servicePoint, newTable);
}
}
base[key] = value;
}
}
}
/// <summary>
/// Helper class used for ServicePoint.m_ConnectionGroupList. The goal here is to
/// intercept each new ConnectionGroup object being added to ServicePoint.m_ConnectionGroupList
/// and replace its m_ConnectionList arraylist field.
/// </summary>
private sealed class ConnectionGroupHashtable : HashtableWrapper
{
public ConnectionGroupHashtable(Hashtable table) : base(table)
{
}
public override object this[object key]
{
get
{
return base[key];
}
set
{
if (s_connectionGroupType.IsInstanceOfType(value))
{
// Replace the Connection arraylist inside this ConnectionGroup object,
// which allows us to intercept each new Connection object added under
// this ConnectionGroup.
ArrayList originalArrayList = s_connectionListField.GetValue(value) as ArrayList;
ConnectionArrayList newArrayList = new ConnectionArrayList(originalArrayList ?? new ArrayList());
s_connectionListField.SetValue(value, newArrayList);
}
base[key] = value;
}
}
}
/// <summary>
/// Helper class used to wrap the array list object. This class itself doesn't actually
/// have the array elements, but rather access another array list that's given at
/// construction time.
/// </summary>
private class ArrayListWrapper : ArrayList
{
private ArrayList _list;
public override int Capacity
{
get
{
return this._list.Capacity;
}
set
{
this._list.Capacity = value;
}
}
public override int Count
{
get
{
return this._list.Count;
}
}
public override bool IsReadOnly
{
get
{
return this._list.IsReadOnly;
}
}
public override bool IsFixedSize
{
get
{
return this._list.IsFixedSize;
}
}
public override bool IsSynchronized
{
get
{
return this._list.IsSynchronized;
}
}
public override object this[int index]
{
get
{
return this._list[index];
}
set
{
this._list[index] = value;
}
}
public override object SyncRoot
{
get
{
return this._list.SyncRoot;
}
}
internal ArrayListWrapper(ArrayList list) : base()
{
this._list = list;
}
public override int Add(object value)
{
return this._list.Add(value);
}
public override void AddRange(ICollection c)
{
this._list.AddRange(c);
}
public override int BinarySearch(object value)
{
return this._list.BinarySearch(value);
}
public override int BinarySearch(object value, IComparer comparer)
{
return this._list.BinarySearch(value, comparer);
}
public override int BinarySearch(int index, int count, object value, IComparer comparer)
{
return this._list.BinarySearch(index, count, value, comparer);
}
public override void Clear()
{
this._list.Clear();
}
public override object Clone()
{
return new ArrayListWrapper((ArrayList)this._list.Clone());
}
public override bool Contains(object item)
{
return this._list.Contains(item);
}
public override void CopyTo(Array array)
{
this._list.CopyTo(array);
}
public override void CopyTo(Array array, int index)
{
this._list.CopyTo(array, index);
}
public override void CopyTo(int index, Array array, int arrayIndex, int count)
{
this._list.CopyTo(index, array, arrayIndex, count);
}
public override IEnumerator GetEnumerator()
{
return this._list.GetEnumerator();
}
public override IEnumerator GetEnumerator(int index, int count)
{
return this._list.GetEnumerator(index, count);
}
public override int IndexOf(object value)
{
return this._list.IndexOf(value);
}
public override int IndexOf(object value, int startIndex)
{
return this._list.IndexOf(value, startIndex);
}
public override int IndexOf(object value, int startIndex, int count)
{
return this._list.IndexOf(value, startIndex, count);
}
public override void Insert(int index, object value)
{
this._list.Insert(index, value);
}
public override void InsertRange(int index, ICollection c)
{
this._list.InsertRange(index, c);
}
public override int LastIndexOf(object value)
{
return this._list.LastIndexOf(value);
}
public override int LastIndexOf(object value, int startIndex)
{
return this._list.LastIndexOf(value, startIndex);
}
public override int LastIndexOf(object value, int startIndex, int count)
{
return this._list.LastIndexOf(value, startIndex, count);
}
public override void Remove(object value)
{
this._list.Remove(value);
}
public override void RemoveAt(int index)
{
this._list.RemoveAt(index);
}
public override void RemoveRange(int index, int count)
{
this._list.RemoveRange(index, count);
}
public override void Reverse(int index, int count)
{
this._list.Reverse(index, count);
}
public override void SetRange(int index, ICollection c)
{
this._list.SetRange(index, c);
}
public override ArrayList GetRange(int index, int count)
{
return this._list.GetRange(index, count);
}
public override void Sort()
{
this._list.Sort();
}
public override void Sort(IComparer comparer)
{
this._list.Sort(comparer);
}
public override void Sort(int index, int count, IComparer comparer)
{
this._list.Sort(index, count, comparer);
}
public override object[] ToArray()
{
return this._list.ToArray();
}
public override Array ToArray(Type type)
{
return this._list.ToArray(type);
}
public override void TrimToSize()
{
this._list.TrimToSize();
}
}
/// <summary>
/// Helper class used for ConnectionGroup.m_ConnectionList. The goal here is to
/// intercept each new Connection object being added to ConnectionGroup.m_ConnectionList
/// and replace its m_WriteList arraylist field.
/// </summary>
private sealed class ConnectionArrayList : ArrayListWrapper
{
public ConnectionArrayList(ArrayList list) : base(list)
{
}
public override int Add(object value)
{
if (s_connectionType.IsInstanceOfType(value))
{
// Replace the HttpWebRequest arraylist inside this Connection object,
// which allows us to intercept each new HttpWebRequest object added under
// this Connection.
ArrayList originalArrayList = s_writeListField.GetValue(value) as ArrayList;
HttpWebRequestArrayList newArrayList = new HttpWebRequestArrayList(originalArrayList ?? new ArrayList());
s_writeListField.SetValue(value, newArrayList);
}
return base.Add(value);
}
}
/// <summary>
/// Helper class used for Connection.m_WriteList. The goal here is to
/// intercept all new HttpWebRequest objects being added to Connection.m_WriteList
/// and notify the listener about the HttpWebRequest that's about to send a request.
/// It also intercepts all HttpWebRequest objects that are about to get removed from
/// Connection.m_WriteList as they have completed the request.
/// </summary>
private sealed class HttpWebRequestArrayList : ArrayListWrapper
{
public HttpWebRequestArrayList(ArrayList list) : base(list)
{
}
public override int Add(object value)
{
HttpWebRequest request = value as HttpWebRequest;
if (request != null)
{
s_instance.RaiseRequestEvent(request);
}
return base.Add(value);
}
public override void RemoveAt(int index)
{
HttpWebRequest request = base[index] as HttpWebRequest;
if (request != null)
{
HttpWebResponse response = s_httpResponseAccessor(request);
if (response != null)
{
s_instance.RaiseResponseEvent(request, response);
}
else
{
// In case reponse content length is 0 and request is async,
// we won't have a HttpWebResponse set on request object when this method is called
// http://referencesource.microsoft.com/#System/net/System/Net/HttpWebResponse.cs,525
// But we there will be CoreResponseData object that is either exception
// or the internal HTTP reponse representation having status, content and headers
var coreResponse = s_coreResponseAccessor(request);
if (coreResponse != null && s_coreResponseDataType.IsInstanceOfType(coreResponse))
{
HttpStatusCode status = s_coreStatusCodeAccessor(coreResponse);
WebHeaderCollection headers = s_coreHeadersAccessor(coreResponse);
// Manual creation of HttpWebResponse here is not possible as this method is eventually called from the
// HttpWebResponse ctor. So we will send Stop event with the Status and Headers payload
// to notify listeners about response;
// We use two different names for Stop events since one event with payload type that varies creates
// complications for efficient payload parsing and is not supported by DiagnosicSource helper
// libraries (e.g. Microsoft.Extensions.DiagnosticAdapter)
s_instance.RaiseResponseEvent(request, status, headers);
}
}
}
base.RemoveAt(index);
}
}
#endregion
#region private methods
/// <summary>
/// Private constructor. This class implements a singleton pattern and only this class is allowed to create an instance.
/// </summary>
private HttpHandlerDiagnosticListener() : base(DiagnosticListenerName)
{
}
private void RaiseRequestEvent(HttpWebRequest request)
{
if (request.Headers.Get(RequestIdHeaderName) != null)
{
// this request was instrumented by previous RaiseRequestEvent
return;
}
if (this.IsEnabled(ActivityName, request))
{
var activity = new Activity(ActivityName);
// Only send start event to users who subscribed for it, but start activity anyway
if (this.IsEnabled(RequestStartName))
{
this.StartActivity(activity, new { Request = request });
}
else
{
activity.Start();
}
if (activity.IdFormat == ActivityIdFormat.W3C)
{
// do not inject header if it was injected already
// perhaps tracing systems wants to override it
if (request.Headers.Get(TraceParentHeaderName) == null)
{
request.Headers.Add(TraceParentHeaderName, activity.Id);
var traceState = activity.TraceStateString;
if (traceState != null)
{
request.Headers.Add(TraceStateHeaderName, traceState);
}
}
}
else
{
// do not inject header if it was injected already
// perhaps tracing systems wants to override it
if (request.Headers.Get(RequestIdHeaderName) == null)
{
request.Headers.Add(RequestIdHeaderName, activity.Id);
}
}
if (request.Headers.Get(CorrelationContextHeaderName) == null)
{
// we expect baggage to be empty or contain a few items
using (IEnumerator<KeyValuePair<string, string>> e = activity.Baggage.GetEnumerator())
{
if (e.MoveNext())
{
StringBuilder baggage = new StringBuilder();
do
{
KeyValuePair<string, string> item = e.Current;
baggage.Append(WebUtility.UrlEncode(item.Key)).Append('=').Append(WebUtility.UrlEncode(item.Value)).Append(',');
}
while (e.MoveNext());
baggage.Remove(baggage.Length - 1, 1);
request.Headers.Add(CorrelationContextHeaderName, baggage.ToString());
}
}
}
// There is no guarantee that Activity.Current will flow to the Response, so let's stop it here
activity.Stop();
}
}
private void RaiseResponseEvent(HttpWebRequest request, HttpWebResponse response)
{
// Response event could be received several times for the same request in case it was redirected
// IsLastResponse checks if response is the last one (no more redirects will happen)
// based on response StatusCode and number or redirects done so far
bool wasRequestInstrumented = request.Headers.Get(TraceParentHeaderName) != null || request.Headers.Get(RequestIdHeaderName) != null;
if (wasRequestInstrumented && IsLastResponse(request, response.StatusCode))
{
// only send Stop if request was instrumented
this.Write(RequestStopName, new { Request = request, Response = response });
}
}
private void RaiseResponseEvent(HttpWebRequest request, HttpStatusCode statusCode, WebHeaderCollection headers)
{
// Response event could be received several times for the same request in case it was redirected
// IsLastResponse checks if response is the last one (no more redirects will happen)
// based on response StatusCode and number or redirects done so far
if (request.Headers.Get(RequestIdHeaderName) != null && IsLastResponse(request, statusCode))
{
this.Write(RequestStopExName, new { Request = request, StatusCode = statusCode, Headers = headers });
}
}
private bool IsLastResponse(HttpWebRequest request, HttpStatusCode statusCode)
{
if (request.AllowAutoRedirect)
{
if (statusCode == HttpStatusCode.Ambiguous || // 300
statusCode == HttpStatusCode.Moved || // 301
statusCode == HttpStatusCode.Redirect || // 302
statusCode == HttpStatusCode.RedirectMethod || // 303
statusCode == HttpStatusCode.RedirectKeepVerb || // 307
(int)statusCode == 308) // 308 Permanent Redirect is not in netfx yet, and so has to be specified this way.
{
return s_autoRedirectsAccessor(request) >= request.MaximumAutomaticRedirections;
}
}
return true;
}
private static void PrepareReflectionObjects()
{
// At any point, if the operation failed, it should just throw. The caller should catch all exceptions and swallow.
// First step: Get all the reflection objects we will ever need.
Assembly systemNetHttpAssembly = typeof(ServicePoint).Assembly;
s_connectionGroupListField = typeof(ServicePoint).GetField("m_ConnectionGroupList", BindingFlags.Instance | BindingFlags.NonPublic);
s_connectionGroupType = systemNetHttpAssembly?.GetType("System.Net.ConnectionGroup");
s_connectionListField = s_connectionGroupType?.GetField("m_ConnectionList", BindingFlags.Instance | BindingFlags.NonPublic);
s_connectionType = systemNetHttpAssembly?.GetType("System.Net.Connection");
s_writeListField = s_connectionType?.GetField("m_WriteList", BindingFlags.Instance | BindingFlags.NonPublic);
s_httpResponseAccessor = CreateFieldGetter<HttpWebRequest, HttpWebResponse>("_HttpResponse", BindingFlags.NonPublic | BindingFlags.Instance);
s_autoRedirectsAccessor = CreateFieldGetter<HttpWebRequest, int>("_AutoRedirects", BindingFlags.NonPublic | BindingFlags.Instance);
s_coreResponseAccessor = CreateFieldGetter<HttpWebRequest, object>("_CoreResponse", BindingFlags.NonPublic | BindingFlags.Instance);
s_coreResponseDataType = systemNetHttpAssembly?.GetType("System.Net.CoreResponseData");
if (s_coreResponseDataType != null)
{
s_coreStatusCodeAccessor = CreateFieldGetter<HttpStatusCode>(s_coreResponseDataType, "m_StatusCode", BindingFlags.Public | BindingFlags.Instance);
s_coreHeadersAccessor = CreateFieldGetter<WebHeaderCollection>(s_coreResponseDataType, "m_ResponseHeaders", BindingFlags.Public | BindingFlags.Instance);
}
// Double checking to make sure we have all the pieces initialized
if (s_connectionGroupListField == null ||
s_connectionGroupType == null ||
s_connectionListField == null ||
s_connectionType == null ||
s_writeListField == null ||
s_httpResponseAccessor == null ||
s_autoRedirectsAccessor == null ||
s_coreResponseDataType == null ||
s_coreStatusCodeAccessor == null ||
s_coreHeadersAccessor == null)
{
// If anything went wrong here, just return false. There is nothing we can do.
throw new InvalidOperationException("Unable to initialize all required reflection objects");
}
}
private static void PerformInjection()
{
FieldInfo servicePointTableField = typeof(ServicePointManager).GetField("s_ServicePointTable", BindingFlags.Static | BindingFlags.NonPublic);
if (servicePointTableField == null)
{
// If anything went wrong here, just return false. There is nothing we can do.
throw new InvalidOperationException("Unable to access the ServicePointTable field");
}
Hashtable originalTable = servicePointTableField.GetValue(null) as Hashtable;
ServicePointHashtable newTable = new ServicePointHashtable(originalTable ?? new Hashtable());
servicePointTableField.SetValue(null, newTable);
}
private static Func<TClass, TField> CreateFieldGetter<TClass, TField>(string fieldName, BindingFlags flags) where TClass : class
{
FieldInfo field = typeof(TClass).GetField(fieldName, flags);
if (field != null)
{
string methodName = field.ReflectedType.FullName + ".get_" + field.Name;
DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new[] { typeof(TClass) }, true);
ILGenerator generator = getterMethod.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldfld, field);
generator.Emit(OpCodes.Ret);
return (Func<TClass, TField>)getterMethod.CreateDelegate(typeof(Func<TClass, TField>));
}
return null;
}
/// <summary>
/// Creates getter for a field defined in private or internal type
/// repesented with classType variable
/// </summary>
private static Func<object, TField> CreateFieldGetter<TField>(Type classType, string fieldName, BindingFlags flags)
{
FieldInfo field = classType.GetField(fieldName, flags);
if (field != null)
{
string methodName = classType.FullName + ".get_" + field.Name;
DynamicMethod getterMethod = new DynamicMethod(methodName, typeof(TField), new[] { typeof(object) }, true);
ILGenerator generator = getterMethod.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclass, classType);
generator.Emit(OpCodes.Ldfld, field);
generator.Emit(OpCodes.Ret);
return (Func<object, TField>)getterMethod.CreateDelegate(typeof(Func<object, TField>));
}
return null;
}
#endregion
internal static HttpHandlerDiagnosticListener s_instance = new HttpHandlerDiagnosticListener();
#region private fields
private const string DiagnosticListenerName = "System.Net.Http.Desktop";
private const string ActivityName = "System.Net.Http.Desktop.HttpRequestOut";
private const string RequestStartName = "System.Net.Http.Desktop.HttpRequestOut.Start";
private const string RequestStopName = "System.Net.Http.Desktop.HttpRequestOut.Stop";
private const string RequestStopExName = "System.Net.Http.Desktop.HttpRequestOut.Ex.Stop";
private const string InitializationFailed = "System.Net.Http.InitializationFailed";
private const string RequestIdHeaderName = "Request-Id";
private const string CorrelationContextHeaderName = "Correlation-Context";
private const string TraceParentHeaderName = "traceparent";
private const string TraceStateHeaderName = "tracestate";
// Fields for controlling initialization of the HttpHandlerDiagnosticListener singleton
private bool initialized = false;
// Fields for reflection
private static FieldInfo s_connectionGroupListField;
private static Type s_connectionGroupType;
private static FieldInfo s_connectionListField;
private static Type s_connectionType;
private static FieldInfo s_writeListField;
private static Func<HttpWebRequest, HttpWebResponse> s_httpResponseAccessor;
private static Func<HttpWebRequest, int> s_autoRedirectsAccessor;
private static Func<HttpWebRequest, object> s_coreResponseAccessor;
private static Func<object, HttpStatusCode> s_coreStatusCodeAccessor;
private static Func<object, WebHeaderCollection> s_coreHeadersAccessor;
private static Type s_coreResponseDataType;
#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 NPOI.HSSF.UserModel
{
using System;
using System.Collections;
using NPOI.HSSF.Model;
using NPOI.HSSF.Record;
using System.Collections.Generic;
using NPOI.SS.UserModel;
/*
* Identifies both built-in and user defined formats within a workbook.<p/>
* See {@link BuiltinFormats} for a list of supported built-in formats.<p/>
*
* <b>International Formats</b><br/>
* Since version 2003 Excel has supported international formats. These are denoted
* with a prefix "[$-xxx]" (where xxx is a 1-7 digit hexadecimal number).
* See the Microsoft article
* <a href="http://office.microsoft.com/assistance/hfws.aspx?AssetID=HA010346351033&CTT=6&Origin=EC010272491033">
* Creating international number formats
* </a> for more details on these codes.
*
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Shawn M. Laubach (slaubach at apache dot org)
*/
[Serializable]
public class HSSFDataFormat : IDataFormat
{
/**
* The first user-defined format starts at 164.
*/
public const int FIRST_USER_DEFINED_FORMAT_INDEX = 164;
private static List<string> builtinFormats = new List<string>(BuiltinFormats.GetAll());
private List<string> formats = new List<string>();
private InternalWorkbook workbook;
private bool movedBuiltins = false; // Flag to see if need to
// Check the built in list
// or if the regular list
// has all entries.
/// <summary>
/// Construncts a new data formatter. It takes a workbook to have
/// access to the workbooks format records.
/// </summary>
/// <param name="workbook">the workbook the formats are tied to.</param>
public HSSFDataFormat(InternalWorkbook workbook)
{
this.workbook = workbook;
IEnumerator i = workbook.Formats.GetEnumerator();
while (i.MoveNext())
{
FormatRecord r = (FormatRecord)i.Current;
for (int j = formats.Count; formats.Count <= r.IndexCode; j++)
{
formats.Add(null);
}
formats[r.IndexCode] = r.FormatString;
}
}
public static List<string> GetBuiltinFormats()
{
return builtinFormats;
}
/// <summary>
/// Get the format index that matches the given format string
/// Automatically Converts "text" to excel's format string to represent text.
/// </summary>
/// <param name="format">The format string matching a built in format.</param>
/// <returns>index of format or -1 if Undefined.</returns>
public static short GetBuiltinFormat(String format)
{
if (format.ToUpper().Equals("TEXT"))
format = "@";
short retval = -1;
for (short k = 0; k <= 0x31; k++)
{
String nformat = (String)builtinFormats[k];
if ((nformat != null) && nformat.Equals(format))
{
retval = k;
break;
}
}
return retval;
}
/// <summary>
/// Get the format index that matches the given format
/// string, creating a new format entry if required.
/// Aliases text to the proper format as required.
/// </summary>
/// <param name="pFormat">The format string matching a built in format.</param>
/// <returns>index of format.</returns>
public short GetFormat(String pFormat)
{
IEnumerator i;
int ind;
String format;
if (pFormat.ToUpper().Equals("TEXT"))
{
format = "@";
}
else
{
format = pFormat;
}
if (!movedBuiltins)
{
i = builtinFormats.GetEnumerator();
ind = 0;
while (i.MoveNext())
{
for (int j = formats.Count; formats.Count < ind + 1; j++)
{
formats.Add(null);
}
formats[ind] = i.Current as string;
ind++;
}
movedBuiltins = true;
}
i = formats.GetEnumerator();
ind = 0;
while (i.MoveNext())
{
if (format.Equals(i.Current))
return (short)ind;
ind++;
}
ind = workbook.GetFormat(format, true);
for (int j = formats.Count; formats.Count < ind + 1; j++)
{
formats.Add(null);
}
formats[ind] = format;
return (short)ind;
}
/// <summary>
/// Get the format string that matches the given format index
/// </summary>
/// <param name="index">The index of a format.</param>
/// <returns>string represented at index of format or null if there Is not a format at that index</returns>
public String GetFormat(short index)
{
if (movedBuiltins)
return (String)formats[index];
if (index == -1)
return null;
String fmt = formats.Count > index ? formats[index] : null;
if (builtinFormats.Count > index
&& builtinFormats[index] != null)
{
// It's in the built in range
if (fmt != null)
{
// It's been overriden, use that value
return fmt;
}
else
{
// Standard built in format
return builtinFormats[index];
}
}
return fmt;
}
/// <summary>
/// Get the format string that matches the given format index
/// </summary>
/// <param name="index">The index of a built in format.</param>
/// <returns>string represented at index of format or null if there Is not a builtin format at that index</returns>
public static String GetBuiltinFormat(short index)
{
return (String)builtinFormats[index];
}
/// <summary>
/// Get the number of builtin and reserved builtinFormats
/// </summary>
/// <returns>number of builtin and reserved builtinFormats</returns>
public static int NumberOfBuiltinBuiltinFormats
{
get
{
return builtinFormats.Count;
}
}
/**
* Ensures that the formats list can hold entries
* up to and including the entry with this index
*/
private void EnsureFormatsSize(int index)
{
if (formats.Count <= index)
{
formats.Capacity = (index + 1);
}
}
}
}
| |
// <copyright file="StatisticsTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.Random;
using MathNet.Numerics.TestData;
using NUnit.Framework;
// ReSharper disable InvokeAsExtensionMethod
namespace MathNet.Numerics.UnitTests.StatisticsTests
{
using Statistics;
/// <summary>
/// Statistics Tests
/// </summary>
[TestFixture, Category("Statistics")]
public class StatisticsTests
{
readonly IDictionary<string, StatTestData> _data = new Dictionary<string, StatTestData>
{
{ "lottery", new StatTestData("NIST.Lottery.dat") },
{ "lew", new StatTestData("NIST.Lew.dat") },
{ "mavro", new StatTestData("NIST.Mavro.dat") },
{ "michelso", new StatTestData("NIST.Michelso.dat") },
{ "numacc1", new StatTestData("NIST.NumAcc1.dat") },
{ "numacc2", new StatTestData("NIST.NumAcc2.dat") },
{ "numacc3", new StatTestData("NIST.NumAcc3.dat") },
{ "numacc4", new StatTestData("NIST.NumAcc4.dat") },
{ "meixner", new StatTestData("NIST.Meixner.dat") }
};
[Test]
public void ThrowsOnNullData()
{
double[] data = null;
// ReSharper disable ExpressionIsAlwaysNull
Assert.That(() => Statistics.Minimum(data), Throws.Exception);
Assert.That(() => Statistics.Maximum(data), Throws.Exception);
Assert.That(() => Statistics.Mean(data), Throws.Exception);
Assert.That(() => Statistics.HarmonicMean(data), Throws.Exception);
Assert.That(() => Statistics.GeometricMean(data), Throws.Exception);
Assert.That(() => Statistics.Median(data), Throws.Exception);
Assert.That(() => Statistics.Quantile(data, 0.3), Throws.Exception);
Assert.That(() => Statistics.Variance(data), Throws.Exception);
Assert.That(() => Statistics.StandardDeviation(data), Throws.Exception);
Assert.That(() => Statistics.PopulationVariance(data), Throws.Exception);
Assert.That(() => Statistics.PopulationStandardDeviation(data), Throws.Exception);
Assert.That(() => Statistics.Covariance(data, data), Throws.Exception);
Assert.That(() => Statistics.PopulationCovariance(data, data), Throws.Exception);
Assert.That(() => Statistics.RootMeanSquare(data), Throws.Exception);
Assert.That(() => SortedArrayStatistics.Minimum(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.Minimum(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.Maximum(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.OrderStatistic(data, 1), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.Median(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.LowerQuartile(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.UpperQuartile(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.Percentile(data, 30), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.Quantile(data, 0.3), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.QuantileCustom(data, 0.3, 0, 0, 1, 0), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.QuantileCustom(data, 0.3, QuantileDefinition.Nearest), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.InterquartileRange(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => SortedArrayStatistics.FiveNumberSummary(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.Minimum(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.Maximum(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.OrderStatisticInplace(data, 1), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.Mean(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.HarmonicMean(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.GeometricMean(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.Variance(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.StandardDeviation(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.PopulationVariance(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.PopulationStandardDeviation(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.Covariance(data, data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.PopulationCovariance(data, data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.RootMeanSquare(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.MedianInplace(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => ArrayStatistics.QuantileInplace(data, 0.3), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.Minimum(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.Maximum(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.Mean(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.HarmonicMean(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.GeometricMean(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.Variance(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.StandardDeviation(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.PopulationVariance(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.PopulationStandardDeviation(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.Covariance(data, data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.PopulationCovariance(data, data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.RootMeanSquare(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => StreamingStatistics.Entropy(data), Throws.Exception.TypeOf<NullReferenceException>());
Assert.That(() => new RunningStatistics(data), Throws.Exception);
Assert.That(() => new RunningStatistics().PushRange(data), Throws.Exception);
// ReSharper restore ExpressionIsAlwaysNull
}
[Test]
public void DoesNotThrowOnEmptyData()
{
double[] data = new double[0];
Assert.DoesNotThrow(() => Statistics.Minimum(data));
Assert.DoesNotThrow(() => Statistics.Maximum(data));
Assert.DoesNotThrow(() => Statistics.Mean(data));
Assert.DoesNotThrow(() => Statistics.HarmonicMean(data));
Assert.DoesNotThrow(() => Statistics.GeometricMean(data));
Assert.DoesNotThrow(() => Statistics.Median(data));
Assert.DoesNotThrow(() => Statistics.Quantile(data, 0.3));
Assert.DoesNotThrow(() => Statistics.Variance(data));
Assert.DoesNotThrow(() => Statistics.StandardDeviation(data));
Assert.DoesNotThrow(() => Statistics.PopulationVariance(data));
Assert.DoesNotThrow(() => Statistics.PopulationStandardDeviation(data));
Assert.DoesNotThrow(() => Statistics.Covariance(data, data));
Assert.DoesNotThrow(() => Statistics.PopulationCovariance(data, data));
Assert.DoesNotThrow(() => Statistics.RootMeanSquare(data));
Assert.DoesNotThrow(() => SortedArrayStatistics.Minimum(data));
Assert.DoesNotThrow(() => SortedArrayStatistics.Maximum(data));
Assert.DoesNotThrow(() => SortedArrayStatistics.OrderStatistic(data, 1));
Assert.DoesNotThrow(() => SortedArrayStatistics.Median(data));
Assert.DoesNotThrow(() => SortedArrayStatistics.LowerQuartile(data));
Assert.DoesNotThrow(() => SortedArrayStatistics.UpperQuartile(data));
Assert.DoesNotThrow(() => SortedArrayStatistics.Percentile(data, 30));
Assert.DoesNotThrow(() => SortedArrayStatistics.Quantile(data, 0.3));
Assert.DoesNotThrow(() => SortedArrayStatistics.QuantileCustom(data, 0.3, 0, 0, 1, 0));
Assert.DoesNotThrow(() => SortedArrayStatistics.QuantileCustom(data, 0.3, QuantileDefinition.Nearest));
Assert.DoesNotThrow(() => SortedArrayStatistics.InterquartileRange(data));
Assert.DoesNotThrow(() => SortedArrayStatistics.FiveNumberSummary(data));
Assert.DoesNotThrow(() => ArrayStatistics.Minimum(data));
Assert.DoesNotThrow(() => ArrayStatistics.Maximum(data));
Assert.DoesNotThrow(() => ArrayStatistics.OrderStatisticInplace(data, 1));
Assert.DoesNotThrow(() => ArrayStatistics.Mean(data));
Assert.DoesNotThrow(() => ArrayStatistics.Variance(data));
Assert.DoesNotThrow(() => ArrayStatistics.StandardDeviation(data));
Assert.DoesNotThrow(() => ArrayStatistics.PopulationVariance(data));
Assert.DoesNotThrow(() => ArrayStatistics.PopulationStandardDeviation(data));
Assert.DoesNotThrow(() => ArrayStatistics.Covariance(data, data));
Assert.DoesNotThrow(() => ArrayStatistics.PopulationCovariance(data, data));
Assert.DoesNotThrow(() => ArrayStatistics.RootMeanSquare(data));
Assert.DoesNotThrow(() => ArrayStatistics.MedianInplace(data));
Assert.DoesNotThrow(() => ArrayStatistics.QuantileInplace(data, 0.3));
Assert.DoesNotThrow(() => StreamingStatistics.Minimum(data));
Assert.DoesNotThrow(() => StreamingStatistics.Maximum(data));
Assert.DoesNotThrow(() => StreamingStatistics.Mean(data));
Assert.DoesNotThrow(() => StreamingStatistics.Variance(data));
Assert.DoesNotThrow(() => StreamingStatistics.StandardDeviation(data));
Assert.DoesNotThrow(() => StreamingStatistics.PopulationVariance(data));
Assert.DoesNotThrow(() => StreamingStatistics.PopulationStandardDeviation(data));
Assert.DoesNotThrow(() => StreamingStatistics.Covariance(data, data));
Assert.DoesNotThrow(() => StreamingStatistics.PopulationCovariance(data, data));
Assert.DoesNotThrow(() => StreamingStatistics.RootMeanSquare(data));
Assert.DoesNotThrow(() => StreamingStatistics.Entropy(data));
Assert.That(() => new RunningStatistics(data), Throws.Nothing);
Assert.That(() => new RunningStatistics().PushRange(data), Throws.Nothing);
Assert.That(() => new RunningStatistics(data).Minimum, Throws.Nothing);
Assert.That(() => new RunningStatistics(data).Maximum, Throws.Nothing);
Assert.That(() => new RunningStatistics(data).Mean, Throws.Nothing);
Assert.That(() => new RunningStatistics(data).Variance, Throws.Nothing);
Assert.That(() => new RunningStatistics(data).StandardDeviation, Throws.Nothing);
Assert.That(() => new RunningStatistics(data).Skewness, Throws.Nothing);
Assert.That(() => new RunningStatistics(data).Kurtosis, Throws.Nothing);
Assert.That(() => new RunningStatistics(data).PopulationVariance, Throws.Nothing);
Assert.That(() => new RunningStatistics(data).PopulationStandardDeviation, Throws.Nothing);
Assert.That(() => new RunningStatistics(data).PopulationSkewness, Throws.Nothing);
Assert.That(() => new RunningStatistics(data).PopulationKurtosis, Throws.Nothing);
}
[TestCase("lottery")]
[TestCase("lew")]
[TestCase("mavro")]
[TestCase("michelso")]
[TestCase("numacc1")]
[TestCase("numacc2")]
[TestCase("numacc3")]
[TestCase("numacc4")]
public void MeanConsistentWithNistData(string dataSet)
{
var data = _data[dataSet];
AssertHelpers.AlmostEqualRelative(data.Mean, Statistics.Mean(data.Data), 14);
AssertHelpers.AlmostEqualRelative(data.Mean, ArrayStatistics.Mean(data.Data), 14);
AssertHelpers.AlmostEqualRelative(data.Mean, StreamingStatistics.Mean(data.Data), 14);
AssertHelpers.AlmostEqualRelative(data.Mean, Statistics.MeanVariance(data.Data).Item1, 14);
AssertHelpers.AlmostEqualRelative(data.Mean, ArrayStatistics.MeanVariance(data.Data).Item1, 14);
AssertHelpers.AlmostEqualRelative(data.Mean, StreamingStatistics.MeanVariance(data.Data).Item1, 14);
AssertHelpers.AlmostEqualRelative(data.Mean, new RunningStatistics(data.Data).Mean, 14);
}
[TestCase("lottery")]
[TestCase("lew")]
[TestCase("mavro")]
[TestCase("michelso")]
[TestCase("numacc1")]
[TestCase("numacc2")]
[TestCase("numacc3")]
[TestCase("numacc4")]
public void NullableMeanConsistentWithNistData(string dataSet)
{
var data = _data[dataSet];
AssertHelpers.AlmostEqualRelative(data.Mean, Statistics.Mean(data.DataWithNulls), 14);
}
[TestCase("lottery", 14)]
[TestCase("lew", 14)]
[TestCase("mavro", 11)]
[TestCase("michelso", 11)]
[TestCase("numacc1", 15)]
[TestCase("numacc2", 13)]
[TestCase("numacc3", 9)]
[TestCase("numacc4", 7)]
public void StandardDeviationConsistentWithNistData(string dataSet, int digits)
{
var data = _data[dataSet];
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, Statistics.StandardDeviation(data.Data), digits);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, ArrayStatistics.StandardDeviation(data.Data), digits);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, StreamingStatistics.StandardDeviation(data.Data), digits);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, Math.Sqrt(Statistics.MeanVariance(data.Data).Item2), digits);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, Math.Sqrt(ArrayStatistics.MeanVariance(data.Data).Item2), digits);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, Math.Sqrt(StreamingStatistics.MeanVariance(data.Data).Item2), digits);
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, new RunningStatistics(data.Data).StandardDeviation, digits);
}
[TestCase("lottery", 14)]
[TestCase("lew", 14)]
[TestCase("mavro", 11)]
[TestCase("michelso", 11)]
[TestCase("numacc1", 15)]
[TestCase("numacc2", 13)]
[TestCase("numacc3", 9)]
[TestCase("numacc4", 7)]
public void NullableStandardDeviationConsistentWithNistData(string dataSet, int digits)
{
var data = _data[dataSet];
AssertHelpers.AlmostEqualRelative(data.StandardDeviation, Statistics.StandardDeviation(data.DataWithNulls), digits);
}
[Test]
public void MinimumMaximumOnShortSequence()
{
var samples = new[] { -1.0, 5, 0, -3, 10, -0.5, 4 };
Assert.That(Statistics.Minimum(samples), Is.EqualTo(-3), "Min");
Assert.That(Statistics.Maximum(samples), Is.EqualTo(10), "Max");
Assert.That(ArrayStatistics.Minimum(samples), Is.EqualTo(-3), "Min");
Assert.That(ArrayStatistics.Maximum(samples), Is.EqualTo(10), "Max");
Assert.That(StreamingStatistics.Minimum(samples), Is.EqualTo(-3), "Min");
Assert.That(StreamingStatistics.Maximum(samples), Is.EqualTo(10), "Max");
Assert.That(new RunningStatistics(samples).Minimum, Is.EqualTo(-3), "Min");
Assert.That(new RunningStatistics(samples).Maximum, Is.EqualTo(10), "Max");
Array.Sort(samples);
Assert.That(SortedArrayStatistics.Minimum(samples), Is.EqualTo(-3), "Min");
Assert.That(SortedArrayStatistics.Maximum(samples), Is.EqualTo(10), "Max");
}
[Test]
public void MinimumMaximumOnShortSequence32()
{
var samples = new[] { -1.0f, 5f, 0f, -3f, 10f, -0.5f, 4f };
Assert.That(Statistics.Minimum(samples), Is.EqualTo(-3), "Min");
Assert.That(Statistics.Maximum(samples), Is.EqualTo(10), "Max");
Assert.That(ArrayStatistics.Minimum(samples), Is.EqualTo(-3), "Min");
Assert.That(ArrayStatistics.Maximum(samples), Is.EqualTo(10), "Max");
Assert.That(StreamingStatistics.Minimum(samples), Is.EqualTo(-3), "Min");
Assert.That(StreamingStatistics.Maximum(samples), Is.EqualTo(10), "Max");
Array.Sort(samples);
Assert.That(SortedArrayStatistics.Minimum(samples), Is.EqualTo(-3), "Min");
Assert.That(SortedArrayStatistics.Maximum(samples), Is.EqualTo(10), "Max");
}
[Test]
public void OrderStatisticsOnShortSequence()
{
// -3 -1 -0.5 0 1 4 5 6 10
var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 1, 6 };
var f = Statistics.OrderStatisticFunc(samples);
Assert.That(f(0), Is.NaN, "Order-0 (bad)");
Assert.That(f(1), Is.EqualTo(-3), "Order-1");
Assert.That(f(2), Is.EqualTo(-1), "Order-2");
Assert.That(f(3), Is.EqualTo(-0.5), "Order-3");
Assert.That(f(7), Is.EqualTo(5), "Order-7");
Assert.That(f(8), Is.EqualTo(6), "Order-8");
Assert.That(f(9), Is.EqualTo(10), "Order-9");
Assert.That(f(10), Is.NaN, "Order-10 (bad)");
Assert.That(Statistics.OrderStatistic(samples, 0), Is.NaN, "Order-0 (bad)");
Assert.That(Statistics.OrderStatistic(samples, 1), Is.EqualTo(-3), "Order-1");
Assert.That(Statistics.OrderStatistic(samples, 2), Is.EqualTo(-1), "Order-2");
Assert.That(Statistics.OrderStatistic(samples, 3), Is.EqualTo(-0.5), "Order-3");
Assert.That(Statistics.OrderStatistic(samples, 7), Is.EqualTo(5), "Order-7");
Assert.That(Statistics.OrderStatistic(samples, 8), Is.EqualTo(6), "Order-8");
Assert.That(Statistics.OrderStatistic(samples, 9), Is.EqualTo(10), "Order-9");
Assert.That(Statistics.OrderStatistic(samples, 10), Is.NaN, "Order-10 (bad)");
Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 0), Is.NaN, "Order-0 (bad)");
Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 1), Is.EqualTo(-3), "Order-1");
Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 2), Is.EqualTo(-1), "Order-2");
Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 3), Is.EqualTo(-0.5), "Order-3");
Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 7), Is.EqualTo(5), "Order-7");
Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 8), Is.EqualTo(6), "Order-8");
Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 9), Is.EqualTo(10), "Order-9");
Assert.That(ArrayStatistics.OrderStatisticInplace(samples, 10), Is.NaN, "Order-10 (bad)");
Array.Sort(samples);
Assert.That(SortedArrayStatistics.OrderStatistic(samples, 0), Is.NaN, "Order-0 (bad)");
Assert.That(SortedArrayStatistics.OrderStatistic(samples, 1), Is.EqualTo(-3), "Order-1");
Assert.That(SortedArrayStatistics.OrderStatistic(samples, 2), Is.EqualTo(-1), "Order-2");
Assert.That(SortedArrayStatistics.OrderStatistic(samples, 3), Is.EqualTo(-0.5), "Order-3");
Assert.That(SortedArrayStatistics.OrderStatistic(samples, 7), Is.EqualTo(5), "Order-7");
Assert.That(SortedArrayStatistics.OrderStatistic(samples, 8), Is.EqualTo(6), "Order-8");
Assert.That(SortedArrayStatistics.OrderStatistic(samples, 9), Is.EqualTo(10), "Order-9");
Assert.That(SortedArrayStatistics.OrderStatistic(samples, 10), Is.NaN, "Order-10 (bad)");
}
[TestCase(0d, -3d)]
[TestCase(1d, 10d)]
[TestCase(0.5d, 1/5d)]
[TestCase(0.2d, -1d)]
[TestCase(0.7d, 4d)]
[TestCase(0.01d, -3d)]
[TestCase(0.99d, 10d)]
[TestCase(0.52d, 1d)]
[TestCase(0.325d, 0d)]
public void QuantileR1EmpiricalInvCDFOnShortSequence(double tau, double expected)
{
// R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=1)
// Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{0,0},{1,0}}]
var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 };
Assert.AreEqual(expected, Statistics.EmpiricalInvCDF(samples, tau), 1e-14);
Assert.AreEqual(expected, Statistics.EmpiricalInvCDFFunc(samples)(tau), 1e-14);
Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.EmpiricalInvCDF), 1e-14);
Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.EmpiricalInvCDF)(tau), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.EmpiricalInvCDF), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 0d, 0d, 1d, 0d), 1e-14);
Array.Sort(samples);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.EmpiricalInvCDF), 1e-14);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 0d, 0d, 1d, 0d), 1e-14);
}
[TestCase(0d, -3d)]
[TestCase(1d, 10d)]
[TestCase(0.5d, 3/5d)]
[TestCase(0.2d, -3/4d)]
[TestCase(0.7d, 9/2d)]
[TestCase(0.01d, -3d)]
[TestCase(0.99d, 10d)]
[TestCase(0.52d, 1d)]
[TestCase(0.325d, 0d)]
public void QuantileR2EmpiricalInvCDFAverageOnShortSequence(double tau, double expected)
{
// R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=2)
// Mathematica: Not Supported
var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 };
Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R2), 1e-14);
Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R2)(tau), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.EmpiricalInvCDFAverage), 1e-14);
Array.Sort(samples);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.EmpiricalInvCDFAverage), 1e-14);
}
[TestCase(0d, -3d)]
[TestCase(1d, 10d)]
[TestCase(0.5d, 1/5d)]
[TestCase(0.2d, -1d)]
[TestCase(0.7d, 4d)]
[TestCase(0.01d, -3d)]
[TestCase(0.99d, 10d)]
[TestCase(0.52d, 1/5d)]
[TestCase(0.325d, -1/2d)]
public void QuantileR3NearestOnShortSequence(double tau, double expected)
{
// R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=3)
// Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{1/2,0},{0,0}}]
var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 };
Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R3), 1e-14);
Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R3)(tau), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Nearest), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 0.5d, 0d, 0d, 0d), 1e-14);
Array.Sort(samples);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Nearest), 1e-14);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 0.5d, 0d, 0d, 0d), 1e-14);
}
[TestCase(0d, -3d)]
[TestCase(1d, 10d)]
[TestCase(0.5d, 1/5d)]
[TestCase(0.2d, -1d)]
[TestCase(0.7d, 4d)]
[TestCase(0.01d, -3d)]
[TestCase(0.99d, 48/5d)]
[TestCase(0.52d, 9/25d)]
[TestCase(0.325d, -3/8d)]
public void QuantileR4CaliforniaOnShortSequence(double tau, double expected)
{
// R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=4)
// Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{0,0},{0,1}}]
var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 };
Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R4), 1e-14);
Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R4)(tau), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.California), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 0d, 0d, 0d, 1d), 1e-14);
Array.Sort(samples);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.California), 1e-14);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 0d, 0d, 0d, 1d), 1e-14);
}
[TestCase(0d, -3d)]
[TestCase(1d, 10d)]
[TestCase(0.5d, 3/5d)]
[TestCase(0.2d, -3/4d)]
[TestCase(0.7d, 9/2d)]
[TestCase(0.01d, -3d)]
[TestCase(0.99d, 10d)]
[TestCase(0.52d, 19/25d)]
[TestCase(0.325d, -1/8d)]
public void QuantileR5HydrologyOnShortSequence(double tau, double expected)
{
// R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=5)
// Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{1/2,0},{0,1}}]
var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 };
Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R5), 1e-14);
Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R5)(tau), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Hydrology), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 0.5d, 0d, 0d, 1d), 1e-14);
Array.Sort(samples);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Hydrology), 1e-14);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 0.5d, 0d, 0d, 1d), 1e-14);
}
[TestCase(0d, -3d)]
[TestCase(1d, 10d)]
[TestCase(0.5d, 3/5d)]
[TestCase(0.2d, -9/10d)]
[TestCase(0.7d, 47/10d)]
[TestCase(0.01d, -3d)]
[TestCase(0.99d, 10d)]
[TestCase(0.52d, 97/125d)]
[TestCase(0.325d, -17/80d)]
public void QuantileR6WeibullOnShortSequence(double tau, double expected)
{
// R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=6)
// Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{0,1},{0,1}}]
var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 };
Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R6), 1e-14);
Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R6)(tau), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Weibull), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 0d, 1d, 0d, 1d), 1e-14);
Array.Sort(samples);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Weibull), 1e-14);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 0d, 1d, 0d, 1d), 1e-14);
}
[TestCase(0d, -3d)]
[TestCase(1d, 10d)]
[TestCase(0.5d, 3/5d)]
[TestCase(0.2d, -3/5d)]
[TestCase(0.7d, 43/10d)]
[TestCase(0.01d, -141/50d)]
[TestCase(0.99d, 241/25d)]
[TestCase(0.52d, 93/125d)]
[TestCase(0.325d, -3/80d)]
public void QuantileR7ExcelOnShortSequence(double tau, double expected)
{
// R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=7)
// Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{1,-1},{0,1}}]
var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 };
Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R7), 1e-14);
Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R7)(tau), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Excel), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 1d, -1d, 0d, 1d), 1e-14);
Array.Sort(samples);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Excel), 1e-14);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 1d, -1d, 0d, 1d), 1e-14);
}
[TestCase(0d, -3d)]
[TestCase(1d, 10d)]
[TestCase(0.5d, 3/5d)]
[TestCase(0.2d, -4/5d)]
[TestCase(0.7d, 137/30d)]
[TestCase(0.01d, -3d)]
[TestCase(0.99d, 10d)]
[TestCase(0.52d, 287/375d)]
[TestCase(0.325d, -37/240d)]
public void QuantileR8MedianOnShortSequence(double tau, double expected)
{
// R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=8)
// Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{1/3,1/3},{0,1}}]
var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 };
Assert.AreEqual(expected, Statistics.Quantile(samples, tau), 1e-14);
Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R8), 1e-14);
Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R8)(tau), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileInplace(samples, tau), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Median), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 1/3d, 1/3d, 0d, 1d), 1e-14);
Array.Sort(samples);
Assert.AreEqual(expected, SortedArrayStatistics.Quantile(samples, tau), 1e-14);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Median), 1e-14);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 1/3d, 1/3d, 0d, 1d), 1e-14);
}
[TestCase(0d, -3d)]
[TestCase(1d, 10d)]
[TestCase(0.5d, 3/5d)]
[TestCase(0.2d, -63/80d)]
[TestCase(0.7d, 91/20d)]
[TestCase(0.01d, -3d)]
[TestCase(0.99d, 10d)]
[TestCase(0.52d, 191/250d)]
[TestCase(0.325d, -47/320d)]
public void QuantileR9NormalOnShortSequence(double tau, double expected)
{
// R: quantile(c(-1,5,0,-3,10,-0.5,4,0.2,1,6),probs=c(0,1,0.5,0.2,0.7,0.01,0.99,0.52,0.325),type=9)
// Mathematica: Quantile[{-1,5,0,-3,10,-1/2,4,1/5,1,6},{0,1,1/2,1/5,7/10,1/100,99/100,13/25,13/40},{{3/8,1/4},{0,1}}]
var samples = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 };
Assert.AreEqual(expected, Statistics.QuantileCustom(samples, tau, QuantileDefinition.R9), 1e-14);
Assert.AreEqual(expected, Statistics.QuantileCustomFunc(samples, QuantileDefinition.R9)(tau), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, QuantileDefinition.Normal), 1e-14);
Assert.AreEqual(expected, ArrayStatistics.QuantileCustomInplace(samples, tau, 3/8d, 1/4d, 0d, 1d), 1e-14);
Array.Sort(samples);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, QuantileDefinition.Normal), 1e-14);
Assert.AreEqual(expected, SortedArrayStatistics.QuantileCustom(samples, tau, 3/8d, 1/4d, 0d, 1d), 1e-14);
}
[Test]
public void RanksSortedArray()
{
var distinct = new double[] { 1, 2, 4, 7, 8, 9, 10, 12 };
var ties = new double[] { 1, 2, 2, 7, 9, 9, 10, 12 };
// R: rank(sort(data), ties.method="average")
Assert.That(
SortedArrayStatistics.Ranks(distinct, RankDefinition.Average),
Is.EqualTo(new[] { 1.0, 2, 3, 4, 5, 6, 7, 8 }).AsCollection.Within(1e-8));
Assert.That(
SortedArrayStatistics.Ranks(ties, RankDefinition.Average),
Is.EqualTo(new[] { 1, 2.5, 2.5, 4, 5.5, 5.5, 7, 8 }).AsCollection.Within(1e-8));
// R: rank(data, ties.method="min")
Assert.That(
SortedArrayStatistics.Ranks(distinct, RankDefinition.Min),
Is.EqualTo(new[] { 1.0, 2, 3, 4, 5, 6, 7, 8 }).AsCollection.Within(1e-8));
Assert.That(
SortedArrayStatistics.Ranks(ties, RankDefinition.Min),
Is.EqualTo(new[] { 1.0, 2, 2, 4, 5, 5, 7, 8 }).AsCollection.Within(1e-8));
// R: rank(data, ties.method="max")
Assert.That(
SortedArrayStatistics.Ranks(distinct, RankDefinition.Max),
Is.EqualTo(new[] { 1.0, 2, 3, 4, 5, 6, 7, 8 }).AsCollection.Within(1e-8));
Assert.That(
SortedArrayStatistics.Ranks(ties, RankDefinition.Max),
Is.EqualTo(new[] { 1.0, 3, 3, 4, 6, 6, 7, 8 }).AsCollection.Within(1e-8));
// R: rank(data, ties.method="first")
Assert.That(
SortedArrayStatistics.Ranks(distinct, RankDefinition.First),
Is.EqualTo(new[] { 1.0, 2, 3, 4, 5, 6, 7, 8 }).AsCollection.Within(1e-8));
Assert.That(
SortedArrayStatistics.Ranks(ties, RankDefinition.First),
Is.EqualTo(new[] { 1.0, 2, 3, 4, 5, 6, 7, 8 }).AsCollection.Within(1e-8));
}
[Test]
public void RanksArray()
{
var distinct = new double[] { 1, 8, 12, 7, 2, 9, 10, 4 };
var ties = new double[] { 1, 9, 12, 7, 2, 9, 10, 2 };
// R: rank(data, ties.method="average")
Assert.That(
ArrayStatistics.RanksInplace((double[])distinct.Clone(), RankDefinition.Average),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8));
Assert.That(
ArrayStatistics.RanksInplace((double[])ties.Clone(), RankDefinition.Average),
Is.EqualTo(new[] { 1, 5.5, 8, 4, 2.5, 5.5, 7, 2.5 }).AsCollection.Within(1e-8));
// R: rank(data, ties.method="min")
Assert.That(
ArrayStatistics.RanksInplace((double[])distinct.Clone(), RankDefinition.Min),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8));
Assert.That(
ArrayStatistics.RanksInplace((double[])ties.Clone(), RankDefinition.Min),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 5, 7, 2 }).AsCollection.Within(1e-8));
// R: rank(data, ties.method="max")
Assert.That(
ArrayStatistics.RanksInplace((double[])distinct.Clone(), RankDefinition.Max),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8));
Assert.That(
ArrayStatistics.RanksInplace((double[])ties.Clone(), RankDefinition.Max),
Is.EqualTo(new[] { 1.0, 6, 8, 4, 3, 6, 7, 3 }).AsCollection.Within(1e-8));
// R: rank(data, ties.method="first")
Assert.That(
ArrayStatistics.RanksInplace((double[])distinct.Clone(), RankDefinition.First),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8));
Assert.That(
ArrayStatistics.RanksInplace((double[])ties.Clone(), RankDefinition.First),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8));
}
[Test]
public void Ranks()
{
var distinct = new double[] { 1, 8, 12, 7, 2, 9, 10, 4 };
var ties = new double[] { 1, 9, 12, 7, 2, 9, 10, 2 };
// R: rank(data, ties.method="average")
Assert.That(
Statistics.Ranks(distinct, RankDefinition.Average),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8));
Assert.That(
Statistics.Ranks(ties, RankDefinition.Average),
Is.EqualTo(new[] { 1, 5.5, 8, 4, 2.5, 5.5, 7, 2.5 }).AsCollection.Within(1e-8));
// R: rank(data, ties.method="min")
Assert.That(
Statistics.Ranks(distinct, RankDefinition.Min),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8));
Assert.That(
Statistics.Ranks(ties, RankDefinition.Min),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 5, 7, 2 }).AsCollection.Within(1e-8));
// R: rank(data, ties.method="max")
Assert.That(
Statistics.Ranks(distinct, RankDefinition.Max),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8));
Assert.That(
Statistics.Ranks(ties, RankDefinition.Max),
Is.EqualTo(new[] { 1.0, 6, 8, 4, 3, 6, 7, 3 }).AsCollection.Within(1e-8));
// R: rank(data, ties.method="first")
Assert.That(
Statistics.Ranks(distinct, RankDefinition.First),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8));
Assert.That(
Statistics.Ranks(ties, RankDefinition.First),
Is.EqualTo(new[] { 1.0, 5, 8, 4, 2, 6, 7, 3 }).AsCollection.Within(1e-8));
}
[Test]
public void EmpiricalCDF()
{
// R: ecdf(data)(x)
var ties = new double[] { 1, 9, 12, 7, 2, 9, 10, 2 };
Assert.That(Statistics.EmpiricalCDF(ties, -1.0), Is.EqualTo(0.0).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 0.0), Is.EqualTo(0.0).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 1.0), Is.EqualTo(0.125).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 2.0), Is.EqualTo(0.375).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 3.0), Is.EqualTo(0.375).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 4.0), Is.EqualTo(0.375).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 5.0), Is.EqualTo(0.375).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 6.0), Is.EqualTo(0.375).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 7.0), Is.EqualTo(0.5).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 8.0), Is.EqualTo(0.5).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 9.0), Is.EqualTo(0.75).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 10.0), Is.EqualTo(0.875).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 11.0), Is.EqualTo(0.875).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 12.0), Is.EqualTo(1.0).Within(1e-8));
Assert.That(Statistics.EmpiricalCDF(ties, 13.0), Is.EqualTo(1.0).Within(1e-8));
}
[Test]
public void EmpiricalCDFSortedArray()
{
// R: ecdf(data)(x)
var ties = new double[] { 1, 9, 12, 7, 2, 9, 10, 2 };
Array.Sort(ties);
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, -1.0), Is.EqualTo(0.0).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 0.0), Is.EqualTo(0.0).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 1.0), Is.EqualTo(0.125).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 2.0), Is.EqualTo(0.375).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 3.0), Is.EqualTo(0.375).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 4.0), Is.EqualTo(0.375).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 5.0), Is.EqualTo(0.375).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 6.0), Is.EqualTo(0.375).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 7.0), Is.EqualTo(0.5).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 8.0), Is.EqualTo(0.5).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 9.0), Is.EqualTo(0.75).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 10.0), Is.EqualTo(0.875).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 11.0), Is.EqualTo(0.875).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 12.0), Is.EqualTo(1.0).Within(1e-8));
Assert.That(SortedArrayStatistics.EmpiricalCDF(ties, 13.0), Is.EqualTo(1.0).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, -1.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.0).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 0.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.0).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 1.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.125).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 2.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.375).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 3.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.375).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 4.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.375).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 5.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.375).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 6.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.375).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 7.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.5).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 8.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.5).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 9.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.75).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 10.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.875).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 11.0, RankDefinition.EmpiricalCDF), Is.EqualTo(0.875).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 12.0, RankDefinition.EmpiricalCDF), Is.EqualTo(1.0).Within(1e-8));
Assert.That(SortedArrayStatistics.QuantileRank(ties, 13.0, RankDefinition.EmpiricalCDF), Is.EqualTo(1.0).Within(1e-8));
}
[Test]
public void MedianOnShortSequence()
{
// R: median(c(-1,5,0,-3,10,-0.5,4,0.2,1,6))
// Mathematica: Median[{-1,5,0,-3,10,-1/2,4,1/5,1,6}]
var even = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1, 6 };
Assert.AreEqual(0.6d, Statistics.Median(even), 1e-14);
Assert.AreEqual(0.6d, ArrayStatistics.MedianInplace(even), 1e-14);
Array.Sort(even);
Assert.AreEqual(0.6d, SortedArrayStatistics.Median(even), 1e-14);
// R: median(c(-1,5,0,-3,10,-0.5,4,0.2,1))
// Mathematica: Median[{-1,5,0,-3,10,-1/2,4,1/5,1}]
var odd = new[] { -1, 5, 0, -3, 10, -0.5, 4, 0.2, 1 };
Assert.AreEqual(0.2d, Statistics.Median(odd), 1e-14);
Assert.AreEqual(0.2d, ArrayStatistics.MedianInplace(odd), 1e-14);
Array.Sort(even);
Assert.AreEqual(0.2d, SortedArrayStatistics.Median(odd), 1e-14);
}
[Test]
public void MedianOnLongConstantSequence()
{
var even = Generate.Repeat(100000, 2.0);
Assert.AreEqual(2.0,SortedArrayStatistics.Median(even), 1e-14);
var odd = Generate.Repeat(100001, 2.0);
Assert.AreEqual(2.0, SortedArrayStatistics.Median(odd), 1e-14);
}
/// <summary>
/// Validate Median/Variance/StdDev on a longer fixed-random sequence of a,
/// large mean but only a very small variance, verifying the numerical stability.
/// Naive summation algorithms generally fail this test.
/// </summary>
[Test]
public void StabilityMeanVariance()
{
// Test around 10^9, potential stability issues
var gaussian = new Normal(1e+9, 2, new MersenneTwister(100));
AssertHelpers.AlmostEqualRelative(1e+9, Statistics.Mean(gaussian.Samples().Take(10000)), 10);
AssertHelpers.AlmostEqualRelative(4d, Statistics.Variance(gaussian.Samples().Take(10000)), 0);
AssertHelpers.AlmostEqualRelative(2d, Statistics.StandardDeviation(gaussian.Samples().Take(10000)), 1);
AssertHelpers.AlmostEqualRelative(1e+9, Statistics.RootMeanSquare(gaussian.Samples().Take(10000)), 10);
AssertHelpers.AlmostEqualRelative(1e+9, ArrayStatistics.Mean(gaussian.Samples().Take(10000).ToArray()), 10);
AssertHelpers.AlmostEqualRelative(4d, ArrayStatistics.Variance(gaussian.Samples().Take(10000).ToArray()), 0);
AssertHelpers.AlmostEqualRelative(2d, ArrayStatistics.StandardDeviation(gaussian.Samples().Take(10000).ToArray()), 1);
AssertHelpers.AlmostEqualRelative(1e+9, ArrayStatistics.RootMeanSquare(gaussian.Samples().Take(10000).ToArray()), 10);
AssertHelpers.AlmostEqualRelative(1e+9, StreamingStatistics.Mean(gaussian.Samples().Take(10000)), 10);
AssertHelpers.AlmostEqualRelative(4d, StreamingStatistics.Variance(gaussian.Samples().Take(10000)), 0);
AssertHelpers.AlmostEqualRelative(2d, StreamingStatistics.StandardDeviation(gaussian.Samples().Take(10000)), 1);
AssertHelpers.AlmostEqualRelative(1e+9, StreamingStatistics.RootMeanSquare(gaussian.Samples().Take(10000)), 10);
AssertHelpers.AlmostEqualRelative(1e+9, new RunningStatistics(gaussian.Samples().Take(10000)).Mean, 10);
AssertHelpers.AlmostEqualRelative(4d, new RunningStatistics(gaussian.Samples().Take(10000)).Variance, 0);
AssertHelpers.AlmostEqualRelative(2d, new RunningStatistics(gaussian.Samples().Take(10000)).StandardDeviation, 1);
}
[TestCase("lottery")]
[TestCase("lew")]
[TestCase("mavro")]
[TestCase("michelso")]
[TestCase("numacc1")]
public void CovarianceConsistentWithVariance(string dataSet)
{
var data = _data[dataSet];
AssertHelpers.AlmostEqualRelative(Statistics.Variance(data.Data), Statistics.Covariance(data.Data, data.Data), 10);
AssertHelpers.AlmostEqualRelative(ArrayStatistics.Variance(data.Data), ArrayStatistics.Covariance(data.Data, data.Data), 10);
AssertHelpers.AlmostEqualRelative(StreamingStatistics.Variance(data.Data), StreamingStatistics.Covariance(data.Data, data.Data), 10);
}
[TestCase("lottery")]
[TestCase("lew")]
[TestCase("mavro")]
[TestCase("michelso")]
[TestCase("numacc1")]
public void PopulationCovarianceConsistentWithPopulationVariance(string dataSet)
{
var data = _data[dataSet];
AssertHelpers.AlmostEqualRelative(Statistics.PopulationVariance(data.Data), Statistics.PopulationCovariance(data.Data, data.Data), 10);
AssertHelpers.AlmostEqualRelative(ArrayStatistics.PopulationVariance(data.Data), ArrayStatistics.PopulationCovariance(data.Data, data.Data), 10);
AssertHelpers.AlmostEqualRelative(StreamingStatistics.PopulationVariance(data.Data), StreamingStatistics.PopulationCovariance(data.Data, data.Data), 10);
}
[Test]
public void CovarianceIsSymmetric()
{
var dataA = _data["lottery"].Data.Take(200).ToArray();
var dataB = _data["lew"].Data.Take(200).ToArray();
AssertHelpers.AlmostEqualRelative(Statistics.Covariance(dataA, dataB), Statistics.Covariance(dataB, dataA), 12);
AssertHelpers.AlmostEqualRelative(StreamingStatistics.Covariance(dataA, dataB), StreamingStatistics.Covariance(dataB, dataA), 12);
AssertHelpers.AlmostEqualRelative(ArrayStatistics.Covariance(dataA.ToArray(), dataB.ToArray()), ArrayStatistics.Covariance(dataB.ToArray(), dataA.ToArray()), 12);
AssertHelpers.AlmostEqualRelative(Statistics.PopulationCovariance(dataA, dataB), Statistics.PopulationCovariance(dataB, dataA), 12);
AssertHelpers.AlmostEqualRelative(StreamingStatistics.PopulationCovariance(dataA, dataB), StreamingStatistics.PopulationCovariance(dataB, dataA), 12);
AssertHelpers.AlmostEqualRelative(ArrayStatistics.PopulationCovariance(dataA.ToArray(), dataB.ToArray()), ArrayStatistics.PopulationCovariance(dataB.ToArray(), dataA.ToArray()), 12);
}
[TestCase("lottery")]
[TestCase("lew")]
[TestCase("mavro")]
[TestCase("michelso")]
[TestCase("numacc1")]
[TestCase("numacc2")]
[TestCase("meixner")]
public void ArrayStatisticsConsistentWithStreamimgStatistics(string dataSet)
{
var data = _data[dataSet];
Assert.That(ArrayStatistics.Mean(data.Data), Is.EqualTo(StreamingStatistics.Mean(data.Data)).Within(1e-15), "Mean");
Assert.That(ArrayStatistics.Variance(data.Data), Is.EqualTo(StreamingStatistics.Variance(data.Data)).Within(1e-15), "Variance");
Assert.That(ArrayStatistics.StandardDeviation(data.Data), Is.EqualTo(StreamingStatistics.StandardDeviation(data.Data)).Within(1e-15), "StandardDeviation");
Assert.That(ArrayStatistics.PopulationVariance(data.Data), Is.EqualTo(StreamingStatistics.PopulationVariance(data.Data)).Within(1e-15), "PopulationVariance");
Assert.That(ArrayStatistics.PopulationStandardDeviation(data.Data), Is.EqualTo(StreamingStatistics.PopulationStandardDeviation(data.Data)).Within(1e-15), "PopulationStandardDeviation");
Assert.That(ArrayStatistics.Covariance(data.Data, data.Data), Is.EqualTo(StreamingStatistics.Covariance(data.Data, data.Data)).Within(1e-10), "Covariance");
Assert.That(ArrayStatistics.PopulationCovariance(data.Data, data.Data), Is.EqualTo(StreamingStatistics.PopulationCovariance(data.Data, data.Data)).Within(1e-10), "PopulationCovariance");
Assert.That(ArrayStatistics.RootMeanSquare(data.Data), Is.EqualTo(StreamingStatistics.RootMeanSquare(data.Data)).Within(1e-15), "RootMeanSquare");
}
[TestCase("lottery")]
[TestCase("lew")]
[TestCase("mavro")]
[TestCase("michelso")]
[TestCase("numacc1")]
[TestCase("numacc2")]
[TestCase("meixner")]
public void RunningStatisticsConsistentWithDescriptiveStatistics(string dataSet)
{
var data = _data[dataSet];
var running = new RunningStatistics(data.Data);
var descriptive = new DescriptiveStatistics(data.Data);
Assert.That(running.Minimum, Is.EqualTo(descriptive.Minimum), "Minimum");
Assert.That(running.Maximum, Is.EqualTo(descriptive.Maximum), "Maximum");
Assert.That(running.Mean, Is.EqualTo(descriptive.Mean).Within(1e-15), "Mean");
Assert.That(running.Variance, Is.EqualTo(descriptive.Variance).Within(1e-15), "Variance");
Assert.That(running.StandardDeviation, Is.EqualTo(descriptive.StandardDeviation).Within(1e-15), "StandardDeviation");
Assert.That(running.Skewness, Is.EqualTo(descriptive.Skewness).Within(1e-15), "Skewness");
Assert.That(running.Kurtosis, Is.EqualTo(descriptive.Kurtosis).Within(1e-14), "Kurtosis");
}
[Test]
public void MinimumOfEmptyMustBeNaN()
{
Assert.That(Statistics.Minimum(new double[0]), Is.NaN);
Assert.That(Statistics.Minimum(new[] { 2d }), Is.Not.NaN);
Assert.That(ArrayStatistics.Minimum(new double[0]), Is.NaN);
Assert.That(ArrayStatistics.Minimum(new[] { 2d }), Is.Not.NaN);
Assert.That(SortedArrayStatistics.Minimum(new double[0]), Is.NaN);
Assert.That(SortedArrayStatistics.Minimum(new[] { 2d }), Is.Not.NaN);
Assert.That(StreamingStatistics.Minimum(new double[0]), Is.NaN);
Assert.That(StreamingStatistics.Minimum(new[] { 2d }), Is.Not.NaN);
Assert.That(new RunningStatistics(new double[0]).Minimum, Is.NaN);
Assert.That(new RunningStatistics(new[] { 2d }).Minimum, Is.Not.NaN);
}
[Test]
public void MaximumOfEmptyMustBeNaN()
{
Assert.That(Statistics.Maximum(new double[0]), Is.NaN);
Assert.That(Statistics.Maximum(new[] { 2d }), Is.Not.NaN);
Assert.That(ArrayStatistics.Maximum(new double[0]), Is.NaN);
Assert.That(ArrayStatistics.Maximum(new[] { 2d }), Is.Not.NaN);
Assert.That(SortedArrayStatistics.Maximum(new double[0]), Is.NaN);
Assert.That(SortedArrayStatistics.Maximum(new[] { 2d }), Is.Not.NaN);
Assert.That(StreamingStatistics.Maximum(new double[0]), Is.NaN);
Assert.That(StreamingStatistics.Maximum(new[] { 2d }), Is.Not.NaN);
Assert.That(new RunningStatistics(new double[0]).Maximum, Is.NaN);
Assert.That(new RunningStatistics(new[] { 2d }).Maximum, Is.Not.NaN);
}
[Test]
public void MeanOfEmptyMustBeNaN()
{
Assert.That(Statistics.Mean(new double[0]), Is.NaN);
Assert.That(Statistics.Mean(new[] { 2d }), Is.Not.NaN);
Assert.That(ArrayStatistics.Mean(new double[0]), Is.NaN);
Assert.That(ArrayStatistics.Mean(new[] { 2d }), Is.Not.NaN);
Assert.That(StreamingStatistics.Mean(new double[0]), Is.NaN);
Assert.That(StreamingStatistics.Mean(new[] { 2d }), Is.Not.NaN);
Assert.That(new RunningStatistics(new double[0]).Mean, Is.NaN);
Assert.That(new RunningStatistics(new[] { 2d }).Mean, Is.Not.NaN);
}
[Test]
public void RootMeanSquareOfEmptyMustBeNaN()
{
Assert.That(Statistics.RootMeanSquare(new double[0]), Is.NaN);
Assert.That(Statistics.RootMeanSquare(new[] { 2d }), Is.Not.NaN);
Assert.That(ArrayStatistics.RootMeanSquare(new double[0]), Is.NaN);
Assert.That(ArrayStatistics.RootMeanSquare(new[] { 2d }), Is.Not.NaN);
Assert.That(StreamingStatistics.RootMeanSquare(new double[0]), Is.NaN);
Assert.That(StreamingStatistics.RootMeanSquare(new[] { 2d }), Is.Not.NaN);
}
[Test]
public void SampleVarianceOfEmptyAndSingleMustBeNaN()
{
Assert.That(Statistics.Variance(new double[0]), Is.NaN);
Assert.That(Statistics.Variance(new[] { 2d }), Is.NaN);
Assert.That(Statistics.Variance(new[] { 2d, 3d }), Is.Not.NaN);
Assert.That(ArrayStatistics.Variance(new double[0]), Is.NaN);
Assert.That(ArrayStatistics.Variance(new[] { 2d }), Is.NaN);
Assert.That(ArrayStatistics.Variance(new[] { 2d, 3d }), Is.Not.NaN);
Assert.That(StreamingStatistics.Variance(new double[0]), Is.NaN);
Assert.That(StreamingStatistics.Variance(new[] { 2d }), Is.NaN);
Assert.That(StreamingStatistics.Variance(new[] { 2d, 3d }), Is.Not.NaN);
Assert.That(new RunningStatistics(new[] { 2d }).Variance, Is.NaN);
Assert.That(new RunningStatistics(new[] { 2d, 3d }).Variance, Is.Not.NaN);
}
[Test]
public void PopulationVarianceOfEmptyMustBeNaN()
{
Assert.That(Statistics.PopulationVariance(new double[0]), Is.NaN);
Assert.That(Statistics.PopulationVariance(new[] { 2d }), Is.Not.NaN);
Assert.That(Statistics.PopulationVariance(new[] { 2d, 3d }), Is.Not.NaN);
Assert.That(ArrayStatistics.PopulationVariance(new double[0]), Is.NaN);
Assert.That(ArrayStatistics.PopulationVariance(new[] { 2d }), Is.Not.NaN);
Assert.That(ArrayStatistics.PopulationVariance(new[] { 2d, 3d }), Is.Not.NaN);
Assert.That(StreamingStatistics.PopulationVariance(new double[0]), Is.NaN);
Assert.That(StreamingStatistics.PopulationVariance(new[] { 2d }), Is.Not.NaN);
Assert.That(StreamingStatistics.PopulationVariance(new[] { 2d, 3d }), Is.Not.NaN);
Assert.That(new RunningStatistics(new[] { 2d }).PopulationVariance, Is.NaN);
Assert.That(new RunningStatistics(new[] { 2d, 3d }).PopulationVariance, Is.Not.NaN);
}
/// <summary>
/// URL http://mathnetnumerics.codeplex.com/workitem/5667
/// </summary>
[Test]
public void Median_CodeplexIssue5667()
{
var seq = Data.ReadAllLines("Codeplex-5667.csv").Select(double.Parse);
Assert.AreEqual(1.0, Statistics.Median(seq));
var array = seq.ToArray();
Assert.AreEqual(1.0, ArrayStatistics.MedianInplace(array));
Array.Sort(array);
Assert.AreEqual(1.0, SortedArrayStatistics.Median(array));
}
[Test]
public void VarianceDenominatorMustNotOverflow_GitHubIssue137()
{
var a = new double[46342];
a[a.Length - 1] = 1000d;
Assert.AreEqual(21.578697, a.Variance(), 1e-5);
Assert.AreEqual(21.578231, a.PopulationVariance(), 1e-5);
Assert.AreEqual(21.578697, new RunningStatistics(a).Variance, 1e-5);
Assert.AreEqual(21.578231, new RunningStatistics(a).PopulationVariance, 1e-5);
}
[Test]
public void MedianIsRobustOnCloseInfinities()
{
Assert.That(Statistics.Median(new[] { 2.0, double.NegativeInfinity, double.PositiveInfinity }), Is.EqualTo(2.0));
Assert.That(Statistics.Median(new[] { 2.0, double.NegativeInfinity, 3.0, double.PositiveInfinity }), Is.EqualTo(2.5));
Assert.That(ArrayStatistics.MedianInplace(new[] { 2.0, double.NegativeInfinity, double.PositiveInfinity }), Is.EqualTo(2.0));
Assert.That(ArrayStatistics.MedianInplace(new[] { double.NegativeInfinity, 2.0, double.PositiveInfinity }), Is.EqualTo(2.0));
Assert.That(ArrayStatistics.MedianInplace(new[] { double.NegativeInfinity, double.PositiveInfinity, 2.0 }), Is.EqualTo(2.0));
Assert.That(ArrayStatistics.MedianInplace(new[] { double.NegativeInfinity, 2.0, 3.0, double.PositiveInfinity }), Is.EqualTo(2.5));
Assert.That(ArrayStatistics.MedianInplace(new[] { double.NegativeInfinity, 2.0, double.PositiveInfinity, 3.0 }), Is.EqualTo(2.5));
Assert.That(SortedArrayStatistics.Median(new[] { double.NegativeInfinity, 2.0, double.PositiveInfinity }), Is.EqualTo(2.0));
Assert.That(SortedArrayStatistics.Median(new[] { double.NegativeInfinity, 2.0, 3.0, double.PositiveInfinity }), Is.EqualTo(2.5));
}
[Test]
public void RobustOnLargeSampleSets()
{
// 0, 0.25, 0.5, 0.75, 0, 0.25, 0.5, 0.75, ...
var shorter = Generate.Periodic(4*4096, 4, 1);
var longer = Generate.Periodic(4*32768, 4, 1);
Assert.That(Statistics.Mean(shorter), Is.EqualTo(0.375).Within(1e-14), "Statistics.Mean: shorter");
Assert.That(Statistics.Mean(longer), Is.EqualTo(0.375).Within(1e-14), "Statistics.Mean: longer");
Assert.That(new DescriptiveStatistics(shorter).Mean, Is.EqualTo(0.375).Within(1e-14), "DescriptiveStatistics.Mean: shorter");
Assert.That(new DescriptiveStatistics(longer).Mean, Is.EqualTo(00.375).Within(1e-14), "DescriptiveStatistics.Mean: longer");
Assert.That(Statistics.RootMeanSquare(shorter), Is.EqualTo(Math.Sqrt(0.21875)).Within(1e-14), "Statistics.RootMeanSquare: shorter");
Assert.That(Statistics.RootMeanSquare(longer), Is.EqualTo(Math.Sqrt(0.21875)).Within(1e-14), "Statistics.RootMeanSquare: longer");
Assert.That(Statistics.Skewness(shorter), Is.EqualTo(0.0).Within(1e-12), "Statistics.Skewness: shorter");
Assert.That(Statistics.Skewness(longer), Is.EqualTo(0.0).Within(1e-12), "Statistics.Skewness: longer");
Assert.That(new DescriptiveStatistics(shorter).Skewness, Is.EqualTo(0.0).Within(1e-12), "DescriptiveStatistics.Skewness: shorter");
Assert.That(new DescriptiveStatistics(longer).Skewness, Is.EqualTo(0.0).Within(1e-12), "DescriptiveStatistics.Skewness: longer");
Assert.That(Statistics.Kurtosis(shorter), Is.EqualTo(-1.36).Within(1e-4), "Statistics.Kurtosis: shorter");
Assert.That(Statistics.Kurtosis(longer), Is.EqualTo(-1.36).Within(1e-4), "Statistics.Kurtosis: longer");
Assert.That(new DescriptiveStatistics(shorter).Kurtosis, Is.EqualTo(-1.36).Within(1e-4), "DescriptiveStatistics.Kurtosis: shorter");
Assert.That(new DescriptiveStatistics(longer).Kurtosis, Is.EqualTo(-1.36).Within(1e-4), "DescriptiveStatistics.Kurtosis: longer");
}
[Test]
public void RootMeanSquareOfSinusoidal()
{
var data = Generate.Sinusoidal(128, 64, 16, 2.0);
Assert.That(Statistics.RootMeanSquare(data), Is.EqualTo(2.0/Constants.Sqrt2).Within(1e-12));
}
[Test]
public void EntropyIsMinimum()
{
var data1 = new double[] { 1, 1, 1, 1, 1 };
Assert.That(StreamingStatistics.Entropy(data1) == 0);
var data2 = new double[] { 0, 0 };
Assert.That(StreamingStatistics.Entropy(data2) == 0);
}
[Test]
public void EntropyIsMaximum()
{
var data1 = new double[] { 1, 2 };
Assert.That(StreamingStatistics.Entropy(data1) == 1.0);
var data2 = new double[] { 1, 2, 3, 4 };
Assert.That(StreamingStatistics.Entropy(data2) == 2.0);
}
[Test]
public void EntropyOfNaNIsNaN()
{
var data = new double[] { 1, 2, double.NaN };
Assert.That(double.IsNaN(StreamingStatistics.Entropy(data)));
}
[Test]
public void MinimumMagnitudePhase()
{
var a = new[] { new Complex32(1.0f, 2.0f), new Complex32(float.PositiveInfinity, float.NegativeInfinity), new Complex32(-2.0f, 4.0f) };
Assert.That(ArrayStatistics.MinimumMagnitudePhase(a), Is.EqualTo(a[0]));
}
[Test]
public void MinimumMagnitudePhaseOfNaNIsNaN()
{
var a = new[] { new Complex32(1.0f, 2.0f), new Complex32(float.NaN, float.NegativeInfinity), new Complex32(-2.0f, 4.0f) };
Assert.That(ArrayStatistics.MinimumMagnitudePhase(a).IsNaN(), Is.True);
}
[Test]
public void MaximumMagnitudePhase()
{
var a = new[] { new Complex32(1.0f, 2.0f), new Complex32(float.PositiveInfinity, float.NegativeInfinity), new Complex32(-2.0f, 4.0f) };
Assert.That(ArrayStatistics.MaximumMagnitudePhase(a), Is.EqualTo(a[1]));
}
[Test]
public void MaximumMagnitudePhaseOfNaNIsNaN()
{
var a = new[] { new Complex32(1.0f, 2.0f), new Complex32(float.NaN, float.NegativeInfinity), new Complex32(-2.0f, 4.0f) };
Assert.That(ArrayStatistics.MaximumMagnitudePhase(a).IsNaN(), Is.True);
}
}
}
// ReSharper restore InvokeAsExtensionMethod
| |
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Object = Java.Lang.Object;
namespace QuickAction
{
public delegate void OnActionItemClickEventHandler(object sender, ActionItemClickEventArgs e);
public delegate void OnActionItemDismissedEventHandler(object sender, EventArgs e);
public class QuickAction : Object, PopupWindow.IOnDismissListener
{
readonly List<ActionItem> _actionItems = new List<ActionItem>();
readonly Context _context;
readonly LayoutInflater _inflater;
readonly QuickActionLayout _orientation;
readonly PopupWindow _window;
readonly IWindowManager _windowManager;
ImageView _arrowDown;
ImageView _arrowUp;
int _childPos;
bool _didAction;
int _insertPos;
View _rootView;
int _rootWidth;
ScrollView _scroller;
ViewGroup _track;
public QuickAction(Context context) : this(context, QuickActionLayout.Vertical)
{
}
public QuickAction(Context context, QuickActionLayout orientation)
{
_context = context;
_window = new PopupWindow(context);
_childPos = 0;
_window.TouchIntercepted += HandleTouchIntercepted;
_windowManager = context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
_orientation = orientation;
_inflater = (LayoutInflater)context.GetSystemService(Context.LayoutInflaterService);
SetRootViewId(orientation == QuickActionLayout.Horizontal ? Resource.Layout.popup_horizontal : Resource.Layout.popup_vertical);
}
public Drawable Background { get; set; }
void PopupWindow.IOnDismissListener.OnDismiss()
{
}
public event OnActionItemDismissedEventHandler ActionItemDismissed;
public event OnActionItemClickEventHandler ActionItemClicked;
public void SetContentView(View root)
{
_rootView = root;
_window.ContentView = root;
}
public void SetContentView(int layoutResourceId)
{
var inflater = (LayoutInflater)_context.GetSystemService(Context.LayoutInflaterService);
SetContentView(inflater.Inflate(layoutResourceId, null));
}
public ActionItem GetActionItem(int index)
{
return _actionItems[index];
}
public void SetRootViewId(int id)
{
_rootView = _inflater.Inflate(id, null);
_track = _rootView.FindViewById<ViewGroup>(Resource.Id.tracks);
_arrowUp = _rootView.FindViewById<ImageView>(Resource.Id.arrow_up);
_arrowDown = _rootView.FindViewById<ImageView>(Resource.Id.arrow_down);
_scroller = _rootView.FindViewById<ScrollView>(Resource.Id.scroller);
_rootView.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
SetContentView(_rootView);
}
public void AddActionItem(ActionItem item)
{
View container;
_actionItems.Add(item);
if (_orientation == QuickActionLayout.Horizontal)
{
container = _inflater.Inflate(Resource.Layout.action_item_horizontal, null);
}
else
{
container = _inflater.Inflate(Resource.Layout.action_item_vertical, null);
}
var img = container.FindViewById<ImageView>(Resource.Id.iv_icon);
if (item.Icon == null)
{
img.Visibility = ViewStates.Gone;
}
else
{
img.SetImageDrawable(item.Icon);
}
var text = container.FindViewById<TextView>(Resource.Id.tv_title);
if (string.IsNullOrWhiteSpace(item.Title))
{
text.Visibility = ViewStates.Gone;
}
else
{
text.Text = item.Title;
}
var pos = _childPos;
container.Click += (sender, e) =>{
if (ActionItemClicked != null)
{
var arg = new ActionItemClickEventArgs(this, pos);
ActionItemClicked(container, arg);
}
if (GetActionItem(pos).IsSticky)
{
return;
}
_didAction = true;
Dismiss();
};
container.Focusable = true;
container.Clickable = true;
if (_orientation == QuickActionLayout.Horizontal && _childPos != 0)
{
var separator = _inflater.Inflate(Resource.Layout.horiz_separator, null);
var parms = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
separator.LayoutParameters = parms;
separator.SetPadding(5, 0, 5, 0);
_track.AddView(separator, _insertPos);
_insertPos++;
}
_track.AddView(container, _insertPos);
_childPos++;
_insertPos++;
}
Rect GetAnchorRectangle(View view)
{
var location = new int[2];
view.GetLocationOnScreen(location);
var anchorRect = new Rect(location[0], location[1], location[0] + view.Width, location[1] + view.Height);
return anchorRect;
}
public void Show(View anchor, QuickActionAnimationStyle animationStyle = QuickActionAnimationStyle.Auto)
{
PreShow();
var windowLocation = new Point();
int arrowPos;
_didAction = false;
var anchorRect = GetAnchorRectangle(anchor);
_rootView.Measure(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent);
var rootHeight = _rootView.MeasuredHeight;
if (_rootWidth == 0)
{
_rootWidth = _rootView.MeasuredWidth;
}
var screenWidth = _windowManager.DefaultDisplay.Width;
var screenHeight = _windowManager.DefaultDisplay.Height;
// Get x coord of top left popup
if ((anchorRect.Left + _rootWidth) > screenWidth)
{
windowLocation.X = anchorRect.Left - (_rootWidth - anchor.Width);
windowLocation.X = (windowLocation.X < 0) ? 0 : windowLocation.X;
arrowPos = anchorRect.CenterX() - windowLocation.X;
}
else
{
if (anchor.Width > _rootWidth)
{
windowLocation.X = anchorRect.CenterX() - (_rootWidth / 2);
}
else
{
windowLocation.X = anchorRect.Left;
}
arrowPos = anchorRect.CenterX() - windowLocation.X;
}
var dyTop = anchorRect.Top;
var dyBottom = screenHeight - anchorRect.Bottom;
var onTop = (dyTop > dyBottom);
if (onTop)
{
if (rootHeight > dyTop)
{
windowLocation.Y = 15;
}
else
{
windowLocation.Y = anchorRect.Top - rootHeight;
}
}
else
{
windowLocation.Y = anchorRect.Bottom;
}
ShowArrow(onTop ? Resource.Id.arrow_down : Resource.Id.arrow_up, arrowPos);
SetAnimationStyle(animationStyle, screenWidth, anchorRect.CenterX(), onTop);
_window.ShowAtLocation(anchor, GravityFlags.NoGravity, windowLocation.X, windowLocation.Y);
}
void SetAnimationStyle(QuickActionAnimationStyle animationStyle, int screenWidth, int requestedX, bool onTop)
{
var arrowPos = requestedX - _arrowUp.MeasuredWidth / 2;
switch (animationStyle)
{
case QuickActionAnimationStyle.GrowLeft:
_window.AnimationStyle = onTop ? Resource.Style.Animations_PopUpMenu_Left : Resource.Style.Animations_PopDownMenu_Left;
break;
case QuickActionAnimationStyle.GrowRight:
_window.AnimationStyle = onTop ? Resource.Style.Animations_PopUpMenu_Right : Resource.Style.Animations_PopDownMenu_Right;
break;
case QuickActionAnimationStyle.GrowFromCenter:
_window.AnimationStyle = onTop ? Resource.Style.Animations_PopUpMenu_Center : Resource.Style.Animations_PopDownMenu_Center;
break;
case QuickActionAnimationStyle.Reflect:
_window.AnimationStyle = onTop ? Resource.Style.Animations_PopUpMenu_Reflect : Resource.Style.Animations_PopDownMenu_Reflect;
break;
case QuickActionAnimationStyle.Auto:
if (arrowPos <= screenWidth / 4)
{
_window.AnimationStyle = onTop ? Resource.Style.Animations_PopUpMenu_Left : Resource.Style.Animations_PopDownMenu_Left;
}
else if (arrowPos > screenWidth / 4 && arrowPos < 3 * (screenWidth / 4))
{
_window.AnimationStyle = onTop ? Resource.Style.Animations_PopUpMenu_Center : Resource.Style.Animations_PopDownMenu_Center;
}
else
{
_window.AnimationStyle = onTop ? Resource.Style.Animations_PopUpMenu_Right : Resource.Style.Animations_PopDownMenu_Right;
}
break;
}
}
/// <summary>
/// Show the arrow.
/// </summary>
/// <param name="whichArrow">arrow type resource id</param>
/// <param name="requestedX">distance from left screen</param>
void ShowArrow(int whichArrow, int requestedX)
{
var showArrow = (whichArrow == Resource.Id.arrow_up) ? _arrowUp : _arrowDown;
var hideArrow = (whichArrow == Resource.Id.arrow_up) ? _arrowDown : _arrowUp;
var arrowWidth = _arrowUp.MeasuredWidth;
showArrow.Visibility = ViewStates.Visible;
var param = (ViewGroup.MarginLayoutParams)showArrow.LayoutParameters;
param.LeftMargin = requestedX - arrowWidth / 2;
hideArrow.Visibility = ViewStates.Invisible;
}
void OnDismiss()
{
if (!_didAction)
{
return;
}
if (ActionItemDismissed != null)
{
ActionItemDismissed(this, new EventArgs());
}
}
void HandleTouchIntercepted(object sender, View.TouchEventArgs e)
{
if (e.Event.Action == MotionEventActions.Outside)
{
_window.Dismiss();
e.Handled = true;
}
else
{
e.Handled = false;
}
}
public virtual void Dismiss()
{
_window.Dismiss();
}
void PreShow()
{
if (_rootView == null)
{
throw new NullReferenceException("SetContentView was not called with a view to display.");
}
_window.SetBackgroundDrawable(Background ?? new BitmapDrawable());
// ReSharper disable AccessToStaticMemberViaDerivedType
_window.Width = WindowManagerLayoutParams.WrapContent;
_window.Height = WindowManagerLayoutParams.WrapContent;
// ReSharper restore AccessToStaticMemberViaDerivedType
_window.Touchable = true;
_window.Focusable = true;
_window.OutsideTouchable = true;
_window.ContentView = _rootView;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using Mono.Cecil;
using UnityEngine;
using ScrollsModLoader.Interfaces;
using System.Net;
namespace Battlelog.Mod
{
public struct teleinfo
{
public string player;
public string unit;
public string position;
public teleinfo(string p, string u, string pos)
{
this.player = p;
this.unit = u;
this.position = pos;
}
}
public class BigLogEntry
{
public string type = "none";
public string targetPlayer;
public string targetname;
public string targetDmg;
public string dmgtype;
public string targetHeal;
public string sacrifice;
public string playedCard;
public string positiontext;
public string abilityname;
public bool killedidol = false;
public bool ignoresummon = false;
public bool ignoreselectedtiles = false;
public string turnstartmessage;
public string sourcePlayer;
public string sourcename;
public List<teleinfo> teleportinfo;
public static string getLogfromBigLog(BigLogEntry ble, Settings settns)
{
string retval = "";
string targetname = "";
string sourcetargetname = "";
if(ble.targetname != null)
{
targetname = ble.targetname;
if (settns.showNames)
{
targetname = ble.targetname.Replace("00CC01", "5959FF");
targetname = targetname.Replace("FF4718", "5959FF");
}
}
if (ble.sourcename != null)
{
sourcetargetname = ble.sourcename;
if (settns.showNames)
{
sourcetargetname = ble.sourcename.Replace("00CC01", "5959FF");
sourcetargetname = sourcetargetname.Replace("FF4718", "5959FF");
}
}
if (ble.type == "sac")
{
retval = ble.targetPlayer + " sacrifices for " + ble.sacrifice;
}
if (ble.type == "playcard")
{
retval = ble.targetPlayer + " played " + targetname;
}
if (ble.type == "turn")
{
retval = ble.turnstartmessage;
}
if (ble.type == "summon")
{
retval = ble.targetPlayer + " summoned a " + targetname + ((settns.showCoordinates) ? ble.positiontext : "");
if (ble.ignoresummon && !settns.showsummon) retval = "";
}
if (ble.type == "idoldmg")
{
retval = ble.targetPlayer + "'s idol" + ((settns.showCoordinates) ? ble.positiontext : "") + " got " + ble.targetDmg + " dmg";
if (ble.killedidol)
{
retval += " and was killed";
}
}
if (ble.type == "idolheal")
{
retval = ble.targetPlayer + "'s idol" + ((settns.showCoordinates) ? ble.positiontext : "") + " is healed by " + ble.targetHeal;
if (ble.targetHeal == "0") retval = "";
}
if (ble.type == "dmgunit")
{
retval = ((settns.showNames) ? ble.targetPlayer + "'s " : "") + targetname + ((settns.showCoordinates) ? ble.positiontext : "") + " got " + ble.targetDmg + " " + ble.dmgtype + " dmg from " + ((settns.showNames) ? ble.sourcePlayer + "'s " : "") + sourcetargetname;
}
if (ble.type == "healunit")
{
retval = ((settns.showNames) ? ble.targetPlayer + "'s " : "") + targetname + ((settns.showCoordinates) ? ble.positiontext : "") + " is healed by " + ble.targetHeal + " from " + ((settns.showNames) ? ble.sourcePlayer + "'s " : "") + sourcetargetname;
if (ble.targetHeal == "0") retval = "";
}
if (ble.type == "enchantunit")
{
retval = ((settns.showNames) ? ble.targetPlayer + "'s " : "") + targetname + ((settns.showCoordinates) ? ble.positiontext : "") + " was enchanted";
}
if (ble.type == "ability")
{
if (ble.abilityname != "Move" )//|| (settns.showMove))
{
retval = "the Ability " + ble.abilityname + " of " + ((settns.showNames) ? ble.targetPlayer + "'s " : "") + targetname + ((settns.showCoordinates) ? ble.positiontext : "") + " was activated";
}
}
if (ble.type == "ruleupdate")
{
retval = ((settns.showNames) ? ble.targetPlayer + "'s " : "") + targetname + "'s lingering effect lasts for " + ble.targetDmg + " rounds";
}
if (ble.type == "rulefade")
{
retval = ((settns.showNames) ? ble.targetPlayer + "'s " : "") + targetname + "'s lingering effect fades";
}
if (ble.type == "removeunit")
{
retval = ((settns.showNames) ? ble.targetPlayer + "'s " : "") + targetname + ((settns.showCoordinates) ? ble.positiontext : "") + " was " + ble.targetDmg;
}
if (ble.type == "teleport")
{
int unitss = 0;
for (int i = 0; i < ble.teleportinfo.Count; i++)
{
teleinfo ti = ble.teleportinfo[i];
string name = ti.player;
string unitname = ti.unit;
string pos = ti.position;
if (settns.showNames)
{
unitname = unitname.Replace("00CC01", "5959FF");
unitname = unitname.Replace("FF4718", "5959FF");
}
if (retval != "") retval += ", ";
retval += ((settns.showNames) ? name + "'s " : "") + unitname + ((settns.showCoordinates) ? pos : "");
unitss++;
}
retval += ((unitss >= 2) ? " are " : " is ") + "teleported";
}
if (ble.type == "selectTiles")
{
string target = "";
for (int i = 0; i < ble.teleportinfo.Count; i++)
{
teleinfo ti = ble.teleportinfo[i];
string name = ti.player;
string unitname = ti.unit;
string pos = ti.position;
if (settns.showNames)
{
unitname = unitname.Replace("00CC01", "5959FF");
unitname = unitname.Replace("FF4718", "5959FF");
}
if (target != "") target += " and ";
target += ((settns.showNames) ? name + "'s " : "") + unitname + ((settns.showCoordinates) ? pos : "");
}
retval = ((settns.showNames) ? ble.targetPlayer + "'s " : "") + targetname + " targets " + target;
if (ble.ignoreselectedtiles) retval = "";
}
if (ble.type == "moveunit" && settns.showMove)
{
retval = ((settns.showNames) ? ble.targetPlayer + "'s " : "") + targetname + ((settns.showCoordinates) ? ble.positiontext : "") + " was moved" + ((settns.showCoordinates) ? ble.targetDmg : "");
}
return retval;
}
public static List<string> getLogsfromBigLogList(List<BigLogEntry> bleList, Settings settns)
{
List<string> retval = new List<string>();
foreach (BigLogEntry ble in bleList)
{
string val = BigLogEntry.getLogfromBigLog(ble, settns);
if (val != "") retval.Add(val);
}
return retval;
}
}
public class Mod : BaseMod, ICommListener
{
Dictionary<long, TileColor> cardIdColorDatabase = new Dictionary<long, TileColor>();
public List<BigLogEntry> bigBattleLog = new List<BigLogEntry>();
public List<String> battlelog = new List<string>();
private BattleMode bm = null;
private BattleModeUI bmui = null;
private Drawstuff ds;
private bool loadedguiSkin = false;
private GUISkin guiSkin;
private bool ignoreSelectTiles = false;
private bool ignoreOneSummone = false;
private FieldInfo currentEffectField=typeof(BattleMode).GetField("currentEffect", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo hm = typeof(BattleMode).GetMethod("handleGameChatMessage", BindingFlags.NonPublic | BindingFlags.Instance);
private MethodInfo getplayer;
public Settings sttngs;
public Mod()
{
this.loadGuiSkin();
MethodInfo[] mis = typeof(BattleMode).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
Console.WriteLine("------------------");
foreach (MethodInfo mi in mis)
{
/*Console.WriteLine(mi.Name);
foreach (ParameterInfo pi in mi.GetParameters())
{
Console.WriteLine(pi.ParameterType.Name);
} */
if (mi.Name == "getPlayer")
{
if ((mi.GetParameters()).Length == 1 && (mi.GetParameters())[0].ParameterType.Name == "TileColor")
{
this.getplayer = mi;
//Console.WriteLine("getplayer found with " + mi.GetParameters()[0].Name + " as param");
}
}
}
try {
App.Communicator.addListener(this);
} catch {}
string recordFolder = this.OwnFolder(); // +System.IO.Path.DirectorySeparatorChar;
sttngs = new Settings(recordFolder);
Console.WriteLine("loaded Recorder");
}
private void loadGuiSkin()
{
this.guiSkin = (GUISkin)ResourceManager.Load("_GUISkins/Lobby");
}
public static string GetName()
{
return "BattleLog";
}
public static int GetVersion()
{
return 10;
}
public void handleMessage(Message msg)
{
}
public void onConnect(OnConnectData ocd)
{
return;
}
public static MethodDefinition[] GetHooks(TypeDefinitionCollection scrollsTypes, int version)
{
try {
MethodDefinition[] defs = new MethodDefinition[] {
//scrollsTypes["BattleMode"].Methods.GetMethod("effectDone")[0],
scrollsTypes["BattleMode"].Methods.GetMethod("Start")[0],
//scrollsTypes["BattleMode"].Methods.GetMethod("OnGUI")[0], // not needed anymore (we do it cleverer!)
scrollsTypes["BattleMode"].Methods.GetMethod("forceRunEffect", new Type[]{typeof(EffectMessage)}),
};
return defs;
} catch {
return new MethodDefinition[] {};
}
}
public override bool WantsToReplace (InvocationInfo info)
{
return false;
}
public override void ReplaceMethod (InvocationInfo info, out object returnValue)
{
returnValue = false;
}
public override void BeforeInvoke(InvocationInfo info)
{
if (info.target is BattleMode && info.targetMethod.Equals("forceRunEffect"))
{
EffectMessage currentEffect = (EffectMessage) info.arguments[0];
string type = currentEffect.type;
string log = "";
this.bm = info.target as BattleMode;
Console.WriteLine("####### current type = " + type);
int old = this.bigBattleLog.Count;
try
{
if (type == "CardSacrificed")
{
log = this.getCardSacrifieceMessage(currentEffect as EMCardSacrificed);
}
if (type == "CardPlayed")
{
log = this.getCardPlayedMessage(currentEffect as EMCardPlayed);
}
if (type == "TurnBegin")
{
log = this.getTurnBeginMessage(currentEffect as EMTurnBegin);
}
if (type == "SummonUnit")
{
log = this.getSummonMessage(currentEffect as EMSummonUnit);
}
if (type == "DamageIdol")
{
log = this.getDamageIdolMessage(currentEffect as EMDamageIdol);
}
if (type == "HealIdol")
{
log = this.getHealIdolMessage(currentEffect as EMHealIdol);
}
if (type == "DamageUnit")
{
log = this.getDamageUnitMessage(currentEffect as EMDamageUnit);
}
if (type == "HealUnit")
{
log = this.getHealUnitMessage(currentEffect as EMHealUnit);
}
if (type == "UnitActivateAbility")
{
log = this.getUnitActivateAbilityMessage(currentEffect as EMUnitActivateAbility);
}
if (type == "RuleUpdate")
{
log = this.getRuleUpdateMessage(currentEffect as EMRuleUpdate);
}
if (type == "RuleRemoved")
{
log = this.getRuleRemoveMessage(currentEffect as EMRuleRemoved);
}
if (type == "RemoveUnit")
{
log = this.getUnitRemoveMessage(currentEffect as EMRemoveUnit);
}
if (type == "TeleportUnits")
{
log = this.getUnitTeleportMessage(currentEffect as EMTeleportUnits);
}
if (type == "SelectedTiles")
{
log = this.getSelectedTilesMessage(currentEffect as EMSelectedTiles);
}
if (type == "MoveUnit")
{
log = this.getUnitMoveMessage(currentEffect as EMMoveUnit);
}
}
catch
{
log = "<_<";
}
Console.WriteLine();
int newone = this.bigBattleLog.Count;
string newlog = "";
if (newone != old)
{
BigLogEntry ble = this.bigBattleLog[this.bigBattleLog.Count - 1];
newlog = BigLogEntry.getLogfromBigLog(ble, this.sttngs);
}
/*if (log != newlog)
{
this.sendMessage("error");
this.sendMessage(log);
}*/
this.sendMessage(newlog);
}
if (info.target is BattleMode && info.targetMethod.Equals("effectDone"))
{
EffectMessage currentEffect = ((EffectMessage)currentEffectField.GetValue(info.target));
}
}
private void sendMessage(string s)
{
if (s == "") return;
GameChatMessageMessage gcmm = new GameChatMessageMessage();
gcmm.from = "BL";
gcmm.text = s;
//hm.Invoke(this.bm, new object[] { gcmm });
this.battlelog.Add(s);
this.ds.scrollDown();
Console.WriteLine("#######"+s);
}
public override void AfterInvoke(InvocationInfo info, ref object returnValue)
{
/*if (info.target is BattleMode && info.targetMethod.Equals("OnGUI"))
{
try
{
this.ds.draw(this.battlelog);
}
catch
{
Console.WriteLine("typical unity error :D");
if (this.ds.scrollbarWasDown)
{
this.ds.chatScroll.y = int.MaxValue;
}
}
}*/
if (info.target is BattleMode && info.targetMethod.Equals("Start"))
{
this.ds = new GameObject("drawing stuff").AddComponent<Drawstuff>();
this.ds.moddingmod = this;
//this.ds = Drawstuff.Instance;
this.ds.setSettings(this.sttngs);
this.battlelog.Clear();
this.bigBattleLog.Clear();
}
}
public string getCardSacrifieceMessage(EMCardSacrificed eMCardSacrificed)
{
string retval = "";
string name = getName(eMCardSacrificed.color);
string sacrifice = ((!eMCardSacrificed.isForCards()) ? (this.getResourceString(eMCardSacrificed.resource)) : "SCROLLS");
retval = name + " sacrifices for " + sacrifice;
BigLogEntry ble = new BigLogEntry();
ble.sacrifice = sacrifice;
ble.targetPlayer = name;
ble.type = "sac";
this.bigBattleLog.Add(ble);
return retval;
}
public string getCardPlayedMessage(EMCardPlayed eMCardPlayed)
{
string retval = "";
TileColor col = TileColor.white;
if (eMCardPlayed.getRawText().StartsWith("{\"CardPlayed\":{\"color\":\"black")) col = TileColor.black;
string name = getName(col);
if (this.cardIdColorDatabase.ContainsKey(eMCardPlayed.card.id))
{
this.cardIdColorDatabase[eMCardPlayed.card.id] = col;
}
else
{
this.cardIdColorDatabase.Add(eMCardPlayed.card.id, col);
}
string playedcard = getUnitname(eMCardPlayed.card.getName(), col);
retval = name + " played " + playedcard;
if (eMCardPlayed.card.getCardType().kind == CardType.Kind.CREATURE || eMCardPlayed.card.getCardType().kind == CardType.Kind.STRUCTURE)
{
this.ignoreSelectTiles = true;
this.ignoreOneSummone = true;
}
BigLogEntry ble = new BigLogEntry();
ble.type = "playcard";
ble.targetPlayer = name;
ble.targetname = playedcard;
this.bigBattleLog.Add(ble);
return retval;
}
public string getTurnBeginMessage(EMTurnBegin eMTurnBegin)
{
string retval = "";
string name = getName(eMTurnBegin.color);
retval = "--- turn " + eMTurnBegin.turn + " ---" + "\r\n" +name + "'s turn starts";
BigLogEntry ble = new BigLogEntry();
ble.type = "turn";
ble.turnstartmessage = retval;
this.bigBattleLog.Add(ble);
return retval;
}
public string getSummonMessage(EMSummonUnit esu)
{
string retval = "";
TileColor col = TileColor.white;
if (esu.getRawText().StartsWith("{\"SummonUnit\":{\"target\":{\"color\":\"black")) col = TileColor.black;
string name = getName(col);
string position = " on " + this.getPosition(esu.target);
string unitname = getUnitname(esu.card.getName(), col);
retval = name + " summoned a " + unitname + ((this.sttngs.showCoordinates) ? position : "");
//if (!sttngs.showNames) retval = getUnitname(esu.card.getName()) + " was summoned";
BigLogEntry ble = new BigLogEntry();
ble.type = "summon";
ble.targetPlayer = name;
ble.targetname = unitname;
ble.positiontext = position;
ble.ignoresummon = this.ignoreOneSummone;
this.bigBattleLog.Add(ble);
if (this.ignoreOneSummone)
{
this.ignoreOneSummone = false;
return "";
}
return retval;
}
public string getDamageIdolMessage(EMDamageIdol edi)
{
string retval = "";
string name = getName(edi.idol.color);
string pos = " on " + (edi.idol.position + 1);
string dmg = this.getDmg(edi.amount);
retval = name + "'s idol" + ((this.sttngs.showCoordinates) ? pos : "") + " got " + dmg + " dmg";
BigLogEntry ble = new BigLogEntry();
ble.type = "idoldmg";
ble.targetPlayer = name;
ble.positiontext = pos;
ble.targetDmg = dmg;
if (edi.idol.hp <= 0 && this.bm.getIdol(edi.idol.color, edi.idol.position).getHitPoints() >= 1)
{
retval += " and was killed";
ble.killedidol = true;
}
this.bigBattleLog.Add(ble);
return retval;
}
public string getHealIdolMessage(EMHealIdol ehi)
{
string retval = "";
string name = getName(ehi.idol.color);
string pos = " on " + (ehi.idol.position + 1);
string heal = getHeal(ehi.amount);
retval = name + "'s idol" + ((this.sttngs.showCoordinates) ? pos : "") + " is healed by " + heal;
BigLogEntry ble = new BigLogEntry();
ble.type = "idolheal";
ble.targetPlayer = name;
ble.positiontext = pos;
ble.targetHeal = heal;
this.bigBattleLog.Add(ble);
if (ehi.amount == 0) return "";
return retval;
}
public string getDamageUnitMessage(EMDamageUnit edi)
{
//if (edi.amount <= 0) return "";
string retval = "";
string name = getName(edi.targetTile.color);
string uname = bm.getUnit(edi.targetTile).getName();
string unitname = getUnitname(uname, edi.targetTile.color);
string pos = " on " + getPosition(edi.targetTile);
string dmgtype = edi.damageType + "" ;
string dmg = this.getDmg(edi.amount);
string dmgsourceplayer = getName(edi.sourceCard.id);
string dmgsourceunit = getUnitname(edi.sourceCard.getName(), edi.sourceCard.id);
//edi.attackType.ToString()
retval = ((sttngs.showNames) ? name + "'s " : "") + unitname + ((this.sttngs.showCoordinates) ? pos : "") + " got " + dmg + " " + dmgtype + " dmg from " + ((sttngs.showNames) ? dmgsourceplayer + "'s " : "") + dmgsourceunit;
BigLogEntry ble = new BigLogEntry();
ble.type = "dmgunit";
ble.targetPlayer = name;
ble.targetname = unitname;
ble.positiontext = pos;
ble.dmgtype = dmgtype;
ble.targetDmg = dmg;
ble.sourcename = dmgsourceunit;
ble.sourcePlayer = dmgsourceplayer;
this.bigBattleLog.Add(ble);
return retval;
}
public string getHealUnitMessage(EMHealUnit ehi)
{
string retval = "";
string name = getName(ehi.target.color);
string uname = bm.getUnit(ehi.target).getName();
string unitname = getUnitname(uname, ehi.target.color);
string pos = " on " + getPosition(ehi.target);
string heal = getHeal(ehi.amount);
long sourcid = 0;
int type = 1;
if (ehi.getRawText().Contains("\"sourceCard\":{\"id\":"))
{
string si = ehi.getRawText().Split(new string[] { "\"sourceCard\":{\"id\":" }, StringSplitOptions.RemoveEmptyEntries)[1];
string typetemp = ehi.getRawText().Split(new string[] { ",\"typeId\":" }, StringSplitOptions.RemoveEmptyEntries)[1];
si = si.Split(',')[0];
typetemp = typetemp.Split(',')[0];
sourcid = Convert.ToInt64(si);
type = Convert.ToInt32(typetemp);
}
string dmgsourceplayer = getName(sourcid);
string dmgsourceunit = getUnitname(getUnitNameFromType(type), sourcid);
retval = ((sttngs.showNames) ? name + "'s " : "") + unitname + ((this.sttngs.showCoordinates) ? pos : "") + " is healed by " + heal + " from " + ((sttngs.showNames) ? dmgsourceplayer + "'s " : "") + dmgsourceunit;
BigLogEntry ble = new BigLogEntry();
ble.type = "healunit";
ble.targetPlayer = name;
ble.targetname = unitname;
ble.positiontext = pos;
ble.targetHeal = heal;
ble.sourcename = dmgsourceunit;
ble.sourcePlayer = dmgsourceplayer;
this.bigBattleLog.Add(ble);
if (ehi.amount == 0) return "";
return retval;
}
public string getEnchantUnitMessage(EMEnchantUnit edi)
{
string retval = "";
string name = getName(edi.target.color);
string uname = bm.getUnit(edi.target).getName();
string unitname = getUnitname(uname, edi.target.color);
string pos = " on " + getPosition(edi.target);
retval = ((sttngs.showNames) ? name + "'s " : "") + unitname + ((this.sttngs.showCoordinates) ? pos : "") + " was enchanted";
BigLogEntry ble = new BigLogEntry();
ble.type = "enchantunit";
ble.targetPlayer = name;
ble.targetname = unitname;
ble.positiontext = pos;
this.bigBattleLog.Add(ble);
return retval;
}
public string getUnitActivateAbilityMessage(EMUnitActivateAbility ehi)
{
this.ignoreSelectTiles = true;
string retval = "";
string name = getName(ehi.unit.color);
string uname = bm.getUnit(ehi.unit.color, ehi.unit.row, ehi.unit.column).getName();
string unitname = getUnitname(uname, ehi.unit.color);
string pos = " on " + getPosition(ehi.unit);
string ability = ehi.name;
retval = "the Ability " + ability + " of " + ((sttngs.showNames) ? name + "'s " : "") + unitname + ((this.sttngs.showCoordinates) ? pos : "") + " was activated";
BigLogEntry ble = new BigLogEntry();
ble.type = "ability";
ble.targetPlayer = name;
ble.targetname = unitname;
ble.positiontext = pos;
ble.abilityname = ability;
this.bigBattleLog.Add(ble);
if (ehi.name == "Move")
{
this.ignoreSelectTiles = true;
return "";
}
return retval;
}
private string getRuleUpdateMessage(EMRuleUpdate ehi) //lingering spells
{
string retval = "";
string name = getName(ehi.color);
string uname = ehi.card.getName();
string unitname = getUnitname(uname, ehi.color);
retval = ((sttngs.showNames) ? name + "'s " : "") + unitname + "'s lingering effect lasts for " + ehi.roundsLeft + " rounds";
BigLogEntry ble = new BigLogEntry();
ble.type = "ruleupdate";
ble.targetPlayer = name;
ble.targetname = unitname;
ble.targetDmg = ehi.roundsLeft+"";
this.bigBattleLog.Add(ble);
return retval;
}
private string getRuleRemoveMessage(EMRuleRemoved ehi) //lingering spells
{
string retval = "";
string name = getName(ehi.color);
string uname = ehi.card.getName();
string unitname = getUnitname(uname, ehi.color);
retval = ((sttngs.showNames) ? name + "'s " : "") + unitname + "'s lingering effect fades";
BigLogEntry ble = new BigLogEntry();
ble.type = "rulefade";
ble.targetPlayer = name;
ble.targetname = unitname;
this.bigBattleLog.Add(ble);
return retval;
}
private string getUnitRemoveMessage(EMRemoveUnit ehi)
{
string retval = "";
string name = getName(ehi.tile.color);
string uname = bm.getUnit(ehi.tile).getName();
string unitname = getUnitname(uname, ehi.tile.color);
string pos = " on " + getPosition(ehi.tile);
string type = "removed";
if (EMRemoveUnit.RemovalType.DESTROY == ehi.removalType) type = "destroyed";
retval = ((sttngs.showNames) ? name + "'s " : "") + unitname + ((this.sttngs.showCoordinates) ? pos : "") + " was " + type;
BigLogEntry ble = new BigLogEntry();
ble.type = "removeunit";
ble.targetPlayer = name;
ble.targetname = unitname;
ble.positiontext = pos;
ble.targetDmg = type;
this.bigBattleLog.Add(ble);
return retval;
}
private string getUnitTeleportMessage(EMTeleportUnits ehi)
{
string retval = "";
BigLogEntry ble = new BigLogEntry();
ble.type = "teleport";
ble.teleportinfo = new List<teleinfo>();
for (int i = 0; i < ehi.units.Length; i++)
{
TeleportInfo ti = ehi.units[i];
string name = getName(ti.from.color);
string uname = bm.getUnit(ti.from).getName();
string unitname = getUnitname(uname, ti.from.color);
string pos = " on " + getPosition(ti.from);
if (retval != "") retval += ", ";
retval += ((sttngs.showNames) ? name + "'s " : "") + unitname + ((this.sttngs.showCoordinates) ? pos : "");
ble.teleportinfo.Add(new teleinfo(name, unitname, pos));
}
retval += " are teleported";
this.bigBattleLog.Add(ble);
return retval;
}
private string getSelectedTilesMessage(EMSelectedTiles est)
{
string name = getName(est.color);
string uname = getUnitname(est.card.getName(), est.color);
BigLogEntry ble = new BigLogEntry();
ble.type = "selectTiles";
ble.targetPlayer = name;
ble.targetname = uname;
string target = "";
if (est.tiles.Length >= 1 && this.bm.getUnit(est.tiles[0]) != null)
{
string tname = this.getName(est.tiles[0].color);
string tu = getUnitname(this.bm.getUnit(est.tiles[0]).getName(), est.tiles[0].color);
string tp = " on " + getPosition(est.tiles[0]);
target = ((sttngs.showNames) ? tname + "'s " : "") + tu + ((this.sttngs.showCoordinates) ? tp : "");
ble.teleportinfo = new List<teleinfo>();
ble.teleportinfo.Add(new teleinfo(tname, tu, tp));
}
if (est.tiles.Length >= 2 && this.bm.getUnit(est.tiles[1]) != null)
{
string tname = this.getName(est.tiles[1].color);
string tu = getUnitname(this.bm.getUnit(est.tiles[1]).getName(), est.tiles[1].color);
string tp = " on " + getPosition(est.tiles[1]);
target += " and " + ((sttngs.showNames) ? tname + "'s " : "") + tu + ((this.sttngs.showCoordinates) ? tp : "");
ble.teleportinfo.Add(new teleinfo(tname, tu, tp));
}
if (target == "") return ""; // todo really?
ble.ignoreselectedtiles = true;
this.bigBattleLog.Add(ble);
if (this.ignoreSelectTiles)
{
this.ignoreSelectTiles = false;
return "";
}
return ((sttngs.showNames) ? name + "'s " : "") + uname + " targets " + target;
}
private string getUnitMoveMessage(EMMoveUnit emu)
{
string retval = "";
string name = getName(emu.from.color);
string uname = bm.getUnit(emu.from).getName();
string unitname = getUnitname(uname, emu.from.color);
string pos = " on " + getPosition(emu.from);
string pos2 = " to " + getPosition(emu.to);
retval = ((sttngs.showNames) ? name + "'s " : "") + unitname + ((this.sttngs.showCoordinates) ? pos : "") + " was moved " + ((this.sttngs.showCoordinates) ? pos2 : "");
BigLogEntry ble = new BigLogEntry();
ble.type = "moveunit";
ble.targetPlayer = name;
ble.targetname = unitname;
ble.positiontext = pos;
ble.targetDmg = pos2;
this.bigBattleLog.Add(ble);
return retval;
}
private string getDmg(int dmg)
{
return "<color=#FF0000>" + dmg + "</color>";
}
private string getHeal(int heal)
{
return "<color=#FF1919>" + heal + "</color>";
}
private string getName(TileColor c)
{
string name = "";
name = ((BMPlayer)getplayer.Invoke(this.bm, new object[] { c })).name;
if (this.bm.isLeftColor(c))
{
name = "<color=#00CC00>" + name + "</color>";
}
else
{
name = "<color=#FF4719>" + name + "</color>";
}
return name;
}
private string getUnitname(string name, TileColor c)
{
string col = "5959FF";
if (this.bm.isLeftColor(c))
{
col = "00CC01";
}
else
{
col = "FF4718";
}
return "<color=#" + col + ">" + name + "</color>";
}
private string getUnitname(string name, long cardid)
{
string col = "5959FF";
if (this.cardIdColorDatabase.ContainsKey(cardid))
{
TileColor c = this.cardIdColorDatabase[cardid];
if (this.bm.isLeftColor(c))
{
col = "00CC01";
}
else
{
col = "FF4718";
}
}
return "<color=#" + col + ">" + name + "</color>";
}
private string getName(long cardid)
{
string name = "";
if (this.cardIdColorDatabase.ContainsKey(cardid))
{
TileColor c = this.cardIdColorDatabase[cardid];
name = ((BMPlayer)getplayer.Invoke(this.bm, new object[] { c })).name;
if (this.bm.isLeftColor(c))
{
name = "<color=#00CC00>" + name + "</color>";
}
else
{
name = "<color=#FF4719>" + name + "</color>";
}
}
else
{
name = "unknown";
}
return name;
}
private string getUnitNameFromType(int type)
{
string retval = "";
retval = CardTypeManager.getInstance().get(type).name;
return retval;
}
private string getPosition(TilePosition tp)
{
string pos = (tp.row + 1) + "," + (tp.column + 1);
return pos;
}
private string getResourceString(ResourceType res)
{
string retval = "";
if (res == ResourceType.DECAY) retval = "<color=#CC00FF>" + "DECAY" + "</color>";
if (res == ResourceType.ORDER) retval = "<color=#3399FF>" + "ORDER" + "</color>";
if (res == ResourceType.ENERGY) retval = "<color=#FFFF33>" + "ENERGY" + "</color>";
if (res == ResourceType.GROWTH) retval = "<color=#66E066>" + "GROWTH" + "</color>";
if (res == ResourceType.SPECIAL) retval = "<color=#FFFFFF>" + "WILD" + "</color>";
return retval;
}
}
}
| |
// 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 RegexNode class is internal to the Regex package.
// It is built into a parsed tree for a regular expression.
// Implementation notes:
//
// Since the node tree is a temporary data structure only used
// during compilation of the regexp to integer codes, it's
// designed for clarity and convenience rather than
// space efficiency.
//
// RegexNodes are built into a tree, linked by the _children list.
// Each node also has a _parent and _ichild member indicating
// its parent and which child # it is in its parent's list.
//
// RegexNodes come in as many types as there are constructs in
// a regular expression, for example, "concatenate", "alternate",
// "one", "rept", "group". There are also node types for basic
// peephole optimizations, e.g., "onerep", "notsetrep", etc.
//
// Because perl 5 allows "lookback" groups that scan backwards,
// each node also gets a "direction". Normally the value of
// boolean _backward = false.
//
// During parsing, top-level nodes are also stacked onto a parse
// stack (a stack of trees). For this purpose we have a _next
// pointer. [Note that to save a few bytes, we could overload the
// _parent pointer instead.]
//
// On the parse stack, each tree has a "role" - basically, the
// nonterminal in the grammar that the parser has currently
// assigned to the tree. That code is stored in _role.
//
// Finally, some of the different kinds of nodes have data.
// Two integers (for the looping constructs) are stored in
// _operands, an object (either a string or a set)
// is stored in _data
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace System.Text.RegularExpressions
{
internal sealed class RegexNode
{
// RegexNode types
// The following are leaves, and correspond to primitive operations
internal const int Oneloop = RegexCode.Oneloop; // c,n a*
internal const int Notoneloop = RegexCode.Notoneloop; // c,n .*
internal const int Setloop = RegexCode.Setloop; // set,n \d*
internal const int Onelazy = RegexCode.Onelazy; // c,n a*?
internal const int Notonelazy = RegexCode.Notonelazy; // c,n .*?
internal const int Setlazy = RegexCode.Setlazy; // set,n \d*?
internal const int One = RegexCode.One; // char a
internal const int Notone = RegexCode.Notone; // char . [^a]
internal const int Set = RegexCode.Set; // set [a-z] \w \s \d
internal const int Multi = RegexCode.Multi; // string abcdef
internal const int Ref = RegexCode.Ref; // index \1
internal const int Bol = RegexCode.Bol; // ^
internal const int Eol = RegexCode.Eol; // $
internal const int Boundary = RegexCode.Boundary; // \b
internal const int Nonboundary = RegexCode.Nonboundary; // \B
internal const int ECMABoundary = RegexCode.ECMABoundary; // \b
internal const int NonECMABoundary = RegexCode.NonECMABoundary; // \B
internal const int Beginning = RegexCode.Beginning; // \A
internal const int Start = RegexCode.Start; // \G
internal const int EndZ = RegexCode.EndZ; // \Z
internal const int End = RegexCode.End; // \z
// Interior nodes do not correspond to primitive operations, but
// control structures compositing other operations
// Concat and alternate take n children, and can run forward or backwards
internal const int Nothing = 22; // []
internal const int Empty = 23; // ()
internal const int Alternate = 24; // a|b
internal const int Concatenate = 25; // ab
internal const int Loop = 26; // m,x * + ? {,}
internal const int Lazyloop = 27; // m,x *? +? ?? {,}?
internal const int Capture = 28; // n ()
internal const int Group = 29; // (?:)
internal const int Require = 30; // (?=) (?<=)
internal const int Prevent = 31; // (?!) (?<!)
internal const int Greedy = 32; // (?>) (?<)
internal const int Testref = 33; // (?(n) | )
internal const int Testgroup = 34; // (?(...) | )
// RegexNode data members
internal int _type;
internal List<RegexNode> _children;
internal string _str;
internal char _ch;
internal int _m;
internal int _n;
internal readonly RegexOptions _options;
internal RegexNode _next;
internal RegexNode(int type, RegexOptions options)
{
_type = type;
_options = options;
}
internal RegexNode(int type, RegexOptions options, char ch)
{
_type = type;
_options = options;
_ch = ch;
}
internal RegexNode(int type, RegexOptions options, string str)
{
_type = type;
_options = options;
_str = str;
}
internal RegexNode(int type, RegexOptions options, int m)
{
_type = type;
_options = options;
_m = m;
}
internal RegexNode(int type, RegexOptions options, int m, int n)
{
_type = type;
_options = options;
_m = m;
_n = n;
}
internal bool UseOptionR()
{
return (_options & RegexOptions.RightToLeft) != 0;
}
internal RegexNode ReverseLeft()
{
if (UseOptionR() && _type == Concatenate && _children != null)
{
_children.Reverse(0, _children.Count);
}
return this;
}
/// <summary>
/// Pass type as OneLazy or OneLoop
/// </summary>
internal void MakeRep(int type, int min, int max)
{
_type += (type - One);
_m = min;
_n = max;
}
/// <summary>
/// Removes redundant nodes from the subtree, and returns a reduced subtree.
/// </summary>
internal RegexNode Reduce()
{
RegexNode n;
switch (Type())
{
case Alternate:
n = ReduceAlternation();
break;
case Concatenate:
n = ReduceConcatenation();
break;
case Loop:
case Lazyloop:
n = ReduceRep();
break;
case Group:
n = ReduceGroup();
break;
case Set:
case Setloop:
n = ReduceSet();
break;
default:
n = this;
break;
}
return n;
}
/// <summary>
/// Simple optimization. If a concatenation or alternation has only
/// one child strip out the intermediate node. If it has zero children,
/// turn it into an empty.
/// </summary>
internal RegexNode StripEnation(int emptyType)
{
switch (ChildCount())
{
case 0:
return new RegexNode(emptyType, _options);
case 1:
return Child(0);
default:
return this;
}
}
/// <summary>
/// Simple optimization. Once parsed into a tree, non-capturing groups
/// serve no function, so strip them out.
/// </summary>
internal RegexNode ReduceGroup()
{
RegexNode u;
for (u = this; u.Type() == Group;)
u = u.Child(0);
return u;
}
/// <summary>
/// Nested repeaters just get multiplied with each other if they're not
/// too lumpy
/// </summary>
internal RegexNode ReduceRep()
{
RegexNode u;
RegexNode child;
int type;
int min;
int max;
u = this;
type = Type();
min = _m;
max = _n;
for (; ;)
{
if (u.ChildCount() == 0)
break;
child = u.Child(0);
// multiply reps of the same type only
if (child.Type() != type)
{
int childType = child.Type();
if (!(childType >= Oneloop && childType <= Setloop && type == Loop ||
childType >= Onelazy && childType <= Setlazy && type == Lazyloop))
break;
}
// child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})?
// [but things like (a {2,})+ are not too lumpy...]
if (u._m == 0 && child._m > 1 || child._n < child._m * 2)
break;
u = child;
if (u._m > 0)
u._m = min = ((int.MaxValue - 1) / u._m < min) ? int.MaxValue : u._m * min;
if (u._n > 0)
u._n = max = ((int.MaxValue - 1) / u._n < max) ? int.MaxValue : u._n * max;
}
return min == int.MaxValue ? new RegexNode(Nothing, _options) : u;
}
/// <summary>
/// Simple optimization. If a set is a singleton, an inverse singleton,
/// or empty, it's transformed accordingly.
/// </summary>
internal RegexNode ReduceSet()
{
// Extract empty-set, one and not-one case as special
if (RegexCharClass.IsEmpty(_str))
{
_type = Nothing;
_str = null;
}
else if (RegexCharClass.IsSingleton(_str))
{
_ch = RegexCharClass.SingletonChar(_str);
_str = null;
_type += (One - Set);
}
else if (RegexCharClass.IsSingletonInverse(_str))
{
_ch = RegexCharClass.SingletonChar(_str);
_str = null;
_type += (Notone - Set);
}
return this;
}
/// <summary>
/// Basic optimization. Single-letter alternations can be replaced
/// by faster set specifications, and nested alternations with no
/// intervening operators can be flattened:
///
/// a|b|c|def|g|h -> [a-c]|def|[gh]
/// apple|(?:orange|pear)|grape -> apple|orange|pear|grape
/// </summary>
internal RegexNode ReduceAlternation()
{
// Combine adjacent sets/chars
bool wasLastSet;
bool lastNodeCannotMerge;
RegexOptions optionsLast;
RegexOptions optionsAt;
int i;
int j;
RegexNode at;
RegexNode prev;
if (_children == null)
return new RegexNode(Nothing, _options);
wasLastSet = false;
lastNodeCannotMerge = false;
optionsLast = 0;
for (i = 0, j = 0; i < _children.Count; i++, j++)
{
at = _children[i];
if (j < i)
_children[j] = at;
for (; ;)
{
if (at._type == Alternate)
{
for (int k = 0; k < at._children.Count; k++)
at._children[k]._next = this;
_children.InsertRange(i + 1, at._children);
j--;
}
else if (at._type == Set || at._type == One)
{
// Cannot merge sets if L or I options differ, or if either are negated.
optionsAt = at._options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
if (at._type == Set)
{
if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !RegexCharClass.IsMergeable(at._str))
{
wasLastSet = true;
lastNodeCannotMerge = !RegexCharClass.IsMergeable(at._str);
optionsLast = optionsAt;
break;
}
}
else if (!wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge)
{
wasLastSet = true;
lastNodeCannotMerge = false;
optionsLast = optionsAt;
break;
}
// The last node was a Set or a One, we're a Set or One and our options are the same.
// Merge the two nodes.
j--;
prev = _children[j];
RegexCharClass prevCharClass;
if (prev._type == One)
{
prevCharClass = new RegexCharClass();
prevCharClass.AddChar(prev._ch);
}
else
{
prevCharClass = RegexCharClass.Parse(prev._str);
}
if (at._type == One)
{
prevCharClass.AddChar(at._ch);
}
else
{
RegexCharClass atCharClass = RegexCharClass.Parse(at._str);
prevCharClass.AddCharClass(atCharClass);
}
prev._type = Set;
prev._str = prevCharClass.ToStringClass();
}
else if (at._type == Nothing)
{
j--;
}
else
{
wasLastSet = false;
lastNodeCannotMerge = false;
}
break;
}
}
if (j < i)
_children.RemoveRange(j, i - j);
return StripEnation(Nothing);
}
/// <summary>
/// Basic optimization. Adjacent strings can be concatenated.
///
/// (?:abc)(?:def) -> abcdef
/// </summary>
internal RegexNode ReduceConcatenation()
{
// Eliminate empties and concat adjacent strings/chars
bool wasLastString;
RegexOptions optionsLast;
RegexOptions optionsAt;
int i;
int j;
if (_children == null)
return new RegexNode(Empty, _options);
wasLastString = false;
optionsLast = 0;
for (i = 0, j = 0; i < _children.Count; i++, j++)
{
RegexNode at;
RegexNode prev;
at = _children[i];
if (j < i)
_children[j] = at;
if (at._type == Concatenate &&
((at._options & RegexOptions.RightToLeft) == (_options & RegexOptions.RightToLeft)))
{
for (int k = 0; k < at._children.Count; k++)
at._children[k]._next = this;
_children.InsertRange(i + 1, at._children);
j--;
}
else if (at._type == Multi ||
at._type == One)
{
// Cannot merge strings if L or I options differ
optionsAt = at._options & (RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
if (!wasLastString || optionsLast != optionsAt)
{
wasLastString = true;
optionsLast = optionsAt;
continue;
}
prev = _children[--j];
if (prev._type == One)
{
prev._type = Multi;
prev._str = Convert.ToString(prev._ch, CultureInfo.InvariantCulture);
}
if ((optionsAt & RegexOptions.RightToLeft) == 0)
{
if (at._type == One)
prev._str += at._ch.ToString();
else
prev._str += at._str;
}
else
{
if (at._type == One)
prev._str = at._ch.ToString() + prev._str;
else
prev._str = at._str + prev._str;
}
}
else if (at._type == Empty)
{
j--;
}
else
{
wasLastString = false;
}
}
if (j < i)
_children.RemoveRange(j, i - j);
return StripEnation(Empty);
}
internal RegexNode MakeQuantifier(bool lazy, int min, int max)
{
RegexNode result;
if (min == 0 && max == 0)
return new RegexNode(Empty, _options);
if (min == 1 && max == 1)
return this;
switch (_type)
{
case One:
case Notone:
case Set:
MakeRep(lazy ? Onelazy : Oneloop, min, max);
return this;
default:
result = new RegexNode(lazy ? Lazyloop : Loop, _options, min, max);
result.AddChild(this);
return result;
}
}
internal void AddChild(RegexNode newChild)
{
RegexNode reducedChild;
if (_children == null)
_children = new List<RegexNode>(4);
reducedChild = newChild.Reduce();
_children.Add(reducedChild);
reducedChild._next = this;
}
internal RegexNode Child(int i)
{
return _children[i];
}
internal int ChildCount()
{
return _children == null ? 0 : _children.Count;
}
internal int Type()
{
return _type;
}
#if DEBUG
internal static readonly string[] TypeStr = new string[] {
"Onerep", "Notonerep", "Setrep",
"Oneloop", "Notoneloop", "Setloop",
"Onelazy", "Notonelazy", "Setlazy",
"One", "Notone", "Set",
"Multi", "Ref",
"Bol", "Eol", "Boundary", "Nonboundary",
"ECMABoundary", "NonECMABoundary",
"Beginning", "Start", "EndZ", "End",
"Nothing", "Empty",
"Alternate", "Concatenate",
"Loop", "Lazyloop",
"Capture", "Group", "Require", "Prevent", "Greedy",
"Testref", "Testgroup"};
internal string Description()
{
StringBuilder ArgSb = new StringBuilder();
ArgSb.Append(TypeStr[_type]);
if ((_options & RegexOptions.ExplicitCapture) != 0)
ArgSb.Append("-C");
if ((_options & RegexOptions.IgnoreCase) != 0)
ArgSb.Append("-I");
if ((_options & RegexOptions.RightToLeft) != 0)
ArgSb.Append("-L");
if ((_options & RegexOptions.Multiline) != 0)
ArgSb.Append("-M");
if ((_options & RegexOptions.Singleline) != 0)
ArgSb.Append("-S");
if ((_options & RegexOptions.IgnorePatternWhitespace) != 0)
ArgSb.Append("-X");
if ((_options & RegexOptions.ECMAScript) != 0)
ArgSb.Append("-E");
switch (_type)
{
case Oneloop:
case Notoneloop:
case Onelazy:
case Notonelazy:
case One:
case Notone:
ArgSb.Append("(Ch = " + RegexCharClass.CharDescription(_ch) + ")");
break;
case Capture:
ArgSb.Append("(index = " + _m.ToString(CultureInfo.InvariantCulture) + ", unindex = " + _n.ToString(CultureInfo.InvariantCulture) + ")");
break;
case Ref:
case Testref:
ArgSb.Append("(index = " + _m.ToString(CultureInfo.InvariantCulture) + ")");
break;
case Multi:
ArgSb.Append("(String = " + _str + ")");
break;
case Set:
case Setloop:
case Setlazy:
ArgSb.Append("(Set = " + RegexCharClass.SetDescription(_str) + ")");
break;
}
switch (_type)
{
case Oneloop:
case Notoneloop:
case Onelazy:
case Notonelazy:
case Setloop:
case Setlazy:
case Loop:
case Lazyloop:
ArgSb.Append("(Min = " + _m.ToString(CultureInfo.InvariantCulture) + ", Max = " + (_n == int.MaxValue ? "inf" : Convert.ToString(_n, CultureInfo.InvariantCulture)) + ")");
break;
}
return ArgSb.ToString();
}
internal const string Space = " ";
internal void Dump()
{
List<int> Stack = new List<int>();
RegexNode CurNode;
int CurChild;
CurNode = this;
CurChild = 0;
Debug.WriteLine(CurNode.Description());
for (; ;)
{
if (CurNode._children != null && CurChild < CurNode._children.Count)
{
Stack.Add(CurChild + 1);
CurNode = CurNode._children[CurChild];
CurChild = 0;
int Depth = Stack.Count;
if (Depth > 32)
Depth = 32;
Debug.WriteLine(Space.Substring(0, Depth) + CurNode.Description());
}
else
{
if (Stack.Count == 0)
break;
CurChild = Stack[Stack.Count - 1];
Stack.RemoveAt(Stack.Count - 1);
CurNode = CurNode._next;
}
}
}
#endif
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLMcode = Interop.Http.CURLMcode;
using CURLoption = Interop.Http.CURLoption;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
#region Constants
private const string VerboseDebuggingConditional = "CURLHANDLER_VERBOSE";
private const char SpaceChar = ' ';
private const int StatusCodeLength = 3;
private const string UriSchemeHttp = "http";
private const string UriSchemeHttps = "https";
private const string EncodingNameGzip = "gzip";
private const string EncodingNameDeflate = "deflate";
private const int RequestBufferSize = 16384; // Default used by libcurl
private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":";
private const string NoContentType = HttpKnownHeaderNames.ContentType + ":";
private const int CurlAge = 5;
private const int MinCurlAge = 3;
#endregion
#region Fields
private readonly static char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF };
private readonly static string[] s_authenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes
private readonly static CURLAUTH[] s_authSchemePriorityOrder = { CURLAUTH.Negotiate, CURLAUTH.Digest, CURLAUTH.Basic };
private readonly static bool s_supportsAutomaticDecompression;
private readonly static bool s_supportsSSL;
private readonly MultiAgent _agent = new MultiAgent();
private volatile bool _anyOperationStarted;
private volatile bool _disposed;
private IWebProxy _proxy = null;
private ICredentials _serverCredentials = null;
private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate;
private CredentialCache _credentialCache = null; // protected by LockObject
private CookieContainer _cookieContainer = new CookieContainer();
private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption;
private object LockObject { get { return _agent; } }
#endregion
static CurlHandler()
{
// curl_global_init call handled by Interop.LibCurl's cctor
int age;
if (!Interop.Http.GetCurlVersionInfo(out age, out s_supportsSSL, out s_supportsAutomaticDecompression))
{
throw new InvalidOperationException(SR.net_http_unix_https_libcurl_no_versioninfo);
}
// Verify the version of curl we're using is new enough
if (age < MinCurlAge)
{
throw new InvalidOperationException(SR.net_http_unix_https_libcurl_too_old);
}
}
#region Properties
internal bool AutomaticRedirection
{
get
{
return _automaticRedirection;
}
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
internal bool SupportsProxy
{
get
{
return true;
}
}
internal bool SupportsRedirectConfiguration
{
get
{
return true;
}
}
internal bool UseProxy
{
get
{
return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy;
}
set
{
CheckDisposedOrStarted();
_proxyPolicy = value ?
ProxyUsePolicy.UseCustomProxy :
ProxyUsePolicy.DoNotUseProxy;
}
}
internal IWebProxy Proxy
{
get
{
return _proxy;
}
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
internal ICredentials Credentials
{
get
{
return _serverCredentials;
}
set
{
_serverCredentials = value;
}
}
internal ClientCertificateOption ClientCertificateOptions
{
get
{
return _clientCertificateOption;
}
set
{
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
internal bool SupportsAutomaticDecompression
{
get
{
return s_supportsAutomaticDecompression;
}
}
internal DecompressionMethods AutomaticDecompression
{
get
{
return _automaticDecompression;
}
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
internal bool PreAuthenticate
{
get
{
return _preAuthenticate;
}
set
{
CheckDisposedOrStarted();
_preAuthenticate = value;
if (value && _credentialCache == null)
{
_credentialCache = new CredentialCache();
}
}
}
internal bool UseCookie
{
get
{
return _useCookie;
}
set
{
CheckDisposedOrStarted();
_useCookie = value;
}
}
internal CookieContainer CookieContainer
{
get
{
return _cookieContainer;
}
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
internal int MaxAutomaticRedirections
{
get
{
return _maxAutomaticRedirections;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(
"value",
value,
SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
/// <summary>
/// <b> UseDefaultCredentials is a no op on Unix </b>
/// </summary>
internal bool UseDefaultCredentials
{
get
{
return false;
}
set
{
}
}
#endregion
protected override void Dispose(bool disposing)
{
_disposed = true;
base.Dispose(disposing);
}
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request", SR.net_http_handler_norequest);
}
if (request.RequestUri.Scheme == UriSchemeHttps)
{
if (!s_supportsSSL)
{
throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl);
}
}
else
{
Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https.");
}
if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null))
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
if (_useCookie && _cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
SetOperationStarted();
// Do an initial cancellation check to avoid initiating the async operation if
// cancellation has already been requested. After this, we'll rely on CancellationToken.Register
// to notify us of cancellation requests and shut down the operation if possible.
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<HttpResponseMessage>(cancellationToken);
}
// Create the easy request. This associates the easy request with this handler and configures
// it based on the settings configured for the handler.
var easy = new EasyRequest(this, request, cancellationToken);
try
{
easy.InitializeCurl();
if (easy._requestContentStream != null)
{
easy._requestContentStream.Run();
}
_agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New });
}
catch (Exception exc)
{
easy.FailRequest(exc);
easy.Cleanup(); // no active processing remains, so we can cleanup
}
return easy.Task;
}
#region Private methods
private void SetOperationStarted()
{
if (!_anyOperationStarted)
{
_anyOperationStarted = true;
}
}
private KeyValuePair<NetworkCredential, CURLAUTH> GetNetworkCredentials(ICredentials credentials, Uri requestUri)
{
if (_preAuthenticate)
{
KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme;
lock (LockObject)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
ncAndScheme = GetCredentials(_credentialCache, requestUri);
}
if (ncAndScheme.Key != null)
{
return ncAndScheme;
}
}
return GetCredentials(credentials, requestUri);
}
private void AddCredentialToCache(Uri serverUri, CURLAUTH authAvail, NetworkCredential nc)
{
lock (LockObject)
{
for (int i=0; i < s_authSchemePriorityOrder.Length; i++)
{
if ((authAvail & s_authSchemePriorityOrder[i]) != 0)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
try
{
_credentialCache.Add(serverUri, s_authenticationSchemes[i], nc);
}
catch(ArgumentException)
{
//Ignore the case of key already present
}
}
}
}
}
private void AddResponseCookies(Uri serverUri, HttpResponseMessage response)
{
if (!_useCookie)
{
return;
}
if (response.Headers.Contains(HttpKnownHeaderNames.SetCookie))
{
IEnumerable<string> cookieHeaders = response.Headers.GetValues(HttpKnownHeaderNames.SetCookie);
foreach (var cookieHeader in cookieHeaders)
{
try
{
_cookieContainer.SetCookies(serverUri, cookieHeader);
}
catch (CookieException e)
{
string msg = string.Format("Malformed cookie: SetCookies Failed with {0}, server: {1}, cookie:{2}",
e.Message,
serverUri.OriginalString,
cookieHeader);
VerboseTrace(msg);
}
}
}
}
private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(ICredentials credentials, Uri requestUri)
{
NetworkCredential nc = null;
CURLAUTH curlAuthScheme = CURLAUTH.None;
if (credentials != null)
{
// we collect all the schemes that are accepted by libcurl for which there is a non-null network credential.
// But CurlHandler works under following assumption:
// for a given server, the credentials do not vary across authentication schemes.
for (int i=0; i < s_authSchemePriorityOrder.Length; i++)
{
NetworkCredential networkCredential = credentials.GetCredential(requestUri, s_authenticationSchemes[i]);
if (networkCredential != null)
{
curlAuthScheme |= s_authSchemePriorityOrder[i];
if (nc == null)
{
nc = networkCredential;
}
else if(!AreEqualNetworkCredentials(nc, networkCredential))
{
throw new PlatformNotSupportedException(SR.net_http_unix_invalid_credential);
}
}
}
}
VerboseTrace("curlAuthScheme = " + curlAuthScheme);
return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ;
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_anyOperationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private static void ThrowIfCURLEError(CURLcode error)
{
if (error != CURLcode.CURLE_OK)
{
var inner = new CurlException((int)error, isMulti: false);
VerboseTrace(inner.Message);
throw inner;
}
}
private static void ThrowIfCURLMError(CURLMcode error)
{
if (error != CURLMcode.CURLM_OK)
{
string msg = CurlException.GetCurlErrorString((int)error, true);
VerboseTrace(msg);
switch (error)
{
case CURLMcode.CURLM_ADDED_ALREADY:
case CURLMcode.CURLM_BAD_EASY_HANDLE:
case CURLMcode.CURLM_BAD_HANDLE:
case CURLMcode.CURLM_BAD_SOCKET:
throw new ArgumentException(msg);
case CURLMcode.CURLM_UNKNOWN_OPTION:
throw new ArgumentOutOfRangeException(msg);
case CURLMcode.CURLM_OUT_OF_MEMORY:
throw new OutOfMemoryException(msg);
case CURLMcode.CURLM_INTERNAL_ERROR:
default:
throw new CurlException((int)error, msg);
}
}
}
private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2)
{
Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check");
return credential1.UserName == credential2.UserName &&
credential1.Domain == credential2.Domain &&
string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal);
}
[Conditional(VerboseDebuggingConditional)]
private static void VerboseTrace(string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null, MultiAgent agent = null)
{
// If we weren't handed a multi agent, see if we can get one from the EasyRequest
if (agent == null && easy != null && easy._associatedMultiAgent != null)
{
agent = easy._associatedMultiAgent;
}
int? agentId = agent != null ? agent.RunningWorkerId : null;
// Get an ID string that provides info about which MultiAgent worker and which EasyRequest this trace is about
string ids = "";
if (agentId != null || easy != null)
{
ids = "(" +
(agentId != null ? "M#" + agentId : "") +
(agentId != null && easy != null ? ", " : "") +
(easy != null ? "E#" + easy.Task.Id : "") +
")";
}
// Create the message and trace it out
string msg = string.Format("[{0, -30}]{1, -16}: {2}", memberName, ids, text);
Interop.Sys.PrintF("%s\n", msg);
}
[Conditional(VerboseDebuggingConditional)]
private static void VerboseTraceIf(bool condition, string text = null, [CallerMemberName] string memberName = null, EasyRequest easy = null)
{
if (condition)
{
VerboseTrace(text, memberName, easy, agent: null);
}
}
private static Exception CreateHttpRequestException(Exception inner = null)
{
return new HttpRequestException(SR.net_http_client_execution_error, inner);
}
private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state)
{
if (!responseHeader.StartsWith(CurlResponseParseUtils.HttpPrefix, StringComparison.OrdinalIgnoreCase))
{
return false;
}
// Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection).
response.Headers.Clear();
response.Content.Headers.Clear();
CurlResponseParseUtils.ReadStatusLine(response, responseHeader);
state._isRedirect = state._handler.AutomaticRedirection &&
(response.StatusCode == HttpStatusCode.Redirect ||
response.StatusCode == HttpStatusCode.RedirectKeepVerb ||
response.StatusCode == HttpStatusCode.RedirectMethod) ;
return true;
}
private static void HandleRedirectLocationHeader(EasyRequest state, string locationValue)
{
Debug.Assert(state._isRedirect);
Debug.Assert(state._handler.AutomaticRedirection);
string location = locationValue.Trim();
//only for absolute redirects
Uri forwardUri;
if (Uri.TryCreate(location, UriKind.RelativeOrAbsolute, out forwardUri) && forwardUri.IsAbsoluteUri)
{
KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme = GetCredentials(state._handler.Credentials as CredentialCache, forwardUri);
if (ncAndScheme.Key != null)
{
state.SetCredentialsOptions(ncAndScheme);
}
else
{
state.SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero);
state.SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero);
}
// reset proxy - it is possible that the proxy has different credentials for the new URI
state.SetProxyOptions(forwardUri);
if (state._handler._useCookie)
{
// reset cookies.
state.SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero);
// set cookies again
state.SetCookieOption(forwardUri);
}
}
// set the headers again. This is a workaround for libcurl's limitation in handling headers with empty values
state.SetRequestHeaders();
}
private static void SetChunkedModeForSend(HttpRequestMessage request)
{
bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault();
HttpContent requestContent = request.Content;
Debug.Assert(requestContent != null, "request is null");
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// libcurl adds a Tranfer-Encoding header by default and the request fails if both are set.
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Same behaviour as WinHttpHandler
requestContent.Headers.ContentLength = null;
}
else
{
// Prevent libcurl from adding Transfer-Encoding header
request.Headers.TransferEncodingChunked = false;
}
}
else if (!chunkedMode)
{
// Make sure Transfer-Encoding: chunked header is set,
// as we have content to send but no known length for it.
request.Headers.TransferEncodingChunked = true;
}
}
#endregion
private enum ProxyUsePolicy
{
DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment.
UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any.
UseCustomProxy = 2 // Use The proxy specified by the user.
}
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using JCG = J2N.Collections.Generic;
using ArrayUtil = Lucene.Net.Util.ArrayUtil;
namespace Lucene.Net.Codecs.Compressing
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReader = Lucene.Net.Index.AtomicReader;
using IBits = Lucene.Net.Util.IBits;
using BlockPackedWriter = Lucene.Net.Util.Packed.BlockPackedWriter;
using BufferedChecksumIndexInput = Lucene.Net.Store.BufferedChecksumIndexInput;
using BytesRef = Lucene.Net.Util.BytesRef;
using ChecksumIndexInput = Lucene.Net.Store.ChecksumIndexInput;
using DataInput = Lucene.Net.Store.DataInput;
using Directory = Lucene.Net.Store.Directory;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using Fields = Lucene.Net.Index.Fields;
using GrowableByteArrayDataOutput = Lucene.Net.Util.GrowableByteArrayDataOutput;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using MergeState = Lucene.Net.Index.MergeState;
using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s;
using SegmentInfo = Lucene.Net.Index.SegmentInfo;
using SegmentReader = Lucene.Net.Index.SegmentReader;
using StringHelper = Lucene.Net.Util.StringHelper;
/// <summary>
/// <see cref="TermVectorsWriter"/> for <see cref="CompressingTermVectorsFormat"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class CompressingTermVectorsWriter : TermVectorsWriter
{
// hard limit on the maximum number of documents per chunk
internal const int MAX_DOCUMENTS_PER_CHUNK = 128;
internal const string VECTORS_EXTENSION = "tvd";
internal const string VECTORS_INDEX_EXTENSION = "tvx";
internal const string CODEC_SFX_IDX = "Index";
internal const string CODEC_SFX_DAT = "Data";
internal const int VERSION_START = 0;
internal const int VERSION_CHECKSUM = 1;
internal const int VERSION_CURRENT = VERSION_CHECKSUM;
internal const int BLOCK_SIZE = 64;
internal const int POSITIONS = 0x01;
internal const int OFFSETS = 0x02;
internal const int PAYLOADS = 0x04;
internal static readonly int FLAGS_BITS = PackedInt32s.BitsRequired(POSITIONS | OFFSETS | PAYLOADS);
private readonly Directory directory;
private readonly string segment;
private readonly string segmentSuffix;
private CompressingStoredFieldsIndexWriter indexWriter;
private IndexOutput vectorsStream;
private readonly CompressionMode compressionMode;
private readonly Compressor compressor;
private readonly int chunkSize;
/// <summary>
/// A pending doc. </summary>
private class DocData
{
private readonly CompressingTermVectorsWriter outerInstance;
internal readonly int numFields;
internal readonly LinkedList<FieldData> fields;
internal readonly int posStart, offStart, payStart;
internal DocData(CompressingTermVectorsWriter outerInstance, int numFields, int posStart, int offStart, int payStart)
{
this.outerInstance = outerInstance;
this.numFields = numFields;
this.fields = new LinkedList<FieldData>();
this.posStart = posStart;
this.offStart = offStart;
this.payStart = payStart;
}
internal virtual FieldData AddField(int fieldNum, int numTerms, bool positions, bool offsets, bool payloads)
{
FieldData field;
if (fields.Count == 0)
{
field = new FieldData(outerInstance, fieldNum, numTerms, positions, offsets, payloads, posStart, offStart, payStart);
}
else
{
FieldData last = fields.Last.Value;
int posStart = last.posStart + (last.hasPositions ? last.totalPositions : 0);
int offStart = last.offStart + (last.hasOffsets ? last.totalPositions : 0);
int payStart = last.payStart + (last.hasPayloads ? last.totalPositions : 0);
field = new FieldData(outerInstance, fieldNum, numTerms, positions, offsets, payloads, posStart, offStart, payStart);
}
fields.AddLast(field);
return field;
}
}
private DocData AddDocData(int numVectorFields)
{
FieldData last = null;
// LUCENENET specific - quicker just to use the linked list properties
// to walk backward, since we are only looking for the last element with
// fields.
var doc = pendingDocs.Last;
while (doc != null)
{
if (!(doc.Value.fields.Count == 0))
{
last = doc.Value.fields.Last.Value;
break;
}
doc = doc.Previous;
}
DocData newDoc;
if (last == null)
{
newDoc = new DocData(this, numVectorFields, 0, 0, 0);
}
else
{
int posStart = last.posStart + (last.hasPositions ? last.totalPositions : 0);
int offStart = last.offStart + (last.hasOffsets ? last.totalPositions : 0);
int payStart = last.payStart + (last.hasPayloads ? last.totalPositions : 0);
newDoc = new DocData(this, numVectorFields, posStart, offStart, payStart);
}
pendingDocs.AddLast(newDoc);
return newDoc;
}
/// <summary>
/// A pending field. </summary>
private class FieldData
{
private readonly CompressingTermVectorsWriter outerInstance;
internal readonly bool hasPositions, hasOffsets, hasPayloads;
internal readonly int fieldNum, flags, numTerms;
internal readonly int[] freqs, prefixLengths, suffixLengths;
internal readonly int posStart, offStart, payStart;
internal int totalPositions;
internal int ord;
internal FieldData(CompressingTermVectorsWriter outerInstance, int fieldNum, int numTerms, bool positions, bool offsets, bool payloads, int posStart, int offStart, int payStart)
{
this.outerInstance = outerInstance;
this.fieldNum = fieldNum;
this.numTerms = numTerms;
this.hasPositions = positions;
this.hasOffsets = offsets;
this.hasPayloads = payloads;
this.flags = (positions ? POSITIONS : 0) | (offsets ? OFFSETS : 0) | (payloads ? PAYLOADS : 0);
this.freqs = new int[numTerms];
this.prefixLengths = new int[numTerms];
this.suffixLengths = new int[numTerms];
this.posStart = posStart;
this.offStart = offStart;
this.payStart = payStart;
totalPositions = 0;
ord = 0;
}
internal virtual void AddTerm(int freq, int prefixLength, int suffixLength)
{
freqs[ord] = freq;
prefixLengths[ord] = prefixLength;
suffixLengths[ord] = suffixLength;
++ord;
}
internal virtual void AddPosition(int position, int startOffset, int length, int payloadLength)
{
if (hasPositions)
{
if (posStart + totalPositions == outerInstance.positionsBuf.Length)
{
outerInstance.positionsBuf = ArrayUtil.Grow(outerInstance.positionsBuf);
}
outerInstance.positionsBuf[posStart + totalPositions] = position;
}
if (hasOffsets)
{
if (offStart + totalPositions == outerInstance.startOffsetsBuf.Length)
{
int newLength = ArrayUtil.Oversize(offStart + totalPositions, 4);
outerInstance.startOffsetsBuf = Arrays.CopyOf(outerInstance.startOffsetsBuf, newLength);
outerInstance.lengthsBuf = Arrays.CopyOf(outerInstance.lengthsBuf, newLength);
}
outerInstance.startOffsetsBuf[offStart + totalPositions] = startOffset;
outerInstance.lengthsBuf[offStart + totalPositions] = length;
}
if (hasPayloads)
{
if (payStart + totalPositions == outerInstance.payloadLengthsBuf.Length)
{
outerInstance.payloadLengthsBuf = ArrayUtil.Grow(outerInstance.payloadLengthsBuf);
}
outerInstance.payloadLengthsBuf[payStart + totalPositions] = payloadLength;
}
++totalPositions;
}
}
private int numDocs; // total number of docs seen
private readonly LinkedList<DocData> pendingDocs; // pending docs
private DocData curDoc; // current document
private FieldData curField; // current field
private readonly BytesRef lastTerm;
private int[] positionsBuf, startOffsetsBuf, lengthsBuf, payloadLengthsBuf;
private readonly GrowableByteArrayDataOutput termSuffixes; // buffered term suffixes
private readonly GrowableByteArrayDataOutput payloadBytes; // buffered term payloads
private readonly BlockPackedWriter writer;
/// <summary>
/// Sole constructor. </summary>
public CompressingTermVectorsWriter(Directory directory, SegmentInfo si, string segmentSuffix, IOContext context, string formatName, CompressionMode compressionMode, int chunkSize)
{
Debug.Assert(directory != null);
this.directory = directory;
this.segment = si.Name;
this.segmentSuffix = segmentSuffix;
this.compressionMode = compressionMode;
this.compressor = compressionMode.NewCompressor();
this.chunkSize = chunkSize;
numDocs = 0;
pendingDocs = new LinkedList<DocData>();
termSuffixes = new GrowableByteArrayDataOutput(ArrayUtil.Oversize(chunkSize, 1));
payloadBytes = new GrowableByteArrayDataOutput(ArrayUtil.Oversize(1, 1));
lastTerm = new BytesRef(ArrayUtil.Oversize(30, 1));
bool success = false;
IndexOutput indexStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, segmentSuffix, VECTORS_INDEX_EXTENSION), context);
try
{
vectorsStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, segmentSuffix, VECTORS_EXTENSION), context);
string codecNameIdx = formatName + CODEC_SFX_IDX;
string codecNameDat = formatName + CODEC_SFX_DAT;
CodecUtil.WriteHeader(indexStream, codecNameIdx, VERSION_CURRENT);
CodecUtil.WriteHeader(vectorsStream, codecNameDat, VERSION_CURRENT);
Debug.Assert(CodecUtil.HeaderLength(codecNameDat) == vectorsStream.GetFilePointer());
Debug.Assert(CodecUtil.HeaderLength(codecNameIdx) == indexStream.GetFilePointer());
indexWriter = new CompressingStoredFieldsIndexWriter(indexStream);
indexStream = null;
vectorsStream.WriteVInt32(PackedInt32s.VERSION_CURRENT);
vectorsStream.WriteVInt32(chunkSize);
writer = new BlockPackedWriter(vectorsStream, BLOCK_SIZE);
positionsBuf = new int[1024];
startOffsetsBuf = new int[1024];
lengthsBuf = new int[1024];
payloadLengthsBuf = new int[1024];
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(indexStream);
Abort();
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
IOUtils.Dispose(vectorsStream, indexWriter);
}
finally
{
vectorsStream = null;
indexWriter = null;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Abort()
{
IOUtils.DisposeWhileHandlingException(this);
IOUtils.DeleteFilesIgnoringExceptions(directory, IndexFileNames.SegmentFileName(segment, segmentSuffix, VECTORS_EXTENSION), IndexFileNames.SegmentFileName(segment, segmentSuffix, VECTORS_INDEX_EXTENSION));
}
public override void StartDocument(int numVectorFields)
{
curDoc = AddDocData(numVectorFields);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void FinishDocument()
{
// append the payload bytes of the doc after its terms
termSuffixes.WriteBytes(payloadBytes.Bytes, payloadBytes.Length);
payloadBytes.Length = 0;
++numDocs;
if (TriggerFlush())
{
Flush();
}
curDoc = null;
}
public override void StartField(FieldInfo info, int numTerms, bool positions, bool offsets, bool payloads)
{
curField = curDoc.AddField(info.Number, numTerms, positions, offsets, payloads);
lastTerm.Length = 0;
}
public override void FinishField()
{
curField = null;
}
public override void StartTerm(BytesRef term, int freq)
{
Debug.Assert(freq >= 1);
int prefix = StringHelper.BytesDifference(lastTerm, term);
curField.AddTerm(freq, prefix, term.Length - prefix);
termSuffixes.WriteBytes(term.Bytes, term.Offset + prefix, term.Length - prefix);
// copy last term
if (lastTerm.Bytes.Length < term.Length)
{
lastTerm.Bytes = new byte[ArrayUtil.Oversize(term.Length, 1)];
}
lastTerm.Offset = 0;
lastTerm.Length = term.Length;
Array.Copy(term.Bytes, term.Offset, lastTerm.Bytes, 0, term.Length);
}
public override void AddPosition(int position, int startOffset, int endOffset, BytesRef payload)
{
Debug.Assert(curField.flags != 0);
curField.AddPosition(position, startOffset, endOffset - startOffset, payload == null ? 0 : payload.Length);
if (curField.hasPayloads && payload != null)
{
payloadBytes.WriteBytes(payload.Bytes, payload.Offset, payload.Length);
}
}
private bool TriggerFlush()
{
return termSuffixes.Length >= chunkSize || pendingDocs.Count >= MAX_DOCUMENTS_PER_CHUNK;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void Flush()
{
int chunkDocs = pendingDocs.Count;
Debug.Assert(chunkDocs > 0, chunkDocs.ToString());
// write the index file
indexWriter.WriteIndex(chunkDocs, vectorsStream.GetFilePointer());
int docBase = numDocs - chunkDocs;
vectorsStream.WriteVInt32(docBase);
vectorsStream.WriteVInt32(chunkDocs);
// total number of fields of the chunk
int totalFields = FlushNumFields(chunkDocs);
if (totalFields > 0)
{
// unique field numbers (sorted)
int[] fieldNums = FlushFieldNums();
// offsets in the array of unique field numbers
FlushFields(totalFields, fieldNums);
// flags (does the field have positions, offsets, payloads?)
FlushFlags(totalFields, fieldNums);
// number of terms of each field
FlushNumTerms(totalFields);
// prefix and suffix lengths for each field
FlushTermLengths();
// term freqs - 1 (because termFreq is always >=1) for each term
FlushTermFreqs();
// positions for all terms, when enabled
FlushPositions();
// offsets for all terms, when enabled
FlushOffsets(fieldNums);
// payload lengths for all terms, when enabled
FlushPayloadLengths();
// compress terms and payloads and write them to the output
compressor.Compress(termSuffixes.Bytes, 0, termSuffixes.Length, vectorsStream);
}
// reset
pendingDocs.Clear();
curDoc = null;
curField = null;
termSuffixes.Length = 0;
}
private int FlushNumFields(int chunkDocs)
{
if (chunkDocs == 1)
{
int numFields = pendingDocs.First.Value.numFields;
vectorsStream.WriteVInt32(numFields);
return numFields;
}
else
{
writer.Reset(vectorsStream);
int totalFields = 0;
foreach (DocData dd in pendingDocs)
{
writer.Add(dd.numFields);
totalFields += dd.numFields;
}
writer.Finish();
return totalFields;
}
}
/// <summary>
/// Returns a sorted array containing unique field numbers. </summary>
private int[] FlushFieldNums()
{
JCG.SortedSet<int> fieldNums = new JCG.SortedSet<int>();
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
fieldNums.Add(fd.fieldNum);
}
}
int numDistinctFields = fieldNums.Count;
Debug.Assert(numDistinctFields > 0);
int bitsRequired = PackedInt32s.BitsRequired(fieldNums.Max);
int token = (Math.Min(numDistinctFields - 1, 0x07) << 5) | bitsRequired;
vectorsStream.WriteByte((byte)(sbyte)token);
if (numDistinctFields - 1 >= 0x07)
{
vectorsStream.WriteVInt32(numDistinctFields - 1 - 0x07);
}
PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(vectorsStream, PackedInt32s.Format.PACKED, fieldNums.Count, bitsRequired, 1);
foreach (int fieldNum in fieldNums)
{
writer.Add(fieldNum);
}
writer.Finish();
int[] fns = new int[fieldNums.Count];
int i = 0;
foreach (int key in fieldNums)
{
fns[i++] = key;
}
return fns;
}
private void FlushFields(int totalFields, int[] fieldNums)
{
PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(vectorsStream, PackedInt32s.Format.PACKED, totalFields, PackedInt32s.BitsRequired(fieldNums.Length - 1), 1);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
int fieldNumIndex = Array.BinarySearch(fieldNums, fd.fieldNum);
Debug.Assert(fieldNumIndex >= 0);
writer.Add(fieldNumIndex);
}
}
writer.Finish();
}
private void FlushFlags(int totalFields, int[] fieldNums)
{
// check if fields always have the same flags
bool nonChangingFlags = true;
int[] fieldFlags = new int[fieldNums.Length];
Arrays.Fill(fieldFlags, -1);
bool breakOuterLoop;
foreach (DocData dd in pendingDocs)
{
breakOuterLoop = false;
foreach (FieldData fd in dd.fields)
{
int fieldNumOff = Array.BinarySearch(fieldNums, fd.fieldNum);
Debug.Assert(fieldNumOff >= 0);
if (fieldFlags[fieldNumOff] == -1)
{
fieldFlags[fieldNumOff] = fd.flags;
}
else if (fieldFlags[fieldNumOff] != fd.flags)
{
nonChangingFlags = false;
breakOuterLoop = true;
}
}
if (breakOuterLoop)
break;
}
if (nonChangingFlags)
{
// write one flag per field num
vectorsStream.WriteVInt32(0);
PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(vectorsStream, PackedInt32s.Format.PACKED, fieldFlags.Length, FLAGS_BITS, 1);
foreach (int flags in fieldFlags)
{
Debug.Assert(flags >= 0);
writer.Add(flags);
}
Debug.Assert(writer.Ord == fieldFlags.Length - 1);
writer.Finish();
}
else
{
// write one flag for every field instance
vectorsStream.WriteVInt32(1);
PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(vectorsStream, PackedInt32s.Format.PACKED, totalFields, FLAGS_BITS, 1);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
writer.Add(fd.flags);
}
}
Debug.Assert(writer.Ord == totalFields - 1);
writer.Finish();
}
}
private void FlushNumTerms(int totalFields)
{
int maxNumTerms = 0;
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
maxNumTerms |= fd.numTerms;
}
}
int bitsRequired = PackedInt32s.BitsRequired(maxNumTerms);
vectorsStream.WriteVInt32(bitsRequired);
PackedInt32s.Writer writer = PackedInt32s.GetWriterNoHeader(vectorsStream, PackedInt32s.Format.PACKED, totalFields, bitsRequired, 1);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
writer.Add(fd.numTerms);
}
}
Debug.Assert(writer.Ord == totalFields - 1);
writer.Finish();
}
private void FlushTermLengths()
{
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
for (int i = 0; i < fd.numTerms; ++i)
{
writer.Add(fd.prefixLengths[i]);
}
}
}
writer.Finish();
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
for (int i = 0; i < fd.numTerms; ++i)
{
writer.Add(fd.suffixLengths[i]);
}
}
}
writer.Finish();
}
private void FlushTermFreqs()
{
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
for (int i = 0; i < fd.numTerms; ++i)
{
writer.Add(fd.freqs[i] - 1);
}
}
}
writer.Finish();
}
private void FlushPositions()
{
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
if (fd.hasPositions)
{
int pos = 0;
for (int i = 0; i < fd.numTerms; ++i)
{
int previousPosition = 0;
for (int j = 0; j < fd.freqs[i]; ++j)
{
int position = positionsBuf[fd.posStart + pos++];
writer.Add(position - previousPosition);
previousPosition = position;
}
}
Debug.Assert(pos == fd.totalPositions);
}
}
}
writer.Finish();
}
private void FlushOffsets(int[] fieldNums)
{
bool hasOffsets = false;
long[] sumPos = new long[fieldNums.Length];
long[] sumOffsets = new long[fieldNums.Length];
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
hasOffsets |= fd.hasOffsets;
if (fd.hasOffsets && fd.hasPositions)
{
int fieldNumOff = Array.BinarySearch(fieldNums, fd.fieldNum);
int pos = 0;
for (int i = 0; i < fd.numTerms; ++i)
{
int previousPos = 0;
int previousOff = 0;
for (int j = 0; j < fd.freqs[i]; ++j)
{
int position = positionsBuf[fd.posStart + pos];
int startOffset = startOffsetsBuf[fd.offStart + pos];
sumPos[fieldNumOff] += position - previousPos;
sumOffsets[fieldNumOff] += startOffset - previousOff;
previousPos = position;
previousOff = startOffset;
++pos;
}
}
Debug.Assert(pos == fd.totalPositions);
}
}
}
if (!hasOffsets)
{
// nothing to do
return;
}
float[] charsPerTerm = new float[fieldNums.Length];
for (int i = 0; i < fieldNums.Length; ++i)
{
charsPerTerm[i] = (sumPos[i] <= 0 || sumOffsets[i] <= 0) ? 0 : (float)((double)sumOffsets[i] / sumPos[i]);
}
// start offsets
for (int i = 0; i < fieldNums.Length; ++i)
{
vectorsStream.WriteInt32(J2N.BitConversion.SingleToInt32Bits(charsPerTerm[i]));
}
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
if ((fd.flags & OFFSETS) != 0)
{
int fieldNumOff = Array.BinarySearch(fieldNums, fd.fieldNum);
float cpt = charsPerTerm[fieldNumOff];
int pos = 0;
for (int i = 0; i < fd.numTerms; ++i)
{
int previousPos = 0;
int previousOff = 0;
for (int j = 0; j < fd.freqs[i]; ++j)
{
int position = fd.hasPositions ? positionsBuf[fd.posStart + pos] : 0;
int startOffset = startOffsetsBuf[fd.offStart + pos];
writer.Add(startOffset - previousOff - (int)(cpt * (position - previousPos)));
previousPos = position;
previousOff = startOffset;
++pos;
}
}
}
}
}
writer.Finish();
// lengths
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
if ((fd.flags & OFFSETS) != 0)
{
int pos = 0;
for (int i = 0; i < fd.numTerms; ++i)
{
for (int j = 0; j < fd.freqs[i]; ++j)
{
writer.Add(lengthsBuf[fd.offStart + pos++] - fd.prefixLengths[i] - fd.suffixLengths[i]);
}
}
Debug.Assert(pos == fd.totalPositions);
}
}
}
writer.Finish();
}
private void FlushPayloadLengths()
{
writer.Reset(vectorsStream);
foreach (DocData dd in pendingDocs)
{
foreach (FieldData fd in dd.fields)
{
if (fd.hasPayloads)
{
for (int i = 0; i < fd.totalPositions; ++i)
{
writer.Add(payloadLengthsBuf[fd.payStart + i]);
}
}
}
}
writer.Finish();
}
public override void Finish(FieldInfos fis, int numDocs)
{
if (!(pendingDocs.Count == 0))
{
Flush();
}
if (numDocs != this.numDocs)
{
throw new Exception("Wrote " + this.numDocs + " docs, finish called with numDocs=" + numDocs);
}
indexWriter.Finish(numDocs, vectorsStream.GetFilePointer());
CodecUtil.WriteFooter(vectorsStream);
}
public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer;
public override void AddProx(int numProx, DataInput positions, DataInput offsets)
{
Debug.Assert((curField.hasPositions) == (positions != null));
Debug.Assert((curField.hasOffsets) == (offsets != null));
if (curField.hasPositions)
{
int posStart = curField.posStart + curField.totalPositions;
if (posStart + numProx > positionsBuf.Length)
{
positionsBuf = ArrayUtil.Grow(positionsBuf, posStart + numProx);
}
int position = 0;
if (curField.hasPayloads)
{
int payStart = curField.payStart + curField.totalPositions;
if (payStart + numProx > payloadLengthsBuf.Length)
{
payloadLengthsBuf = ArrayUtil.Grow(payloadLengthsBuf, payStart + numProx);
}
for (int i = 0; i < numProx; ++i)
{
int code = positions.ReadVInt32();
if ((code & 1) != 0)
{
// this position has a payload
int payloadLength = positions.ReadVInt32();
payloadLengthsBuf[payStart + i] = payloadLength;
payloadBytes.CopyBytes(positions, payloadLength);
}
else
{
payloadLengthsBuf[payStart + i] = 0;
}
position += (int)((uint)code >> 1);
positionsBuf[posStart + i] = position;
}
}
else
{
for (int i = 0; i < numProx; ++i)
{
position += ((int)((uint)positions.ReadVInt32() >> 1));
positionsBuf[posStart + i] = position;
}
}
}
if (curField.hasOffsets)
{
int offStart = curField.offStart + curField.totalPositions;
if (offStart + numProx > startOffsetsBuf.Length)
{
int newLength = ArrayUtil.Oversize(offStart + numProx, 4);
startOffsetsBuf = Arrays.CopyOf(startOffsetsBuf, newLength);
lengthsBuf = Arrays.CopyOf(lengthsBuf, newLength);
}
int lastOffset = 0, startOffset, endOffset;
for (int i = 0; i < numProx; ++i)
{
startOffset = lastOffset + offsets.ReadVInt32();
endOffset = startOffset + offsets.ReadVInt32();
lastOffset = endOffset;
startOffsetsBuf[offStart + i] = startOffset;
lengthsBuf[offStart + i] = endOffset - startOffset;
}
}
curField.totalPositions += numProx;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override int Merge(MergeState mergeState)
{
int docCount = 0;
int idx = 0;
foreach (AtomicReader reader in mergeState.Readers)
{
SegmentReader matchingSegmentReader = mergeState.MatchingSegmentReaders[idx++];
CompressingTermVectorsReader matchingVectorsReader = null;
if (matchingSegmentReader != null)
{
TermVectorsReader vectorsReader = matchingSegmentReader.TermVectorsReader;
// we can only bulk-copy if the matching reader is also a CompressingTermVectorsReader
if (vectorsReader != null && vectorsReader is CompressingTermVectorsReader)
{
matchingVectorsReader = (CompressingTermVectorsReader)vectorsReader;
}
}
int maxDoc = reader.MaxDoc;
IBits liveDocs = reader.LiveDocs;
if (matchingVectorsReader == null || matchingVectorsReader.Version != VERSION_CURRENT || matchingVectorsReader.CompressionMode != compressionMode || matchingVectorsReader.ChunkSize != chunkSize || matchingVectorsReader.PackedInt32sVersion != PackedInt32s.VERSION_CURRENT)
{
// naive merge...
for (int i = NextLiveDoc(0, liveDocs, maxDoc); i < maxDoc; i = NextLiveDoc(i + 1, liveDocs, maxDoc))
{
Fields vectors = reader.GetTermVectors(i);
AddAllDocVectors(vectors, mergeState);
++docCount;
mergeState.CheckAbort.Work(300);
}
}
else
{
CompressingStoredFieldsIndexReader index = matchingVectorsReader.Index;
IndexInput vectorsStreamOrig = matchingVectorsReader.VectorsStream;
vectorsStreamOrig.Seek(0);
ChecksumIndexInput vectorsStream = new BufferedChecksumIndexInput((IndexInput)vectorsStreamOrig.Clone());
for (int i = NextLiveDoc(0, liveDocs, maxDoc); i < maxDoc; )
{
// We make sure to move the checksum input in any case, otherwise the final
// integrity check might need to read the whole file a second time
long startPointer = index.GetStartPointer(i);
if (startPointer > vectorsStream.GetFilePointer())
{
vectorsStream.Seek(startPointer);
}
if ((pendingDocs.Count == 0) && (i == 0 || index.GetStartPointer(i - 1) < startPointer)) // start of a chunk
{
int docBase = vectorsStream.ReadVInt32();
int chunkDocs = vectorsStream.ReadVInt32();
Debug.Assert(docBase + chunkDocs <= matchingSegmentReader.MaxDoc);
if (docBase + chunkDocs < matchingSegmentReader.MaxDoc && NextDeletedDoc(docBase, liveDocs, docBase + chunkDocs) == docBase + chunkDocs)
{
long chunkEnd = index.GetStartPointer(docBase + chunkDocs);
long chunkLength = chunkEnd - vectorsStream.GetFilePointer();
indexWriter.WriteIndex(chunkDocs, this.vectorsStream.GetFilePointer());
this.vectorsStream.WriteVInt32(docCount);
this.vectorsStream.WriteVInt32(chunkDocs);
this.vectorsStream.CopyBytes(vectorsStream, chunkLength);
docCount += chunkDocs;
this.numDocs += chunkDocs;
mergeState.CheckAbort.Work(300 * chunkDocs);
i = NextLiveDoc(docBase + chunkDocs, liveDocs, maxDoc);
}
else
{
for (; i < docBase + chunkDocs; i = NextLiveDoc(i + 1, liveDocs, maxDoc))
{
Fields vectors = reader.GetTermVectors(i);
AddAllDocVectors(vectors, mergeState);
++docCount;
mergeState.CheckAbort.Work(300);
}
}
}
else
{
Fields vectors = reader.GetTermVectors(i);
AddAllDocVectors(vectors, mergeState);
++docCount;
mergeState.CheckAbort.Work(300);
i = NextLiveDoc(i + 1, liveDocs, maxDoc);
}
}
vectorsStream.Seek(vectorsStream.Length - CodecUtil.FooterLength());
CodecUtil.CheckFooter(vectorsStream);
}
}
Finish(mergeState.FieldInfos, docCount);
return docCount;
}
private static int NextLiveDoc(int doc, IBits liveDocs, int maxDoc)
{
if (liveDocs == null)
{
return doc;
}
while (doc < maxDoc && !liveDocs.Get(doc))
{
++doc;
}
return doc;
}
private static int NextDeletedDoc(int doc, IBits liveDocs, int maxDoc)
{
if (liveDocs == null)
{
return maxDoc;
}
while (doc < maxDoc && liveDocs.Get(doc))
{
++doc;
}
return doc;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Management.Automation;
namespace Microsoft.PowerShell.ScheduledJob
{
/// <summary>
/// Base class for NewScheduledJobOption, SetScheduledJobOption cmdlets.
/// </summary>
public abstract class ScheduledJobOptionCmdletBase : ScheduleJobCmdletBase
{
#region Parameters
/// <summary>
/// Options parameter set name.
/// </summary>
protected const string OptionsParameterSet = "Options";
/// <summary>
/// Scheduled job task is run with elevated privileges when this switch is selected.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public SwitchParameter RunElevated
{
get { return _runElevated; }
set { _runElevated = value; }
}
private SwitchParameter _runElevated = false;
/// <summary>
/// Scheduled job task is hidden in Windows Task Scheduler when true.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public SwitchParameter HideInTaskScheduler
{
get { return _hideInTaskScheduler; }
set { _hideInTaskScheduler = value; }
}
private SwitchParameter _hideInTaskScheduler = false;
/// <summary>
/// Scheduled job task will be restarted when machine becomes idle. This is applicable
/// only if the job was configured to stop when no longer idle.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public SwitchParameter RestartOnIdleResume
{
get { return _restartOnIdleResume; }
set { _restartOnIdleResume = value; }
}
private SwitchParameter _restartOnIdleResume = false;
/// <summary>
/// Provides task scheduler options for multiple running instances of the job.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public TaskMultipleInstancePolicy MultipleInstancePolicy
{
get { return _multipleInstancePolicy; }
set { _multipleInstancePolicy = value; }
}
private TaskMultipleInstancePolicy _multipleInstancePolicy = TaskMultipleInstancePolicy.IgnoreNew;
/// <summary>
/// Prevents the job task from being started manually via Task Scheduler UI.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public SwitchParameter DoNotAllowDemandStart
{
get { return _doNotAllowDemandStart; }
set { _doNotAllowDemandStart = value; }
}
private SwitchParameter _doNotAllowDemandStart = false;
/// <summary>
/// Allows the job task to be run only when network connection available.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public SwitchParameter RequireNetwork
{
get { return _requireNetwork; }
set { _requireNetwork = value; }
}
private SwitchParameter _requireNetwork = false;
/// <summary>
/// Stops running job started by Task Scheduler if computer is no longer idle.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public SwitchParameter StopIfGoingOffIdle
{
get { return _stopIfGoingOffIdle; }
set { _stopIfGoingOffIdle = value; }
}
private SwitchParameter _stopIfGoingOffIdle = false;
/// <summary>
/// Will wake the computer to run the job if computer is in sleep mode when
/// trigger activates.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public SwitchParameter WakeToRun
{
get { return _wakeToRun; }
set { _wakeToRun = value; }
}
private SwitchParameter _wakeToRun = false;
/// <summary>
/// Continue running task job if computer going on battery.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public SwitchParameter ContinueIfGoingOnBattery
{
get { return _continueIfGoingOnBattery; }
set { _continueIfGoingOnBattery = value; }
}
private SwitchParameter _continueIfGoingOnBattery = false;
/// <summary>
/// Will start job task even if computer is running on battery power.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public SwitchParameter StartIfOnBattery
{
get { return _startIfOnBattery; }
set { _startIfOnBattery = value; }
}
private SwitchParameter _startIfOnBattery = false;
/// <summary>
/// Specifies how long Task Scheduler will wait for idle time after a trigger has
/// activated before giving up trying to run job during computer idle.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public TimeSpan IdleTimeout
{
get { return _idleTimeout; }
set { _idleTimeout = value; }
}
private TimeSpan _idleTimeout = new TimeSpan(1, 0, 0);
/// <summary>
/// How long the computer needs to be idle before a triggered job task is started.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public TimeSpan IdleDuration
{
get { return _idleDuration; }
set { _idleDuration = value; }
}
private TimeSpan _idleDuration = new TimeSpan(0, 10, 0);
/// <summary>
/// Will start job task if machine is idle.
/// </summary>
[Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)]
public SwitchParameter StartIfIdle
{
get { return _startIfIdle; }
set { _startIfIdle = value; }
}
private SwitchParameter _startIfIdle = false;
#endregion
#region Cmdlet Overrides
/// <summary>
/// Begin processing.
/// </summary>
protected override void BeginProcessing()
{
// Validate parameters.
if (MyInvocation.BoundParameters.ContainsKey(nameof(IdleTimeout)) &&
_idleTimeout < TimeSpan.Zero)
{
throw new PSArgumentException(ScheduledJobErrorStrings.InvalidIdleTimeout);
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(IdleDuration)) &&
_idleDuration < TimeSpan.Zero)
{
throw new PSArgumentException(ScheduledJobErrorStrings.InvalidIdleDuration);
}
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using NLog.Filters;
using NLog.Targets;
/// <summary>
/// Represents a logging rule. An equivalent of <logger /> configuration element.
/// </summary>
[NLogConfigurationItem]
public class LoggingRule
{
private ILoggingRuleLevelFilter _logLevelFilter = LoggingRuleLevelFilter.Off;
private LoggerNameMatcher _loggerNameMatcher = LoggerNameMatcher.Create(null);
/// <summary>
/// Create an empty <see cref="LoggingRule" />.
/// </summary>
public LoggingRule()
:this(null)
{
}
/// <summary>
/// Create an empty <see cref="LoggingRule" />.
/// </summary>
public LoggingRule(string ruleName)
{
RuleName = ruleName;
Filters = new List<Filter>();
ChildRules = new List<LoggingRule>();
Targets = new List<Target>();
}
/// <summary>
/// Create a new <see cref="LoggingRule" /> with a <paramref name="minLevel"/> and <paramref name="maxLevel"/> which writes to <paramref name="target"/>.
/// </summary>
/// <param name="loggerNamePattern">Logger name pattern used for <see cref="LoggerNamePattern"/>. It may include one or more '*' or '?' wildcards at any position.</param>
/// <param name="minLevel">Minimum log level needed to trigger this rule.</param>
/// <param name="maxLevel">Maximum log level needed to trigger this rule.</param>
/// <param name="target">Target to be written to when the rule matches.</param>
public LoggingRule(string loggerNamePattern, LogLevel minLevel, LogLevel maxLevel, Target target)
: this()
{
LoggerNamePattern = loggerNamePattern;
Targets.Add(target);
EnableLoggingForLevels(minLevel, maxLevel);
}
/// <summary>
/// Create a new <see cref="LoggingRule" /> with a <paramref name="minLevel"/> which writes to <paramref name="target"/>.
/// </summary>
/// <param name="loggerNamePattern">Logger name pattern used for <see cref="LoggerNamePattern"/>. It may include one or more '*' or '?' wildcards at any position.</param>
/// <param name="minLevel">Minimum log level needed to trigger this rule.</param>
/// <param name="target">Target to be written to when the rule matches.</param>
public LoggingRule(string loggerNamePattern, LogLevel minLevel, Target target)
: this()
{
LoggerNamePattern = loggerNamePattern;
Targets.Add(target);
EnableLoggingForLevels(minLevel, LogLevel.MaxLevel);
}
/// <summary>
/// Create a (disabled) <see cref="LoggingRule" />. You should call <see cref="EnableLoggingForLevel"/> or see cref="EnableLoggingForLevels"/> to enable logging.
/// </summary>
/// <param name="loggerNamePattern">Logger name pattern used for <see cref="LoggerNamePattern"/>. It may include one or more '*' or '?' wildcards at any position.</param>
/// <param name="target">Target to be written to when the rule matches.</param>
public LoggingRule(string loggerNamePattern, Target target)
: this()
{
LoggerNamePattern = loggerNamePattern;
Targets.Add(target);
}
/// <summary>
/// Rule identifier to allow rule lookup
/// </summary>
public string RuleName { get; }
/// <summary>
/// Gets a collection of targets that should be written to when this rule matches.
/// </summary>
public IList<Target> Targets { get; }
/// <summary>
/// Gets a collection of child rules to be evaluated when this rule matches.
/// </summary>
public IList<LoggingRule> ChildRules { get; }
internal List<LoggingRule> GetChildRulesThreadSafe() { lock (ChildRules) return ChildRules.ToList(); }
internal List<Target> GetTargetsThreadSafe() { lock (Targets) return Targets.ToList(); }
internal bool RemoveTargetThreadSafe(Target target) { lock (Targets) return Targets.Remove(target); }
/// <summary>
/// Gets a collection of filters to be checked before writing to targets.
/// </summary>
public IList<Filter> Filters { get; }
/// <summary>
/// Gets or sets a value indicating whether to quit processing any further rule when this one matches.
/// </summary>
public bool Final { get; set; }
/// <summary>
/// Gets or sets logger name pattern.
/// </summary>
/// <remarks>
/// Logger name pattern used by <see cref="NameMatches(string)"/> to check if a logger name matches this rule.
/// It may include one or more '*' or '?' wildcards at any position.
/// <list type="bullet">
/// <item>'*' means zero or more occurrences of any character</item>
/// <item>'?' means exactly one occurrence of any character</item>
/// </list>
/// </remarks>
public string LoggerNamePattern
{
get => _loggerNameMatcher.Pattern;
set
{
_loggerNameMatcher = LoggerNameMatcher.Create(value);
}
}
/// <summary>
/// Gets the collection of log levels enabled by this rule.
/// </summary>
[NLogConfigurationIgnoreProperty]
public ReadOnlyCollection<LogLevel> Levels
{
get
{
var enabledLogLevels = new List<LogLevel>();
var currentLogLevels = _logLevelFilter.LogLevels;
for (int i = LogLevel.MinLevel.Ordinal; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
if (currentLogLevels[i])
{
enabledLogLevels.Add(LogLevel.FromOrdinal(i));
}
}
return enabledLogLevels.AsReadOnly();
}
}
/// <summary>
/// Default action if none of the filters match
/// </summary>
public FilterResult DefaultFilterResult { get; set; } = FilterResult.Neutral;
/// <summary>
/// Enables logging for a particular level.
/// </summary>
/// <param name="level">Level to be enabled.</param>
public void EnableLoggingForLevel(LogLevel level)
{
if (level == LogLevel.Off)
{
return;
}
_logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(level, level, true);
}
/// <summary>
/// Enables logging for a particular levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>.
/// </summary>
/// <param name="minLevel">Minimum log level needed to trigger this rule.</param>
/// <param name="maxLevel">Maximum log level needed to trigger this rule.</param>
public void EnableLoggingForLevels(LogLevel minLevel, LogLevel maxLevel)
{
_logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(minLevel, maxLevel, true);
}
internal void EnableLoggingForLevels(NLog.Layouts.SimpleLayout simpleLayout)
{
_logLevelFilter = new DynamicLogLevelFilter(this, simpleLayout);
}
internal void EnableLoggingForRange(Layouts.SimpleLayout minLevel, Layouts.SimpleLayout maxLevel)
{
_logLevelFilter = new DynamicRangeLevelFilter(this, minLevel, maxLevel);
}
/// <summary>
/// Disables logging for a particular level.
/// </summary>
/// <param name="level">Level to be disabled.</param>
public void DisableLoggingForLevel(LogLevel level)
{
if (level == LogLevel.Off)
{
return;
}
_logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(level, level, false);
}
/// <summary>
/// Disables logging for particular levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>.
/// </summary>
/// <param name="minLevel">Minimum log level to be disables.</param>
/// <param name="maxLevel">Maximum log level to de disabled.</param>
public void DisableLoggingForLevels(LogLevel minLevel, LogLevel maxLevel)
{
_logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(minLevel, maxLevel, false);
}
/// <summary>
/// Enables logging the levels between (included) <paramref name="minLevel"/> and <paramref name="maxLevel"/>. All the other levels will be disabled.
/// </summary>
/// <param name="minLevel">>Minimum log level needed to trigger this rule.</param>
/// <param name="maxLevel">Maximum log level needed to trigger this rule.</param>
public void SetLoggingLevels(LogLevel minLevel, LogLevel maxLevel)
{
_logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(LogLevel.MinLevel, LogLevel.MaxLevel, false).SetLoggingLevels(minLevel, maxLevel, true);
}
/// <summary>
/// Returns a string representation of <see cref="LoggingRule"/>. Used for debugging.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(_loggerNameMatcher.ToString());
sb.Append(" levels: [ ");
var currentLogLevels = _logLevelFilter.LogLevels;
for (int i = 0; i < currentLogLevels.Length; ++i)
{
if (currentLogLevels[i])
{
sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", LogLevel.FromOrdinal(i).ToString());
}
}
sb.Append("] appendTo: [ ");
foreach (Target app in GetTargetsThreadSafe())
{
sb.AppendFormat(CultureInfo.InvariantCulture, "{0} ", app.Name);
}
sb.Append("]");
return sb.ToString();
}
/// <summary>
/// Checks whether te particular log level is enabled for this rule.
/// </summary>
/// <param name="level">Level to be checked.</param>
/// <returns>A value of <see langword="true"/> when the log level is enabled, <see langword="false" /> otherwise.</returns>
public bool IsLoggingEnabledForLevel(LogLevel level)
{
if (level == LogLevel.Off)
{
return false;
}
var currentLogLevels = _logLevelFilter.LogLevels;
return currentLogLevels[level.Ordinal];
}
/// <summary>
/// Checks whether given name matches the <see cref="LoggerNamePattern"/>.
/// </summary>
/// <param name="loggerName">String to be matched.</param>
/// <returns>A value of <see langword="true"/> when the name matches, <see langword="false" /> otherwise.</returns>
public bool NameMatches(string loggerName)
{
return _loggerNameMatcher.NameMatches(loggerName);
}
}
}
| |
//! \file ImagePSD.cs
//! \date Tue Nov 17 18:22:36 2015
//! \brief Adobe Photoshop file format implementation.
//
// Copyright (C) 2015 by morkt
//
// 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 GameRes.Utility;
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace GameRes.Formats.Adobe
{
internal class PsdMetaData : ImageMetaData
{
public int Channels;
public int Mode;
}
[Export(typeof(ImageFormat))]
public class PsdFormat : ImageFormat
{
public override string Tag { get { return "PSD"; } }
public override string Description { get { return "Adobe Photoshop image format"; } }
public override uint Signature { get { return 0x53504238; } } // '8BPS'
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (26).ToArray();
int version = BigEndian.ToInt16 (header, 4);
if (1 != version)
return null;
int channels = BigEndian.ToInt16 (header, 0x0C);
if (channels < 1 || channels > 56)
return null;
uint height = BigEndian.ToUInt32 (header, 0x0E);
uint width = BigEndian.ToUInt32 (header, 0x12);
if (width < 1 || width > 30000 || height < 1 || height > 30000)
return null;
int bpc = BigEndian.ToInt16 (header, 0x16);
return new PsdMetaData
{
Width = width,
Height = height,
Channels = channels,
BPP = channels * bpc,
Mode = BigEndian.ToInt16 (header, 0x18),
};
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var meta = (PsdMetaData)info;
using (var reader = new PsdReader (stream, meta))
{
reader.Unpack();
return ImageData.Create (info, reader.Format, reader.Palette, reader.Data);
}
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("PsdFormat.Write not implemented");
}
}
internal class PsdReader : IDisposable
{
IBinaryStream m_input;
PsdMetaData m_info;
byte[] m_output;
int m_channel_size;
public PixelFormat Format { get; private set; }
public BitmapPalette Palette { get; private set; }
public byte[] Data { get { return m_output; } }
public PsdReader (IBinaryStream input, PsdMetaData info)
{
m_info = info;
m_input = input;
int bpc = m_info.BPP / m_info.Channels;
switch (m_info.Mode)
{
case 3:
if (8 != bpc)
throw new NotSupportedException();
if (3 == m_info.Channels)
Format = PixelFormats.Bgr24;
else if (4 == m_info.Channels)
Format = PixelFormats.Bgra32;
else if (m_info.Channels > 4)
Format = PixelFormats.Bgr32;
else
throw new NotSupportedException();
break;
// case 2: Format = PixelFormats.Indexed8; break;
case 1:
if (8 == bpc)
Format = PixelFormats.Gray8;
else if (16 == bpc)
Format = PixelFormats.Gray16;
else
throw new NotSupportedException();
break;
case 0: Format = PixelFormats.BlackWhite; break;
default:
throw new NotImplementedException ("Not supported PSD color mode");
}
m_channel_size = (int)m_info.Height * (int)m_info.Width * bpc / 8;
}
public void Unpack ()
{
m_input.Position = 0x1A;
int color_data_length = Binary.BigEndian (m_input.ReadInt32());
long next_pos = m_input.Position + color_data_length;
if (0 != color_data_length)
{
if (8 == m_info.BPP)
ReadPalette (color_data_length);
m_input.Position = next_pos;
}
next_pos += 4 + Binary.BigEndian (m_input.ReadInt32());
m_input.Position = next_pos; // skip Image Resources
next_pos += 4 + Binary.BigEndian (m_input.ReadInt32());
m_input.Position = next_pos; // skip Layer and Mask Information
int compression = Binary.BigEndian (m_input.ReadInt16());
int remaining = checked((int)(m_input.Length - m_input.Position));
byte[] pixels;
if (0 == compression)
pixels = m_input.ReadBytes (remaining);
else if (1 == compression)
pixels = UnpackRLE();
else
throw new NotSupportedException ("PSD files with ZIP compression not supported");
if (1 == m_info.Channels)
{
m_output = pixels;
return;
}
int channels = Math.Min (4, m_info.Channels);
m_output = new byte[channels * m_channel_size];
int src = 0;
for (int ch = 0; ch < channels; ++ch)
{
int dst = ChannelMap[ch];
for (int i = 0; i < m_channel_size; ++i)
{
m_output[dst] = pixels[src++];
dst += channels;
}
}
}
static readonly byte[] ChannelMap = { 2, 1, 0, 3 };
void ReadPalette (int palette_size)
{
int colors = Math.Min (0x100, palette_size/3);
Palette = ImageFormat.ReadPalette (m_input.AsStream, colors, PaletteFormat.Rgb);
}
byte[] UnpackRLE ()
{
var scanlines = new int[m_info.Channels, (int)m_info.Height];
for (int ch = 0; ch < m_info.Channels; ++ch)
{
for (uint row = 0; row < m_info.Height; ++row)
scanlines[ch,row] = Binary.BigEndian (m_input.ReadInt16());
}
var pixels = new byte[m_info.Channels * m_channel_size];
int dst = 0;
for (int ch = 0; ch < m_info.Channels; ++ch)
{
for (uint row = 0; row < m_info.Height; ++row)
{
int line_count = scanlines[ch,row];
int n = 0;
while (n < line_count)
{
int count = m_input.ReadInt8();
++n;
if (count >= 0)
{
++count;
m_input.Read (pixels, dst, count);
dst += count;
n += count;
}
else if (count > -128)
{
count = 1 - count;
byte color = m_input.ReadUInt8();
++n;
for (int i = 0; i < count; ++i)
pixels[dst++] = color;
}
}
}
}
return pixels;
}
#region IDisposable Members
public void Dispose ()
{
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.Hosting
{
public partial class ImportEngine
{
/// <summary>
/// Used by the <see cref="ImportEngine"/> to manage the composition of a given part.
/// It stores things like the list of disposable exports used to satisfy the imports as
/// well as the caching of the exports discovered during previewing of a part.
/// </summary>
private class PartManager
{
private Dictionary<ImportDefinition, List<IDisposable>> _importedDisposableExports;
private Dictionary<ImportDefinition, Export[]> _importCache;
private string[] _importedContractNames;
private ComposablePart _part;
private ImportState _state = ImportState.NoImportsSatisfied;
private readonly ImportEngine _importEngine;
public PartManager(ImportEngine importEngine, ComposablePart part)
{
_importEngine = importEngine;
_part = part;
}
public ComposablePart Part
{
get
{
return _part;
}
}
public ImportState State
{
get
{
using (_importEngine._lock.LockStateForRead())
{
return _state;
}
}
set
{
using (_importEngine._lock.LockStateForWrite())
{
_state = value;
}
}
}
public bool TrackingImports { get; set; }
public IEnumerable<string> GetImportedContractNames()
{
if (Part == null)
{
return Enumerable.Empty<string>();
}
if (_importedContractNames == null)
{
_importedContractNames = Part.ImportDefinitions.Select(import => import.ContractName ?? ImportDefinition.EmptyContractName).Distinct().ToArray();
}
return _importedContractNames;
}
public CompositionResult TrySetImport(ImportDefinition import, Export[] exports)
{
try
{
Part.SetImport(import, exports);
UpdateDisposableDependencies(import, exports);
return CompositionResult.SucceededResult;
}
catch (CompositionException ex)
{ // Pulling on one of the exports failed
return new CompositionResult(
ErrorBuilder.CreatePartCannotSetImport(Part, import, ex));
}
catch (ComposablePartException ex)
{ // Type mismatch between export and import
return new CompositionResult(
ErrorBuilder.CreatePartCannotSetImport(Part, import, ex));
}
}
public void SetSavedImport(ImportDefinition import, Export[] exports, AtomicComposition atomicComposition)
{
if (atomicComposition != null)
{
var savedExports = GetSavedImport(import);
// Add a revert action to revert the stored exports
// in the case that this atomicComposition gets rolled back.
atomicComposition.AddRevertAction(() =>
SetSavedImport(import, savedExports, null));
}
if (_importCache == null)
{
_importCache = new Dictionary<ImportDefinition, Export[]>();
}
_importCache[import] = exports;
}
public Export[] GetSavedImport(ImportDefinition import)
{
Export[] exports = null;
if (_importCache != null)
{
// We don't care about the return value we just want the exports
// and if it isn't present we just return the initialized null value
_importCache.TryGetValue(import, out exports);
}
return exports;
}
public void ClearSavedImports()
{
_importCache = null;
}
public CompositionResult TryOnComposed()
{
try
{
Part.Activate();
return CompositionResult.SucceededResult;
}
catch (ComposablePartException ex)
{ // Type failed to be constructed, imports could not be set, etc
return new CompositionResult(
ErrorBuilder.CreatePartCannotActivate(Part, ex));
}
}
public void UpdateDisposableDependencies(ImportDefinition import, Export[] exports)
{
// Determine if there are any new disposable exports, optimizing for the most
// likely case, which is that there aren't any
List<IDisposable> disposableExports = null;
foreach (var export in exports)
{
IDisposable disposableExport = export as IDisposable;
if (disposableExport != null)
{
if (disposableExports == null)
{
disposableExports = new List<IDisposable>();
}
disposableExports.Add(disposableExport);
}
}
// Dispose any existing references previously set on this import
List<IDisposable> oldDisposableExports = null;
if (_importedDisposableExports != null &&
_importedDisposableExports.TryGetValue(import, out oldDisposableExports))
{
oldDisposableExports.ForEach(disposable => disposable.Dispose());
// If there aren't any replacements, get rid of the old storage
if (disposableExports == null)
{
_importedDisposableExports.Remove(import);
if (!_importedDisposableExports.FastAny())
{
_importedDisposableExports = null;
}
return;
}
}
// Record the new collection
if (disposableExports != null)
{
if (_importedDisposableExports == null)
{
_importedDisposableExports = new Dictionary<ImportDefinition, List<IDisposable>>();
}
_importedDisposableExports[import] = disposableExports;
}
}
public void DisposeAllDependencies()
{
if (_importedDisposableExports != null)
{
IEnumerable<IDisposable> dependencies = _importedDisposableExports.Values
.SelectMany(exports => exports);
_importedDisposableExports = null;
dependencies.ForEach(disposableExport => disposableExport.Dispose());
}
}
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 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.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Timers;
using System.Web;
using ConcurrencyHelpers.Monitor;
using Node.Cs.Lib.Loggers;
using Node.Cs.Lib.Utils;
namespace Node.Cs.Lib.Contexts
{
public class NodeCsResponse : HttpResponseBase, IForcedHeadersResponse
{
const long TIMEOUT_MS = 60000;
static NodeCsResponse()
{
var innerCollectionProperty = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.NonPublic | BindingFlags.Instance);
_getInnerCollection = innerCollectionProperty.GetGetMethod(true);
}
private readonly HttpListenerResponse _response;
private static readonly MethodInfo _getInnerCollection;
//private Timer _timeout;
//private Stopwatch _watch;
private void Restart()
{
//_watch.Reset();
}
public NodeCsResponse(HttpListenerResponse response)
{
/*_watch = new Stopwatch();
_watch.Start();
_timeout = new Timer(TIMEOUT_MS);
_timeout.Elapsed += OnTimeout;
_timeout.Start();*/
_response = response;
}
/*
void OnTimeout(object sender, ElapsedEventArgs e)
{
if (_watch.ElapsedMilliseconds > TIMEOUT_MS)
{
_timeout.Dispose();
try
{
Close();
}
catch
{
}
}
}*/
public override Stream OutputStream
{
get
{
Restart();
return _response.OutputStream;
}
}
public override NameValueCollection Headers
{
get
{
Restart();
return _response.Headers;
}
}
public override string ContentType
{
get
{
Restart();
return _response.ContentType;
}
set
{
_response.ContentType = value;
}
}
public override Encoding ContentEncoding
{
get
{
Restart();
return _response.ContentEncoding;
}
set
{
Restart();
_response.ContentEncoding = value;
}
}
public void ForceHeader(string key, string value)
{
Restart();
var nameValueCollection = (NameValueCollection)_getInnerCollection.Invoke(_response.Headers, new object[] { });
if (!_response.Headers.AllKeys.Contains(key))
{
nameValueCollection.Add(key, value);
}
else
{
nameValueCollection.Set(key, value);
}
}
public override void SetCookie(HttpCookie cookie)
{
Restart();
var discard = cookie.Expires.ToUniversalTime() < DateTime.UtcNow;
_response.SetCookie(new Cookie(cookie.Name, cookie.Value)
{
Path = "/",
Expires = discard ? DateTime.Now.AddDays(-1) : cookie.Expires,
Secure = cookie.Secure
});
}
public override void AppendCookie(HttpCookie cookie)
{
Restart();
var discard = cookie.Expires.ToUniversalTime() < DateTime.UtcNow;
_response.AppendCookie(new Cookie(cookie.Name, cookie.Value)
{
Path = "/",
Expires = discard ? DateTime.Now.AddDays(-1) : cookie.Expires,
Secure = cookie.Secure
});
}
public override int StatusCode
{
get
{
return _response.StatusCode;
}
set
{
Restart();
_response.StatusCode = value;
}
}
private bool _closed;
public override void Close()
{
if (!_closed)
{
PerfMon.SetMetric(PerfMonConst.NodeCs_Network_ClosedConnections, 1);
_closed = true;
try
{
#if !TESTHTTP
_response.Close();
#endif
GlobalVars.OpenedConnections--;
}
catch
{
Logger.Info("Connection already closed.");
}
}
}
public override void Redirect(string url)
{
Restart();
_response.Redirect(url);
}
public void SetContentLength(int p)
{
_response.ContentLength64 = p;
}
}
}
| |
/****************************************************************************
Tilde
Copyright (c) 2008 Tantalus Media Pty
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.
****************************************************************************/
namespace Tilde.CorePlugins.TextEditor
{
partial class FindReplaceDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FindReplaceDialog));
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.buttonFindReplace = new System.Windows.Forms.ToolStripDropDownButton();
this.findToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.replaceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.findInFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.replaceInFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.groupBoxFindOptions = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.comboBoxFileTypes = new System.Windows.Forms.ComboBox();
this.checkBoxIncludeSubFolders = new System.Windows.Forms.CheckBox();
this.labelFileTypes = new System.Windows.Forms.Label();
this.checkBoxMatchCase = new System.Windows.Forms.CheckBox();
this.checkBoxUseRegularExpressions = new System.Windows.Forms.CheckBox();
this.checkBoxMatchWholeWord = new System.Windows.Forms.CheckBox();
this.checkBoxSearchUp = new System.Windows.Forms.CheckBox();
this.labelReplaceWith = new System.Windows.Forms.Label();
this.comboBoxReplaceWith = new System.Windows.Forms.ComboBox();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.labelFindWhat = new System.Windows.Forms.Label();
this.comboBoxFindWhat = new System.Windows.Forms.ComboBox();
this.labelSearchIn = new System.Windows.Forms.Label();
this.panelSearchIn = new System.Windows.Forms.Panel();
this.buttonBrowseSearchIn = new System.Windows.Forms.Button();
this.comboBoxSearchIn = new System.Windows.Forms.ComboBox();
this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
this.buttonFindNext = new System.Windows.Forms.Button();
this.buttonFindAll = new System.Windows.Forms.Button();
this.buttonSkipFile = new System.Windows.Forms.Button();
this.buttonReplace = new System.Windows.Forms.Button();
this.buttonReplaceAll = new System.Windows.Forms.Button();
this.buttonStopFind = new System.Windows.Forms.Button();
this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
this.toolStrip1.SuspendLayout();
this.groupBoxFindOptions.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.panelSearchIn.SuspendLayout();
this.flowLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// toolStrip1
//
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.buttonFindReplace});
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(370, 25);
this.toolStrip1.TabIndex = 1;
this.toolStrip1.Text = "toolStrip1";
//
// buttonFindReplace
//
this.buttonFindReplace.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.buttonFindReplace.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.findToolStripMenuItem,
this.replaceToolStripMenuItem,
this.findInFilesToolStripMenuItem,
this.replaceInFilesToolStripMenuItem});
this.buttonFindReplace.Image = ((System.Drawing.Image)(resources.GetObject("buttonFindReplace.Image")));
this.buttonFindReplace.ImageTransparentColor = System.Drawing.Color.Magenta;
this.buttonFindReplace.Name = "buttonFindReplace";
this.buttonFindReplace.Size = new System.Drawing.Size(40, 22);
this.buttonFindReplace.Text = "Find";
//
// findToolStripMenuItem
//
this.findToolStripMenuItem.Name = "findToolStripMenuItem";
this.findToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.findToolStripMenuItem.Text = "Find";
this.findToolStripMenuItem.Click += new System.EventHandler(this.findToolStripMenuItem_Click);
//
// replaceToolStripMenuItem
//
this.replaceToolStripMenuItem.Name = "replaceToolStripMenuItem";
this.replaceToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.replaceToolStripMenuItem.Text = "Replace";
this.replaceToolStripMenuItem.Click += new System.EventHandler(this.replaceToolStripMenuItem_Click);
//
// findInFilesToolStripMenuItem
//
this.findInFilesToolStripMenuItem.Name = "findInFilesToolStripMenuItem";
this.findInFilesToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.findInFilesToolStripMenuItem.Text = "Find in Files";
this.findInFilesToolStripMenuItem.Click += new System.EventHandler(this.findInFilesToolStripMenuItem_Click);
//
// replaceInFilesToolStripMenuItem
//
this.replaceInFilesToolStripMenuItem.Name = "replaceInFilesToolStripMenuItem";
this.replaceInFilesToolStripMenuItem.Size = new System.Drawing.Size(147, 22);
this.replaceInFilesToolStripMenuItem.Text = "Replace in Files";
this.replaceInFilesToolStripMenuItem.Click += new System.EventHandler(this.replaceInFilesToolStripMenuItem_Click);
//
// groupBoxFindOptions
//
this.groupBoxFindOptions.AutoSize = true;
this.groupBoxFindOptions.Controls.Add(this.tableLayoutPanel2);
this.groupBoxFindOptions.Dock = System.Windows.Forms.DockStyle.Top;
this.groupBoxFindOptions.Location = new System.Drawing.Point(3, 126);
this.groupBoxFindOptions.Name = "groupBoxFindOptions";
this.groupBoxFindOptions.Size = new System.Drawing.Size(364, 174);
this.groupBoxFindOptions.TabIndex = 3;
this.groupBoxFindOptions.TabStop = false;
this.groupBoxFindOptions.Text = "Options";
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.AutoSize = true;
this.tableLayoutPanel2.ColumnCount = 1;
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel2.Controls.Add(this.comboBoxFileTypes, 0, 6);
this.tableLayoutPanel2.Controls.Add(this.checkBoxIncludeSubFolders, 0, 4);
this.tableLayoutPanel2.Controls.Add(this.labelFileTypes, 0, 5);
this.tableLayoutPanel2.Controls.Add(this.checkBoxMatchCase, 0, 0);
this.tableLayoutPanel2.Controls.Add(this.checkBoxUseRegularExpressions, 0, 3);
this.tableLayoutPanel2.Controls.Add(this.checkBoxMatchWholeWord, 0, 1);
this.tableLayoutPanel2.Controls.Add(this.checkBoxSearchUp, 0, 2);
this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 16);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 7;
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.Size = new System.Drawing.Size(358, 155);
this.tableLayoutPanel2.TabIndex = 4;
//
// comboBoxFileTypes
//
this.comboBoxFileTypes.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxFileTypes.Location = new System.Drawing.Point(3, 131);
this.comboBoxFileTypes.Name = "comboBoxFileTypes";
this.comboBoxFileTypes.Size = new System.Drawing.Size(352, 21);
this.comboBoxFileTypes.TabIndex = 6;
this.comboBoxFileTypes.Tag = "FileTypes";
//
// checkBoxIncludeSubFolders
//
this.checkBoxIncludeSubFolders.AutoSize = true;
this.checkBoxIncludeSubFolders.Location = new System.Drawing.Point(3, 95);
this.checkBoxIncludeSubFolders.Name = "checkBoxIncludeSubFolders";
this.checkBoxIncludeSubFolders.Size = new System.Drawing.Size(115, 17);
this.checkBoxIncludeSubFolders.TabIndex = 7;
this.checkBoxIncludeSubFolders.Text = "Include sub-folders";
this.checkBoxIncludeSubFolders.UseVisualStyleBackColor = true;
//
// labelFileTypes
//
this.labelFileTypes.AutoSize = true;
this.labelFileTypes.Location = new System.Drawing.Point(3, 115);
this.labelFileTypes.Name = "labelFileTypes";
this.labelFileTypes.Size = new System.Drawing.Size(128, 13);
this.labelFileTypes.TabIndex = 4;
this.labelFileTypes.Text = "Search in these file types:";
//
// checkBoxMatchCase
//
this.checkBoxMatchCase.AutoSize = true;
this.checkBoxMatchCase.Location = new System.Drawing.Point(3, 3);
this.checkBoxMatchCase.Name = "checkBoxMatchCase";
this.checkBoxMatchCase.Size = new System.Drawing.Size(82, 17);
this.checkBoxMatchCase.TabIndex = 0;
this.checkBoxMatchCase.Text = "Match case";
this.checkBoxMatchCase.UseVisualStyleBackColor = true;
//
// checkBoxUseRegularExpressions
//
this.checkBoxUseRegularExpressions.AutoSize = true;
this.checkBoxUseRegularExpressions.Location = new System.Drawing.Point(3, 72);
this.checkBoxUseRegularExpressions.Name = "checkBoxUseRegularExpressions";
this.checkBoxUseRegularExpressions.Size = new System.Drawing.Size(138, 17);
this.checkBoxUseRegularExpressions.TabIndex = 3;
this.checkBoxUseRegularExpressions.Text = "Use regular expressions";
this.checkBoxUseRegularExpressions.UseVisualStyleBackColor = true;
//
// checkBoxMatchWholeWord
//
this.checkBoxMatchWholeWord.AutoSize = true;
this.checkBoxMatchWholeWord.Location = new System.Drawing.Point(3, 26);
this.checkBoxMatchWholeWord.Name = "checkBoxMatchWholeWord";
this.checkBoxMatchWholeWord.Size = new System.Drawing.Size(113, 17);
this.checkBoxMatchWholeWord.TabIndex = 1;
this.checkBoxMatchWholeWord.Text = "Match whole word";
this.checkBoxMatchWholeWord.UseVisualStyleBackColor = true;
//
// checkBoxSearchUp
//
this.checkBoxSearchUp.AutoSize = true;
this.checkBoxSearchUp.Location = new System.Drawing.Point(3, 49);
this.checkBoxSearchUp.Name = "checkBoxSearchUp";
this.checkBoxSearchUp.Size = new System.Drawing.Size(75, 17);
this.checkBoxSearchUp.TabIndex = 2;
this.checkBoxSearchUp.Text = "Search up";
this.checkBoxSearchUp.UseVisualStyleBackColor = true;
//
// labelReplaceWith
//
this.labelReplaceWith.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelReplaceWith.Location = new System.Drawing.Point(3, 40);
this.labelReplaceWith.Name = "labelReplaceWith";
this.labelReplaceWith.Size = new System.Drawing.Size(364, 13);
this.labelReplaceWith.TabIndex = 3;
this.labelReplaceWith.Text = "Replace with:";
//
// comboBoxReplaceWith
//
this.comboBoxReplaceWith.Dock = System.Windows.Forms.DockStyle.Fill;
this.comboBoxReplaceWith.Location = new System.Drawing.Point(3, 56);
this.comboBoxReplaceWith.Name = "comboBoxReplaceWith";
this.comboBoxReplaceWith.Size = new System.Drawing.Size(364, 21);
this.comboBoxReplaceWith.TabIndex = 2;
this.comboBoxReplaceWith.Tag = "Replace";
this.comboBoxReplaceWith.KeyDown += new System.Windows.Forms.KeyEventHandler(this.comboBoxReplaceWith_KeyDown);
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.labelFindWhat, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.comboBoxFindWhat, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.labelReplaceWith, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.comboBoxReplaceWith, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.labelSearchIn, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.panelSearchIn, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.groupBoxFindOptions, 0, 6);
this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 8);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 25);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 9;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(370, 494);
this.tableLayoutPanel1.TabIndex = 5;
//
// labelFindWhat
//
this.labelFindWhat.Location = new System.Drawing.Point(3, 0);
this.labelFindWhat.Name = "labelFindWhat";
this.labelFindWhat.Size = new System.Drawing.Size(223, 13);
this.labelFindWhat.TabIndex = 2;
this.labelFindWhat.Text = "Find what:";
//
// comboBoxFindWhat
//
this.comboBoxFindWhat.Dock = System.Windows.Forms.DockStyle.Fill;
this.comboBoxFindWhat.Location = new System.Drawing.Point(3, 16);
this.comboBoxFindWhat.Name = "comboBoxFindWhat";
this.comboBoxFindWhat.Size = new System.Drawing.Size(364, 21);
this.comboBoxFindWhat.TabIndex = 1;
this.comboBoxFindWhat.Tag = "Find";
this.comboBoxFindWhat.KeyDown += new System.Windows.Forms.KeyEventHandler(this.comboBoxFindWhat_KeyDown);
this.comboBoxFindWhat.TextChanged += new System.EventHandler(this.comboBoxFindWhat_TextChanged);
//
// labelSearchIn
//
this.labelSearchIn.Dock = System.Windows.Forms.DockStyle.Fill;
this.labelSearchIn.Location = new System.Drawing.Point(3, 80);
this.labelSearchIn.Name = "labelSearchIn";
this.labelSearchIn.Size = new System.Drawing.Size(364, 13);
this.labelSearchIn.TabIndex = 6;
this.labelSearchIn.Text = "Search in:";
//
// panelSearchIn
//
this.panelSearchIn.AutoSize = true;
this.panelSearchIn.Controls.Add(this.buttonBrowseSearchIn);
this.panelSearchIn.Controls.Add(this.comboBoxSearchIn);
this.panelSearchIn.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelSearchIn.Location = new System.Drawing.Point(3, 96);
this.panelSearchIn.Name = "panelSearchIn";
this.panelSearchIn.Size = new System.Drawing.Size(364, 24);
this.panelSearchIn.TabIndex = 4;
//
// buttonBrowseSearchIn
//
this.buttonBrowseSearchIn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonBrowseSearchIn.Location = new System.Drawing.Point(338, 0);
this.buttonBrowseSearchIn.Name = "buttonBrowseSearchIn";
this.buttonBrowseSearchIn.Size = new System.Drawing.Size(26, 21);
this.buttonBrowseSearchIn.TabIndex = 8;
this.buttonBrowseSearchIn.Text = "...";
this.buttonBrowseSearchIn.UseVisualStyleBackColor = true;
this.buttonBrowseSearchIn.Click += new System.EventHandler(this.buttonBrowseSearchIn_Click);
//
// comboBoxSearchIn
//
this.comboBoxSearchIn.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxSearchIn.Location = new System.Drawing.Point(0, 0);
this.comboBoxSearchIn.Name = "comboBoxSearchIn";
this.comboBoxSearchIn.Size = new System.Drawing.Size(332, 21);
this.comboBoxSearchIn.TabIndex = 7;
this.comboBoxSearchIn.Tag = "SearchIn";
//
// flowLayoutPanel1
//
this.flowLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.flowLayoutPanel1.AutoSize = true;
this.flowLayoutPanel1.Controls.Add(this.buttonFindNext);
this.flowLayoutPanel1.Controls.Add(this.buttonFindAll);
this.flowLayoutPanel1.Controls.Add(this.buttonSkipFile);
this.flowLayoutPanel1.Controls.Add(this.buttonReplace);
this.flowLayoutPanel1.Controls.Add(this.buttonReplaceAll);
this.flowLayoutPanel1.Controls.Add(this.buttonStopFind);
this.flowLayoutPanel1.Location = new System.Drawing.Point(3, 306);
this.flowLayoutPanel1.Name = "flowLayoutPanel1";
this.flowLayoutPanel1.Size = new System.Drawing.Size(364, 58);
this.flowLayoutPanel1.TabIndex = 4;
//
// buttonFindNext
//
this.buttonFindNext.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonFindNext.Location = new System.Drawing.Point(3, 3);
this.buttonFindNext.Name = "buttonFindNext";
this.buttonFindNext.Size = new System.Drawing.Size(75, 23);
this.buttonFindNext.TabIndex = 4;
this.buttonFindNext.Text = "Find Next";
this.buttonFindNext.UseVisualStyleBackColor = true;
this.buttonFindNext.Click += new System.EventHandler(this.buttonFindNext_Click);
//
// buttonFindAll
//
this.buttonFindAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonFindAll.Location = new System.Drawing.Point(84, 3);
this.buttonFindAll.Name = "buttonFindAll";
this.buttonFindAll.Size = new System.Drawing.Size(75, 23);
this.buttonFindAll.TabIndex = 7;
this.buttonFindAll.Text = "Find All";
this.buttonFindAll.UseVisualStyleBackColor = true;
this.buttonFindAll.Click += new System.EventHandler(this.buttonFindAll_Click);
//
// buttonSkipFile
//
this.buttonSkipFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonSkipFile.Location = new System.Drawing.Point(165, 3);
this.buttonSkipFile.Name = "buttonSkipFile";
this.buttonSkipFile.Size = new System.Drawing.Size(75, 23);
this.buttonSkipFile.TabIndex = 8;
this.buttonSkipFile.Text = "Skip File";
this.buttonSkipFile.UseVisualStyleBackColor = true;
//
// buttonReplace
//
this.buttonReplace.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonReplace.Location = new System.Drawing.Point(246, 3);
this.buttonReplace.Name = "buttonReplace";
this.buttonReplace.Size = new System.Drawing.Size(75, 23);
this.buttonReplace.TabIndex = 5;
this.buttonReplace.Text = "Replace";
this.buttonReplace.UseVisualStyleBackColor = true;
this.buttonReplace.Click += new System.EventHandler(this.buttonReplace_Click);
//
// buttonReplaceAll
//
this.buttonReplaceAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonReplaceAll.Location = new System.Drawing.Point(3, 32);
this.buttonReplaceAll.Name = "buttonReplaceAll";
this.buttonReplaceAll.Size = new System.Drawing.Size(75, 23);
this.buttonReplaceAll.TabIndex = 6;
this.buttonReplaceAll.Text = "Replace All";
this.buttonReplaceAll.UseVisualStyleBackColor = true;
this.buttonReplaceAll.Click += new System.EventHandler(this.buttonReplaceAll_Click);
//
// buttonStopFind
//
this.buttonStopFind.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonStopFind.Location = new System.Drawing.Point(84, 32);
this.buttonStopFind.Name = "buttonStopFind";
this.buttonStopFind.Size = new System.Drawing.Size(75, 23);
this.buttonStopFind.TabIndex = 9;
this.buttonStopFind.Text = "Stop Find";
this.buttonStopFind.UseVisualStyleBackColor = true;
this.buttonStopFind.Click += new System.EventHandler(this.buttonStopFind_Click);
//
// FindReplaceDialog
//
this.ClientSize = new System.Drawing.Size(370, 519);
this.Controls.Add(this.tableLayoutPanel1);
this.Controls.Add(this.toolStrip1);
this.DockAreas = ((WeifenLuo.WinFormsUI.Docking.DockAreas)(((((WeifenLuo.WinFormsUI.Docking.DockAreas.Float | WeifenLuo.WinFormsUI.Docking.DockAreas.DockLeft)
| WeifenLuo.WinFormsUI.Docking.DockAreas.DockRight)
| WeifenLuo.WinFormsUI.Docking.DockAreas.DockTop)
| WeifenLuo.WinFormsUI.Docking.DockAreas.DockBottom)));
this.KeyPreview = true;
this.Name = "FindReplaceDialog";
this.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.Float;
this.TabText = "Find/Replace";
this.Text = "Find/Replace";
this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.FindReplaceDialog_KeyUp);
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.groupBoxFindOptions.ResumeLayout(false);
this.groupBoxFindOptions.PerformLayout();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.panelSearchIn.ResumeLayout(false);
this.flowLayoutPanel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.GroupBox groupBoxFindOptions;
private System.Windows.Forms.CheckBox checkBoxUseRegularExpressions;
private System.Windows.Forms.CheckBox checkBoxSearchUp;
private System.Windows.Forms.CheckBox checkBoxMatchWholeWord;
private System.Windows.Forms.CheckBox checkBoxMatchCase;
private System.Windows.Forms.Label labelReplaceWith;
private System.Windows.Forms.ComboBox comboBoxReplaceWith;
private System.Windows.Forms.ToolStripDropDownButton buttonFindReplace;
private System.Windows.Forms.ToolStripMenuItem findToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem replaceToolStripMenuItem;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Label labelFindWhat;
private System.Windows.Forms.ComboBox comboBoxFindWhat;
private System.Windows.Forms.Button buttonFindNext;
private System.Windows.Forms.Button buttonReplace;
private System.Windows.Forms.Button buttonReplaceAll;
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
private System.Windows.Forms.Label labelSearchIn;
private System.Windows.Forms.ToolStripMenuItem findInFilesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem replaceInFilesToolStripMenuItem;
private System.Windows.Forms.ComboBox comboBoxFileTypes;
private System.Windows.Forms.Label labelFileTypes;
private System.Windows.Forms.Button buttonFindAll;
private System.Windows.Forms.Button buttonSkipFile;
private System.Windows.Forms.Panel panelSearchIn;
private System.Windows.Forms.Button buttonBrowseSearchIn;
private System.Windows.Forms.ComboBox comboBoxSearchIn;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog;
private System.Windows.Forms.Button buttonStopFind;
private System.Windows.Forms.CheckBox checkBoxIncludeSubFolders;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// ProductEdit (editable root object).<br/>
/// This is a generated <see cref="ProductEdit"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="Suppliers"/> of type <see cref="ProductSupplierColl"/> (1:M relation to <see cref="ProductSupplierItem"/>)
/// </remarks>
[Serializable]
public partial class ProductEdit : BusinessBase<ProductEdit>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="ProductId"/> property.
/// </summary>
[NotUndoable]
public static readonly PropertyInfo<Guid> ProductIdProperty = RegisterProperty<Guid>(p => p.ProductId, "Product Id");
/// <summary>
/// Gets or sets the Product Id.
/// </summary>
/// <value>The Product Id.</value>
public Guid ProductId
{
get { return GetProperty(ProductIdProperty); }
set { SetProperty(ProductIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="ProductCode"/> property.
/// </summary>
public static readonly PropertyInfo<string> ProductCodeProperty = RegisterProperty<string>(p => p.ProductCode, "Product Code");
/// <summary>
/// Gets or sets the Product Code.
/// </summary>
/// <value>The Product Code.</value>
public string ProductCode
{
get { return GetProperty(ProductCodeProperty); }
set { SetProperty(ProductCodeProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name, "Name");
/// <summary>
/// Gets or sets the Name.
/// </summary>
/// <value>The Name.</value>
public string Name
{
get { return GetProperty(NameProperty); }
set { SetProperty(NameProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="ProductTypeId"/> property.
/// </summary>
public static readonly PropertyInfo<int> ProductTypeIdProperty = RegisterProperty<int>(p => p.ProductTypeId, "Product Type Id");
/// <summary>
/// Gets or sets the Product Type Id.
/// </summary>
/// <value>The Product Type Id.</value>
public int ProductTypeId
{
get { return GetProperty(ProductTypeIdProperty); }
set { SetProperty(ProductTypeIdProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="UnitCost"/> property.
/// </summary>
public static readonly PropertyInfo<string> UnitCostProperty = RegisterProperty<string>(p => p.UnitCost, "Unit Cost");
/// <summary>
/// Gets or sets the Unit Cost.
/// </summary>
/// <value>The Unit Cost.</value>
public string UnitCost
{
get { return GetProperty(UnitCostProperty); }
set { SetProperty(UnitCostProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="StockByteNull"/> property.
/// </summary>
public static readonly PropertyInfo<byte?> StockByteNullProperty = RegisterProperty<byte?>(p => p.StockByteNull, "Stock Byte Null");
/// <summary>
/// Gets or sets the Stock Byte Null.
/// </summary>
/// <value>The Stock Byte Null.</value>
public byte? StockByteNull
{
get { return GetProperty(StockByteNullProperty); }
set { SetProperty(StockByteNullProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="StockByte"/> property.
/// </summary>
public static readonly PropertyInfo<byte> StockByteProperty = RegisterProperty<byte>(p => p.StockByte, "Stock Byte");
/// <summary>
/// Gets or sets the Stock Byte.
/// </summary>
/// <value>The Stock Byte.</value>
public byte StockByte
{
get { return GetProperty(StockByteProperty); }
set { SetProperty(StockByteProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="StockShortNull"/> property.
/// </summary>
public static readonly PropertyInfo<short?> StockShortNullProperty = RegisterProperty<short?>(p => p.StockShortNull, "Stock Short Null");
/// <summary>
/// Gets or sets the Stock Short Null.
/// </summary>
/// <value>The Stock Short Null.</value>
public short? StockShortNull
{
get { return GetProperty(StockShortNullProperty); }
set { SetProperty(StockShortNullProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="StockShort"/> property.
/// </summary>
public static readonly PropertyInfo<short> StockShortProperty = RegisterProperty<short>(p => p.StockShort, "Stock Short");
/// <summary>
/// Gets or sets the Stock Short.
/// </summary>
/// <value>The Stock Short.</value>
public short StockShort
{
get { return GetProperty(StockShortProperty); }
set { SetProperty(StockShortProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="StockIntNull"/> property.
/// </summary>
public static readonly PropertyInfo<int?> StockIntNullProperty = RegisterProperty<int?>(p => p.StockIntNull, "Stock Int Null");
/// <summary>
/// Gets or sets the Stock Int Null.
/// </summary>
/// <value>The Stock Int Null.</value>
public int? StockIntNull
{
get { return GetProperty(StockIntNullProperty); }
set { SetProperty(StockIntNullProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="StockInt"/> property.
/// </summary>
public static readonly PropertyInfo<int> StockIntProperty = RegisterProperty<int>(p => p.StockInt, "Stock Int");
/// <summary>
/// Gets or sets the Stock Int.
/// </summary>
/// <value>The Stock Int.</value>
public int StockInt
{
get { return GetProperty(StockIntProperty); }
set { SetProperty(StockIntProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="StockLongNull"/> property.
/// </summary>
public static readonly PropertyInfo<long?> StockLongNullProperty = RegisterProperty<long?>(p => p.StockLongNull, "Stock Long Null");
/// <summary>
/// Gets or sets the Stock Long Null.
/// </summary>
/// <value>The Stock Long Null.</value>
public long? StockLongNull
{
get { return GetProperty(StockLongNullProperty); }
set { SetProperty(StockLongNullProperty, value); }
}
/// <summary>
/// Maintains metadata about <see cref="StockLong"/> property.
/// </summary>
public static readonly PropertyInfo<long> StockLongProperty = RegisterProperty<long>(p => p.StockLong, "Stock Long");
/// <summary>
/// Gets or sets the Stock Long.
/// </summary>
/// <value>The Stock Long.</value>
public long StockLong
{
get { return GetProperty(StockLongProperty); }
set { SetProperty(StockLongProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="Suppliers"/> property.
/// </summary>
public static readonly PropertyInfo<ProductSupplierColl> SuppliersProperty = RegisterProperty<ProductSupplierColl>(p => p.Suppliers, "Suppliers", RelationshipTypes.Child);
/// <summary>
/// Gets the Suppliers ("parent load" child property).
/// </summary>
/// <value>The Suppliers.</value>
public ProductSupplierColl Suppliers
{
get { return GetProperty(SuppliersProperty); }
private set { LoadProperty(SuppliersProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="ProductEdit"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="ProductEdit"/> object.</returns>
public static ProductEdit NewProductEdit()
{
return DataPortal.Create<ProductEdit>();
}
/// <summary>
/// Factory method. Loads a <see cref="ProductEdit"/> object, based on given parameters.
/// </summary>
/// <param name="productId">The ProductId parameter of the ProductEdit to fetch.</param>
/// <returns>A reference to the fetched <see cref="ProductEdit"/> object.</returns>
public static ProductEdit GetProductEdit(Guid productId)
{
return DataPortal.Fetch<ProductEdit>(productId);
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="ProductEdit"/> object.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewProductEdit(EventHandler<DataPortalResult<ProductEdit>> callback)
{
DataPortal.BeginCreate<ProductEdit>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="ProductEdit"/> object, based on given parameters.
/// </summary>
/// <param name="productId">The ProductId parameter of the ProductEdit to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetProductEdit(Guid productId, EventHandler<DataPortalResult<ProductEdit>> callback)
{
DataPortal.BeginFetch<ProductEdit>(productId, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductEdit"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductEdit()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="ProductEdit"/> object properties.
/// </summary>
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(ProductIdProperty, Guid.NewGuid());
LoadProperty(ProductCodeProperty, null);
LoadProperty(SuppliersProperty, DataPortal.CreateChild<ProductSupplierColl>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.DataPortal_Create();
}
/// <summary>
/// Loads a <see cref="ProductEdit"/> object from the database, based on given criteria.
/// </summary>
/// <param name="productId">The Product Id.</param>
protected void DataPortal_Fetch(Guid productId)
{
var args = new DataPortalHookArgs(productId);
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<IProductEditDal>();
var data = dal.Fetch(productId);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
if (dr.Read())
{
Fetch(dr);
FetchChildren(dr);
}
}
}
/// <summary>
/// Loads a <see cref="ProductEdit"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(ProductIdProperty, dr.GetGuid("ProductId"));
LoadProperty(ProductCodeProperty, dr.IsDBNull("ProductCode") ? null : dr.GetString("ProductCode"));
LoadProperty(NameProperty, dr.GetString("Name"));
LoadProperty(ProductTypeIdProperty, dr.GetInt32("ProductTypeId"));
LoadProperty(UnitCostProperty, dr.GetString("UnitCost"));
LoadProperty(StockByteNullProperty, (byte?)dr.GetValue("StockByteNull"));
LoadProperty(StockByteProperty, dr.GetByte("StockByte"));
LoadProperty(StockShortNullProperty, (short?)dr.GetValue("StockShortNull"));
LoadProperty(StockShortProperty, dr.GetInt16("StockShort"));
LoadProperty(StockIntNullProperty, (int?)dr.GetValue("StockIntNull"));
LoadProperty(StockIntProperty, dr.GetInt32("StockInt"));
LoadProperty(StockLongNullProperty, (long?)dr.GetValue("StockLongNull"));
LoadProperty(StockLongProperty, dr.GetInt64("StockLong"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void FetchChildren(SafeDataReader dr)
{
dr.NextResult();
LoadProperty(SuppliersProperty, DataPortal.FetchChild<ProductSupplierColl>(dr));
}
/// <summary>
/// Inserts a new <see cref="ProductEdit"/> object in the database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IProductEditDal>();
using (BypassPropertyChecks)
{
dal.Insert(
ProductId,
ProductCode,
Name,
ProductTypeId,
UnitCost,
StockByteNull,
StockByte,
StockShortNull,
StockShort,
StockIntNull,
StockInt,
StockLongNull,
StockLong
);
}
OnInsertPost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="ProductEdit"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IProductEditDal>();
using (BypassPropertyChecks)
{
dal.Update(
ProductId,
ProductCode,
Name,
ProductTypeId,
UnitCost,
StockByteNull,
StockByte,
StockShortNull,
StockShort,
StockIntNull,
StockInt,
StockLongNull,
StockLong
);
}
OnUpdatePost(args);
// flushes all pending data operations
FieldManager.UpdateChildren(this);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright (C) 2014 - 2015 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
#if UNITY_4_6 || UNITY_5
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TextMeshProUGUI)), CanEditMultipleObjects]
public class TMPro_uiEditorPanel : Editor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
public static bool textInput = true;
public static bool fontSettings = true;
public static bool extraSettings = false;
public static bool shadowSetting = false;
public static bool materialEditor = true;
}
//private static int m_eventID;
private static string[] uiStateLabel = new string[] { "\t- <i>Click to expand</i> -", "\t- <i>Click to collapse</i> -" };
private const string k_UndoRedo = "UndoRedoPerformed";
public int selAlignGrid_A = 0;
public int selAlignGrid_B = 0;
// Serialized Properties
private SerializedProperty text_prop;
private SerializedProperty fontAsset_prop;
private SerializedProperty fontSharedMaterial_prop;
//private SerializedProperty fontBaseMaterial_prop;
private SerializedProperty isNewBaseMaterial_prop;
private SerializedProperty fontStyle_prop;
// Color Properties
private SerializedProperty fontColor_prop;
private SerializedProperty enableVertexGradient_prop;
private SerializedProperty fontColorGradient_prop;
private SerializedProperty overrideHtmlColor_prop;
private SerializedProperty fontSize_prop;
private SerializedProperty fontSizeBase_prop;
private SerializedProperty autoSizing_prop;
private SerializedProperty fontSizeMin_prop;
private SerializedProperty fontSizeMax_prop;
//private SerializedProperty charSpacingMax_prop;
private SerializedProperty lineSpacingMax_prop;
private SerializedProperty charWidthMaxAdj_prop;
private SerializedProperty characterSpacing_prop;
private SerializedProperty lineSpacing_prop;
private SerializedProperty paragraphSpacing_prop;
private SerializedProperty textAlignment_prop;
//private SerializedProperty textAlignment_prop;
private SerializedProperty horizontalMapping_prop;
private SerializedProperty verticalMapping_prop;
private SerializedProperty uvOffset_prop;
private SerializedProperty uvLineOffset_prop;
private SerializedProperty enableWordWrapping_prop;
private SerializedProperty wordWrappingRatios_prop;
private SerializedProperty textOverflowMode_prop;
private SerializedProperty pageToDisplay_prop;
private SerializedProperty enableKerning_prop;
private SerializedProperty inputSource_prop;
private SerializedProperty havePropertiesChanged_prop;
private SerializedProperty isInputPasingRequired_prop;
//private SerializedProperty isCalculateSizeRequired_prop;
private SerializedProperty isRichText_prop;
private SerializedProperty hasFontAssetChanged_prop;
private SerializedProperty enableExtraPadding_prop;
private SerializedProperty checkPaddingRequired_prop;
//private SerializedProperty isOrthographic_prop;
//private SerializedProperty textRectangle_prop;
private SerializedProperty margin_prop;
//private SerializedProperty isMaskUpdateRequired_prop;
//private SerializedProperty mask_prop;
private SerializedProperty maskOffset_prop;
//private SerializedProperty maskOffsetMode_prop;
//private SerializedProperty maskSoftness_prop;
//private SerializedProperty vertexOffset_prop;
//private SerializedProperty sortingLayerID_prop;
//private SerializedProperty sortingOrder_prop;
private bool havePropertiesChanged = false;
private TextMeshProUGUI m_textMeshProScript;
private RectTransform m_rectTransform;
private CanvasRenderer m_uiRenderer;
private Editor m_materialEditor;
private Material m_targetMaterial;
private Rect m_inspectorStartRegion;
private Rect m_inspectorEndRegion;
//private bool m_isMultiSelection;
//private bool m_isMixSelectionTypes;
//private TMPro_UpdateManager m_updateManager;
private Vector3[] m_rectCorners = new Vector3[4];
private Vector3[] handlePoints = new Vector3[4]; // { new Vector3(-10, -10, 0), new Vector3(-10, 10, 0), new Vector3(10, 10, 0), new Vector3(10, -10, 0) };
//private float prev_lineLenght;
//private bool m_isUndoSet;
public void OnEnable()
{
//Debug.Log("New Instance of TMPRO UGUI Editor with ID " + this.GetInstanceID());
// Initialize the Event Listener for Undo Events.
Undo.undoRedoPerformed += OnUndoRedo;
//Undo.postprocessModifications += OnUndoRedoEvent;
text_prop = serializedObject.FindProperty("m_text");
fontAsset_prop = serializedObject.FindProperty("m_fontAsset");
fontSharedMaterial_prop = serializedObject.FindProperty("m_sharedMaterial");
//fontBaseMaterial_prop = serializedObject.FindProperty("m_baseMaterial");
isNewBaseMaterial_prop = serializedObject.FindProperty("m_isNewBaseMaterial");
fontStyle_prop = serializedObject.FindProperty("m_fontStyle");
fontSize_prop = serializedObject.FindProperty("m_fontSize");
fontSizeBase_prop = serializedObject.FindProperty("m_fontSizeBase");
autoSizing_prop = serializedObject.FindProperty("m_enableAutoSizing");
fontSizeMin_prop = serializedObject.FindProperty("m_fontSizeMin");
fontSizeMax_prop = serializedObject.FindProperty("m_fontSizeMax");
//charSpacingMax_prop = serializedObject.FindProperty("m_charSpacingMax");
lineSpacingMax_prop = serializedObject.FindProperty("m_lineSpacingMax");
charWidthMaxAdj_prop = serializedObject.FindProperty("m_charWidthMaxAdj");
// Colors & Gradient
fontColor_prop = serializedObject.FindProperty("m_fontColor");
enableVertexGradient_prop = serializedObject.FindProperty ("m_enableVertexGradient");
fontColorGradient_prop = serializedObject.FindProperty ("m_fontColorGradient");
overrideHtmlColor_prop = serializedObject.FindProperty("m_overrideHtmlColors");
characterSpacing_prop = serializedObject.FindProperty("m_characterSpacing");
lineSpacing_prop = serializedObject.FindProperty("m_lineSpacing");
paragraphSpacing_prop = serializedObject.FindProperty("m_paragraphSpacing");
textAlignment_prop = serializedObject.FindProperty("m_textAlignment");
enableWordWrapping_prop = serializedObject.FindProperty("m_enableWordWrapping");
wordWrappingRatios_prop = serializedObject.FindProperty("m_wordWrappingRatios");
textOverflowMode_prop = serializedObject.FindProperty("m_overflowMode");
pageToDisplay_prop = serializedObject.FindProperty("m_pageToDisplay");
horizontalMapping_prop = serializedObject.FindProperty("m_horizontalMapping");
verticalMapping_prop = serializedObject.FindProperty("m_verticalMapping");
uvOffset_prop = serializedObject.FindProperty("m_uvOffset");
uvLineOffset_prop = serializedObject.FindProperty("m_uvLineOffset");
enableKerning_prop = serializedObject.FindProperty("m_enableKerning");
//isOrthographic_prop = serializedObject.FindProperty("m_isOrthographic");
havePropertiesChanged_prop = serializedObject.FindProperty("havePropertiesChanged");
inputSource_prop = serializedObject.FindProperty("m_inputSource");
isInputPasingRequired_prop = serializedObject.FindProperty("isInputParsingRequired");
//isCalculateSizeRequired_prop = serializedObject.FindProperty("m_isCalculateSizeRequired");
enableExtraPadding_prop = serializedObject.FindProperty("m_enableExtraPadding");
isRichText_prop = serializedObject.FindProperty("m_isRichText");
checkPaddingRequired_prop = serializedObject.FindProperty("checkPaddingRequired");
margin_prop = serializedObject.FindProperty("m_margin");
//isMaskUpdateRequired_prop = serializedObject.FindProperty("isMaskUpdateRequired");
//mask_prop = serializedObject.FindProperty("m_mask");
maskOffset_prop= serializedObject.FindProperty("m_maskOffset");
//maskOffsetMode_prop = serializedObject.FindProperty("m_maskOffsetMode");
//maskSoftness_prop = serializedObject.FindProperty("m_maskSoftness");
//vertexOffset_prop = serializedObject.FindProperty("m_vertexOffset");
//sortingLayerID_prop = serializedObject.FindProperty("m_sortingLayerID");
//sortingOrder_prop = serializedObject.FindProperty("m_sortingOrder");
hasFontAssetChanged_prop = serializedObject.FindProperty("hasFontAssetChanged");
// Get the UI Skin and Styles for the various Editors
TMP_UIStyleManager.GetUIStyles();
m_textMeshProScript = (TextMeshProUGUI)target;
m_rectTransform = Selection.activeGameObject.GetComponent<RectTransform>();
m_uiRenderer = Selection.activeGameObject.GetComponent<CanvasRenderer>();
// Add a Material Component if one does not exists
/*
m_materialComponent = Selection.activeGameObject.GetComponent<MaterialComponent> ();
if (m_materialComponent == null)
{
m_materialComponent = Selection.activeGameObject.AddComponent<MaterialComponent> ();
}
*/
// Create new Material Editor if one does not exists
if (m_uiRenderer != null && m_uiRenderer.GetMaterial() != null)
{
m_materialEditor = Editor.CreateEditor(m_uiRenderer.GetMaterial());
m_targetMaterial = m_uiRenderer.GetMaterial();
//UnityEditorInternal.InternalEditorUtility.SetIsInspectorExpanded(m_targetMaterial, true);
//Debug.Log("Currently Assigned Material is " + m_targetMaterial + ". Font Material is " + m_textMeshProScript.fontSharedMaterial);
}
//m_updateManager = Camera.main.gameObject.GetComponent<TMPro_UpdateManager>();
}
public void OnDisable()
{
//Debug.Log("OnDisable() for GUIEditor Panel called.");
Undo.undoRedoPerformed -= OnUndoRedo;
// Destroy material editor if one exists
if (m_materialEditor != null)
{
//Debug.Log("Destroying Inline Material Editor.");
DestroyImmediate(m_materialEditor);
}
//Undo.postprocessModifications -= OnUndoRedoEvent;
}
public override void OnInspectorGUI()
{
// Make sure Multi selection only includes TMP Text objects.
if (IsMixSelectionTypes()) return;
serializedObject.Update();
//EditorGUIUtility.LookLikeControls(150, 30);
Rect rect;
float labelWidth = EditorGUIUtility.labelWidth = 130f;
float fieldWidth = EditorGUIUtility.fieldWidth;
// TEXT INPUT BOX SECTION
if (GUILayout.Button("<b>TEXT INPUT BOX</b>" + (m_foldout.textInput ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
m_foldout.textInput = !m_foldout.textInput;
if (m_foldout.textInput)
{
EditorGUI.BeginChangeCheck();
text_prop.stringValue = EditorGUILayout.TextArea(text_prop.stringValue, TMP_UIStyleManager.TextAreaBoxEditor, GUILayout.Height(125), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
inputSource_prop.enumValueIndex = 0;
isInputPasingRequired_prop.boolValue = true;
//isCalculateSizeRequired_prop.boolValue = true;
havePropertiesChanged = true;
}
}
// FONT SETTINGS SECTION
if (GUILayout.Button("<b>FONT SETTINGS</b>" + (m_foldout.fontSettings ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
m_foldout.fontSettings = !m_foldout.fontSettings;
if (m_foldout.fontSettings)
{
// FONT ASSET
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontAsset_prop);
if (EditorGUI.EndChangeCheck())
{
//Undo.RecordObject(m_textMeshProScript, "Material Change");
havePropertiesChanged = true;
hasFontAssetChanged_prop.boolValue = true;
}
// FONT STYLE
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Font Style");
int styleValue = fontStyle_prop.intValue;
int v1 = GUILayout.Toggle((styleValue & 1) == 1, "B", GUI.skin.button) ? 1 : 0; // Bold
int v2 = GUILayout.Toggle((styleValue & 2) == 2, "I", GUI.skin.button) ? 2 : 0; // Italics
int v3 = GUILayout.Toggle((styleValue & 4) == 4, "U", GUI.skin.button) ? 4 : 0; // Underline
int v7 = GUILayout.Toggle((styleValue & 64) == 64, "S", GUI.skin.button) ? 64 : 0; // Strikethrough
int v4 = GUILayout.Toggle((styleValue & 8) == 8, "ab", GUI.skin.button) ? 8 : 0; // Lowercase
int v5 = GUILayout.Toggle((styleValue & 16) == 16, "AB", GUI.skin.button) ? 16 : 0; // Uppercase
int v6 = GUILayout.Toggle((styleValue & 32) == 32, "SC", GUI.skin.button) ? 32 : 0; // Smallcaps
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
fontStyle_prop.intValue = v1 + v2 + v3 + v4 + v5 + v6 + v7;
havePropertiesChanged = true;
}
// FACE VERTEX COLOR
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontColor_prop, new GUIContent("Color (Vertex)"));
// VERTEX COLOR GRADIENT
EditorGUILayout.BeginHorizontal();
//EditorGUILayout.PrefixLabel("Color Gradient");
EditorGUILayout.PropertyField(enableVertexGradient_prop, new GUIContent("Color Gradient"), GUILayout.MinWidth(140), GUILayout.MaxWidth(200));
EditorGUIUtility.labelWidth = 95;
EditorGUILayout.PropertyField(overrideHtmlColor_prop, new GUIContent("Override Tags"));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (enableVertexGradient_prop.boolValue)
{
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("topLeft"), new GUIContent("Top Left"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("topRight"), new GUIContent("Top Right"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("bottomLeft"), new GUIContent("Bottom Left"));
EditorGUILayout.PropertyField(fontColorGradient_prop.FindPropertyRelative("bottomRight"), new GUIContent("Bottom Right"));
}
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// FONT SIZE
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(fontSize_prop, new GUIContent("Font Size"), GUILayout.MinWidth(168), GUILayout.MaxWidth(200));
EditorGUIUtility.fieldWidth = fieldWidth;
if (EditorGUI.EndChangeCheck())
{
fontSizeBase_prop.floatValue = fontSize_prop.floatValue;
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
EditorGUI.BeginChangeCheck();
EditorGUIUtility.labelWidth = 70;
EditorGUILayout.PropertyField(autoSizing_prop, new GUIContent("Auto Size"));
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = labelWidth;
if (EditorGUI.EndChangeCheck())
{
if (autoSizing_prop.boolValue == false)
fontSize_prop.floatValue = fontSizeBase_prop.floatValue;
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
// Show auto sizing options
if (autoSizing_prop.boolValue)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Auto Size Options");
EditorGUIUtility.labelWidth = 24;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontSizeMin_prop, new GUIContent("Min"), GUILayout.MinWidth(46));
if (EditorGUI.EndChangeCheck())
{
fontSizeMin_prop.floatValue = Mathf.Min(fontSizeMin_prop.floatValue, fontSizeMax_prop.floatValue);
havePropertiesChanged = true;
}
EditorGUIUtility.labelWidth = 27;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(fontSizeMax_prop, new GUIContent("Max"), GUILayout.MinWidth(49));
if (EditorGUI.EndChangeCheck())
{
fontSizeMax_prop.floatValue = Mathf.Max(fontSizeMin_prop.floatValue, fontSizeMax_prop.floatValue);
havePropertiesChanged = true;
}
EditorGUI.BeginChangeCheck();
EditorGUIUtility.labelWidth = 36;
//EditorGUILayout.PropertyField(charSpacingMax_prop, new GUIContent("Char"), GUILayout.MinWidth(50));
EditorGUILayout.PropertyField(charWidthMaxAdj_prop, new GUIContent("WD%"), GUILayout.MinWidth(58));
EditorGUIUtility.labelWidth = 28;
EditorGUILayout.PropertyField(lineSpacingMax_prop, new GUIContent("Line"), GUILayout.MinWidth(50));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
charWidthMaxAdj_prop.floatValue = Mathf.Clamp(charWidthMaxAdj_prop.floatValue, 0, 50);
//charSpacingMax_prop.floatValue = Mathf.Min(0, charSpacingMax_prop.floatValue);
lineSpacingMax_prop.floatValue = Mathf.Min(0, lineSpacingMax_prop.floatValue);
havePropertiesChanged = true;
}
}
// CHARACTER, LINE & PARAGRAPH SPACING
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Spacing Options");
EditorGUIUtility.labelWidth = 30;
EditorGUILayout.PropertyField(characterSpacing_prop, new GUIContent("Char"), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUILayout.PropertyField(lineSpacing_prop, new GUIContent("Line"), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUILayout.PropertyField(paragraphSpacing_prop, new GUIContent(" Par."), GUILayout.MinWidth(50)); //, GUILayout.MaxWidth(100));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
//isAffectingWordWrapping_prop.boolValue = true;
}
// TEXT ALIGNMENT
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false, 17);
GUIStyle btn = new GUIStyle(GUI.skin.button);
btn.margin = new RectOffset(1, 1, 1, 1);
btn.padding = new RectOffset(1, 1, 1, 0);
selAlignGrid_A = textAlignment_prop.enumValueIndex & ~28;
selAlignGrid_B = (textAlignment_prop.enumValueIndex & ~3) / 4;
GUI.Label(new Rect(rect.x, rect.y, 100, rect.height), "Alignment");
float columnB = EditorGUIUtility.labelWidth + 15;
selAlignGrid_A = GUI.SelectionGrid(new Rect(columnB, rect.y, 23 * 4, rect.height), selAlignGrid_A, TMP_UIStyleManager.alignContent_A, 4, btn);
selAlignGrid_B = GUI.SelectionGrid(new Rect(columnB + 23 * 4 + 10, rect.y, 23 * 5, rect.height), selAlignGrid_B, TMP_UIStyleManager.alignContent_B, 5, btn);
if (EditorGUI.EndChangeCheck())
{
textAlignment_prop.enumValueIndex = selAlignGrid_A + selAlignGrid_B * 4;
havePropertiesChanged = true;
}
// WRAPPING RATIOS shown if Justified mode is selected.
EditorGUI.BeginChangeCheck();
if (textAlignment_prop.enumValueIndex == 3 || textAlignment_prop.enumValueIndex == 7 || textAlignment_prop.enumValueIndex == 11 || textAlignment_prop.enumValueIndex == 19)
DrawPropertySlider("Wrap Mix (W <-> C)", wordWrappingRatios_prop);
if (EditorGUI.EndChangeCheck())
havePropertiesChanged = true;
// TEXT WRAPPING & OVERFLOW
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false);
EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 130, rect.height), new GUIContent("Wrapping & Overflow"));
rect.width = (rect.width - 130) / 2f;
rect.x += 130;
int wrapSelection = EditorGUI.Popup(rect, enableWordWrapping_prop.boolValue ? 1 : 0, new string[] { "Disabled", "Enabled" });
if (EditorGUI.EndChangeCheck())
{
enableWordWrapping_prop.boolValue = wrapSelection == 1 ? true : false;
havePropertiesChanged = true;
isInputPasingRequired_prop.boolValue = true;
}
// TEXT OVERFLOW
EditorGUI.BeginChangeCheck();
if (textOverflowMode_prop.enumValueIndex != 5)
{
rect.x += rect.width + 5f;
rect.width -= 5;
EditorGUI.PropertyField(rect, textOverflowMode_prop, GUIContent.none);
}
else
{
rect.x += rect.width + 5f;
rect.width /= 2;
EditorGUI.PropertyField(rect, textOverflowMode_prop, GUIContent.none);
rect.x += rect.width;
rect.width -= 5;
EditorGUI.PropertyField(rect, pageToDisplay_prop, GUIContent.none);
}
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
isInputPasingRequired_prop.boolValue = true;
}
// TEXTURE MAPPING OPTIONS
EditorGUI.BeginChangeCheck();
rect = EditorGUILayout.GetControlRect(false);
EditorGUI.PrefixLabel(new Rect(rect.x, rect.y, 130, rect.height), new GUIContent("UV Mapping Options"));
rect.width = (rect.width - 130) / 2f;
rect.x += 130;
EditorGUI.PropertyField(rect, horizontalMapping_prop, GUIContent.none);
rect.x += rect.width + 5f;
rect.width -= 5;
EditorGUI.PropertyField(rect, verticalMapping_prop, GUIContent.none);
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// UV OPTIONS
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("UV Offset");
EditorGUILayout.PropertyField(uvOffset_prop, GUIContent.none, GUILayout.MinWidth(70f));
EditorGUIUtility.labelWidth = 30;
EditorGUILayout.PropertyField(uvLineOffset_prop, new GUIContent("Line"), GUILayout.MinWidth(70f));
EditorGUIUtility.labelWidth = labelWidth;
EditorGUILayout.EndHorizontal();
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
}
// KERNING
EditorGUI.BeginChangeCheck();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(enableKerning_prop, new GUIContent("Enable Kerning?"));
if (EditorGUI.EndChangeCheck())
{
//isAffectingWordWrapping_prop.boolValue = true;
havePropertiesChanged = true;
}
// EXTRA PADDING
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(enableExtraPadding_prop, new GUIContent("Extra Padding?"));
if (EditorGUI.EndChangeCheck())
{
havePropertiesChanged = true;
checkPaddingRequired_prop.boolValue = true;
}
EditorGUILayout.EndHorizontal();
}
if (GUILayout.Button("<b>EXTRA SETTINGS</b>" + (m_foldout.extraSettings ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
m_foldout.extraSettings = !m_foldout.extraSettings;
if (m_foldout.extraSettings)
{
EditorGUI.indentLevel = 0;
EditorGUI.BeginChangeCheck();
DrawMaginProperty(margin_prop, "Margins");
DrawMaginProperty(maskOffset_prop, "Mask Offset");
//EditorGUILayout.BeginHorizontal();
//EditorGUILayout.PropertyField(sortingLayerID_prop);
//EditorGUILayout.PropertyField(sortingOrder_prop);
//EditorGUILayout.EndHorizontal();
//EditorGUILayout.PropertyField(isOrthographic_prop, new GUIContent("Orthographic Mode?"));
EditorGUILayout.PropertyField(isRichText_prop, new GUIContent("Enable Rich Text?"));
//EditorGUILayout.PropertyField(textRectangle_prop, true);
if (EditorGUI.EndChangeCheck())
havePropertiesChanged = true;
// EditorGUI.BeginChangeCheck();
//EditorGUILayout.PropertyField(mask_prop);
//EditorGUILayout.PropertyField(maskOffset_prop, true);
//EditorGUILayout.PropertyField(maskSoftness_prop);
//if (EditorGUI.EndChangeCheck())
//{
// isMaskUpdateRequired_prop.boolValue = true;
// havePropertiesChanged = true;
//}
//EditorGUILayout.PropertyField(sortingLayerID_prop);
//EditorGUILayout.PropertyField(sortingOrder_prop);
// Mask Selection
}
EditorGUILayout.Space();
// If a Custom Material Editor exists, we use it.
if (m_uiRenderer != null && m_uiRenderer.GetMaterial() != null)
{
Material mat = m_uiRenderer.GetMaterial();
//Debug.Log(mat + " " + m_targetMaterial);
if (mat != m_targetMaterial)
{
// Destroy previous Material Instance
//Debug.Log("New Material has been assigned.");
m_targetMaterial = mat;
DestroyImmediate(m_materialEditor);
}
if (m_materialEditor == null)
{
m_materialEditor = Editor.CreateEditor(mat);
}
m_materialEditor.DrawHeader();
m_materialEditor.OnInspectorGUI();
}
if (havePropertiesChanged)
{
//Debug.Log("Properties have changed.");
havePropertiesChanged_prop.boolValue = true;
havePropertiesChanged = false;
EditorUtility.SetDirty(target);
}
serializedObject.ApplyModifiedProperties();
//m_targetMaterial = m_uiRenderer.GetMaterial();
}
private void DragAndDropGUI()
{
Event evt = Event.current;
Rect dropArea = new Rect(m_inspectorStartRegion.x, m_inspectorStartRegion.y, m_inspectorEndRegion.width, m_inspectorEndRegion.y - m_inspectorStartRegion.y);
switch (evt.type)
{
case EventType.dragUpdated:
case EventType.DragPerform:
if (!dropArea.Contains(evt.mousePosition))
break;
DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
if (evt.type == EventType.DragPerform)
{
DragAndDrop.AcceptDrag();
// Do something
Material mat = DragAndDrop.objectReferences[0] as Material;
//Debug.Log("Drag-n-Drop Material is " + mat + ". Target Material is " + m_targetMaterial + ". Canvas Material is " + m_uiRenderer.GetMaterial() );
// Check to make sure we have a valid material and that the font atlases match.
if (!mat || mat == m_uiRenderer.GetMaterial() || mat.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() != m_textMeshProScript.font.atlas.GetInstanceID())
{
if (mat && mat.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() != m_textMeshProScript.font.atlas.GetInstanceID())
Debug.LogWarning("Drag-n-Drop Material [" + mat.name + "]'s Atlas does not match the assigned Font Asset [" + m_textMeshProScript.font.name + "]'s Atlas.", this);
break;
}
fontSharedMaterial_prop.objectReferenceValue = mat;
//fontBaseMaterial_prop.objectReferenceValue = mat;
isNewBaseMaterial_prop.boolValue = true;
//TMPro_EventManager.ON_DRAG_AND_DROP_MATERIAL_CHANGED(m_textMeshProScript, mat);
EditorUtility.SetDirty(target);
//havePropertiesChanged = true;
}
evt.Use();
break;
}
}
// DRAW MARGIN PROPERTY
private void DrawMaginProperty(SerializedProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 2 * 18);
Rect pos0 = new Rect(rect.x, rect.y + 2, rect.width, 18);
float width = rect.width + 3;
pos0.width = old_LabelWidth;
GUI.Label(pos0, label);
Vector4 vec = property.vector4Value;
float widthB = width - old_LabelWidth;
float fieldWidth = widthB / 4;
pos0.width = fieldWidth - 5;
// Labels
pos0.x = old_LabelWidth + 15;
GUI.Label(pos0, "Left");
pos0.x += fieldWidth;
GUI.Label(pos0, "Top");
pos0.x += fieldWidth;
GUI.Label(pos0, "Right");
pos0.x += fieldWidth;
GUI.Label(pos0, "Bottom");
pos0.y += 18;
pos0.x = old_LabelWidth + 15;
vec.x = EditorGUI.FloatField(pos0, GUIContent.none, vec.x);
pos0.x += fieldWidth;
vec.y = EditorGUI.FloatField(pos0, GUIContent.none, vec.y);
pos0.x += fieldWidth;
vec.z = EditorGUI.FloatField(pos0, GUIContent.none, vec.z);
pos0.x += fieldWidth;
vec.w = EditorGUI.FloatField(pos0, GUIContent.none, vec.w);
property.vector4Value = vec;
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
public void OnSceneGUI()
{
if (IsMixSelectionTypes()) return;
// Margin Frame & Handles
m_rectTransform.GetWorldCorners(m_rectCorners);
Vector4 marginOffset = m_textMeshProScript.margin;
Vector3 lossyScale = m_rectTransform.lossyScale;
handlePoints[0] = m_rectCorners[0] + m_rectTransform.TransformDirection(new Vector3(marginOffset.x * lossyScale.x, marginOffset.w * lossyScale.y, 0));
handlePoints[1] = m_rectCorners[1] + m_rectTransform.TransformDirection(new Vector3(marginOffset.x * lossyScale.x, -marginOffset.y * lossyScale.y, 0));
handlePoints[2] = m_rectCorners[2] + m_rectTransform.TransformDirection(new Vector3(-marginOffset.z * lossyScale.x, -marginOffset.y * lossyScale.y, 0));
handlePoints[3] = m_rectCorners[3] + m_rectTransform.TransformDirection(new Vector3(-marginOffset.z * lossyScale.x, marginOffset.w * lossyScale.y, 0));
Handles.DrawSolidRectangleWithOutline(handlePoints, new Color32(255, 255, 255, 0), new Color32(255, 255, 0, 255));
// Draw & process FreeMoveHandles
// LEFT HANDLE
Vector3 old_left = (handlePoints[0] + handlePoints[1]) * 0.5f;
Vector3 new_left = Handles.FreeMoveHandle(old_left, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, Handles.DotCap);
bool hasChanged = false;
if (old_left != new_left)
{
float delta = old_left.x - new_left.x;
marginOffset.x += -delta / lossyScale.x;
//Debug.Log("Left Margin H0:" + handlePoints[0] + " H1:" + handlePoints[1]);
hasChanged = true;
}
// TOP HANDLE
Vector3 old_top = (handlePoints[1] + handlePoints[2]) * 0.5f;
Vector3 new_top = Handles.FreeMoveHandle(old_top, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_top != new_top)
{
float delta = old_top.y - new_top.y;
marginOffset.y += delta / lossyScale.y;
//Debug.Log("Top Margin H1:" + handlePoints[1] + " H2:" + handlePoints[2]);
hasChanged = true;
}
// RIGHT HANDLE
Vector3 old_right = (handlePoints[2] + handlePoints[3]) * 0.5f;
Vector3 new_right = Handles.FreeMoveHandle(old_right, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_right != new_right)
{
float delta = old_right.x - new_right.x;
marginOffset.z += delta / lossyScale.x;
hasChanged = true;
//Debug.Log("Right Margin H2:" + handlePoints[2] + " H3:" + handlePoints[3]);
}
// BOTTOM HANDLE
Vector3 old_bottom = (handlePoints[3] + handlePoints[0]) * 0.5f;
Vector3 new_bottom = Handles.FreeMoveHandle(old_bottom, Quaternion.identity, HandleUtility.GetHandleSize(m_rectTransform.position) * 0.05f, Vector3.zero, Handles.DotCap);
if (old_bottom != new_bottom)
{
float delta = old_bottom.y - new_bottom.y;
marginOffset.w += -delta / lossyScale.y;
hasChanged = true;
//Debug.Log("Bottom Margin H0:" + handlePoints[0] + " H3:" + handlePoints[3]);
}
if (hasChanged)
{
Undo.RecordObjects(new Object[] {m_rectTransform, m_textMeshProScript }, "Margin Changes");
m_textMeshProScript.margin = marginOffset;
EditorUtility.SetDirty(target);
}
}
void DrawPropertySlider(string label, SerializedProperty property)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 17);
//EditorGUIUtility.labelWidth = m_labelWidth;
GUIContent content = label == "" ? GUIContent.none : new GUIContent(label);
EditorGUI.Slider(new Rect(rect.x, rect.y, rect.width, rect.height), property, 0.0f, 1.0f, content);
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
private void DrawDimensionProperty(SerializedProperty property, string label)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 18);
Rect pos0 = new Rect(rect.x, rect.y + 2, rect.width, 18);
float width = rect.width + 3;
pos0.width = old_LabelWidth;
GUI.Label(pos0, label);
Rect rectangle = property.rectValue;
float width_B = width - old_LabelWidth;
float fieldWidth = width_B / 4;
pos0.width = fieldWidth - 5;
pos0.x = old_LabelWidth + 15;
GUI.Label(pos0, "Width");
pos0.x += fieldWidth;
rectangle.width = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.width);
pos0.x += fieldWidth;
GUI.Label(pos0, "Height");
pos0.x += fieldWidth;
rectangle.height = EditorGUI.FloatField(pos0, GUIContent.none, rectangle.height);
property.rectValue = rectangle;
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
void DrawPropertyBlock(string[] labels, SerializedProperty[] properties)
{
float old_LabelWidth = EditorGUIUtility.labelWidth;
float old_FieldWidth = EditorGUIUtility.fieldWidth;
Rect rect = EditorGUILayout.GetControlRect(false, 17);
GUI.Label(new Rect(rect.x, rect.y, old_LabelWidth, rect.height), labels[0]);
rect.x = old_LabelWidth + 15;
rect.width = (rect.width + 20 - rect.x) / labels.Length;
for (int i = 0; i < labels.Length; i++)
{
if (i == 0)
{
EditorGUIUtility.labelWidth = 20;
EditorGUI.PropertyField(new Rect(rect.x - 20, rect.y, 75, rect.height), properties[i], new GUIContent(" "));
rect.x += rect.width;
}
else
{
EditorGUIUtility.labelWidth = GUI.skin.textArea.CalcSize(new GUIContent(labels[i])).x;
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width - 5, rect.height), properties[i], new GUIContent(labels[i]));
rect.x += rect.width;
}
}
EditorGUIUtility.labelWidth = old_LabelWidth;
EditorGUIUtility.fieldWidth = old_FieldWidth;
}
// Method to handle multi object selection
private bool IsMixSelectionTypes()
{
Object[] objects = Selection.gameObjects;
if (objects.Length > 1)
{
//m_isMultiSelection = true;
for (int i = 0; i < objects.Length; i++)
{
if (((GameObject)objects[i]).GetComponent<TextMeshProUGUI>() == null)
return true;
}
}
return false;
}
// Special Handling of Undo / Redo Events.
private void OnUndoRedo()
{
//int undoEventID = Undo.GetCurrentGroup();
//int LastUndoEventID = m_eventID;
//Debug.Log(m_textMeshProScript.fontMaterial);
/*
if (undoEventID != LastUndoEventID)
{
for (int i = 0; i < targets.Length; i++)
{
//Debug.Log("Undo & Redo Performed detected in Editor Panel. Event ID:" + Undo.GetCurrentGroup());
TMPro_EventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, targets[i] as TextMeshPro);
m_eventID = undoEventID;
}
}
*/
}
/*
private UndoPropertyModification[] OnUndoRedoEvent(UndoPropertyModification[] modifications)
{
int eventID = Undo.GetCurrentGroup();
PropertyModification modifiedProp = modifications[0].propertyModification;
System.Type targetType = modifiedProp.target.GetType();
if (targetType == typeof(Material))
{
//Debug.Log("Undo / Redo Event Registered in Editor Panel on Target: " + targetObject);
//TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, targetObject as Material);
//EditorUtility.SetDirty(targetObject);
}
//string propertyPath = modifications[0].propertyModification.propertyPath;
//if (propertyPath == "m_fontAsset")
//{
//int currentEvent = Undo.GetCurrentGroup();
//Undo.RecordObject(Selection.activeGameObject.renderer.sharedMaterial, "Font Asset Changed");
//Undo.CollapseUndoOperations(currentEvent);
//Debug.Log("Undo / Redo Event: Font Asset changed. Event ID:" + Undo.GetCurrentGroup());
//}
//Debug.Log("Undo / Redo Event Registered in Editor Panel on Target: " + modifiedProp.propertyPath + " Undo Event ID:" + eventID + " Stored ID:" + TMPro_EditorUtility.UndoEventID);
//TextMeshPro_EventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, target as TextMeshPro);
return modifications;
}
*/
}
}
#endif
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#endregion
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace Picodex.Render.Unity
{
/// <summary>
/// 4-component Vector of the Half type. Occupies 8 Byte total.
/// </summary>
[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Vector4h : ISerializable, IEquatable<Vector4h>
{
#region Public Fields
/// <summary>The X component of the Half4.</summary>
public Half X;
/// <summary>The Y component of the Half4.</summary>
public Half Y;
/// <summary>The Z component of the Half4.</summary>
public Half Z;
/// <summary>The W component of the Half4.</summary>
public Half W;
#endregion Public Fields
#region Constructors
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector4h(Half value)
{
X = value;
Y = value;
Z = value;
W = value;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="value">The value that will initialize this instance.</param>
public Vector4h(Single value)
{
X = new Half(value);
Y = new Half(value);
Z = new Half(value);
W = new Half(value);
}
/// <summary>
/// The new Half4 instance will avoid conversion and copy directly from the Half parameters.
/// </summary>
/// <param name="x">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="y">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="z">An Half instance of a 16-bit half-precision floating-point number.</param>
/// <param name="w">An Half instance of a 16-bit half-precision floating-point number.</param>
public Vector4h(Half x, Half y, Half z, Half w)
{
this.X = x;
this.Y = y;
this.Z = z;
this.W = w;
}
/// <summary>
/// The new Half4 instance will convert the 4 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
/// <param name="z">32-bit single-precision floating-point number.</param>
/// <param name="w">32-bit single-precision floating-point number.</param>
public Vector4h(Single x, Single y, Single z, Single w)
{
X = new Half(x);
Y = new Half(y);
Z = new Half(z);
W = new Half(w);
}
/// <summary>
/// The new Half4 instance will convert the 4 parameters into 16-bit half-precision floating-point.
/// </summary>
/// <param name="x">32-bit single-precision floating-point number.</param>
/// <param name="y">32-bit single-precision floating-point number.</param>
/// <param name="z">32-bit single-precision floating-point number.</param>
/// <param name="w">32-bit single-precision floating-point number.</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
public Vector4h(Single x, Single y, Single z, Single w, bool throwOnError)
{
X = new Half(x, throwOnError);
Y = new Half(y, throwOnError);
Z = new Half(z, throwOnError);
W = new Half(w, throwOnError);
}
/// <summary>
/// The new Half4 instance will convert the Vector4 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector4</param>
[CLSCompliant(false)]
public Vector4h(Vector4 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
W = new Half(v.W);
}
/// <summary>
/// The new Half4 instance will convert the Vector4 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector4</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector4h(Vector4 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
W = new Half(v.W, throwOnError);
}
/// <summary>
/// The new Half4 instance will convert the Vector4 into 16-bit half-precision floating-point.
/// This is the fastest constructor.
/// </summary>
/// <param name="v">OpenTK.Vector4</param>
public Vector4h(ref Vector4 v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
W = new Half(v.W);
}
/// <summary>
/// The new Half4 instance will convert the Vector4 into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector4</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
public Vector4h(ref Vector4 v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
W = new Half(v.W, throwOnError);
}
/// <summary>
/// The new Half4 instance will convert the Vector4d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector4d</param>
[CLSCompliant(false)]
public Vector4h(Vector4d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
W = new Half(v.W);
}
/// <summary>
/// The new Half4 instance will convert the Vector4d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector4d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector4h(Vector4d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
W = new Half(v.W, throwOnError);
}
/// <summary>
/// The new Half4 instance will convert the Vector4d into 16-bit half-precision floating-point.
/// This is the faster constructor.
/// </summary>
/// <param name="v">OpenTK.Vector4d</param>
[CLSCompliant(false)]
public Vector4h(ref Vector4d v)
{
X = new Half(v.X);
Y = new Half(v.Y);
Z = new Half(v.Z);
W = new Half(v.W);
}
/// <summary>
/// The new Half4 instance will convert the Vector4d into 16-bit half-precision floating-point.
/// </summary>
/// <param name="v">OpenTK.Vector4d</param>
/// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param>
[CLSCompliant(false)]
public Vector4h(ref Vector4d v, bool throwOnError)
{
X = new Half(v.X, throwOnError);
Y = new Half(v.Y, throwOnError);
Z = new Half(v.Z, throwOnError);
W = new Half(v.W, throwOnError);
}
#endregion Constructors
#region Swizzle
#region 2-component
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the X and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Xy { get { return new Vector2h(X, Y); } set { X = value.X; Y = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the X and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Xz { get { return new Vector2h(X, Z); } set { X = value.X; Z = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the X and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Xw { get { return new Vector2h(X, W); } set { X = value.X; W = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Y and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Yx { get { return new Vector2h(Y, X); } set { Y = value.X; X = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Y and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Yz { get { return new Vector2h(Y, Z); } set { Y = value.X; Z = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Y and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Yw { get { return new Vector2h(Y, W); } set { Y = value.X; W = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Z and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Zx { get { return new Vector2h(Z, X); } set { Z = value.X; X = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the Z and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Zy { get { return new Vector2h(Z, Y); } set { Z = value.X; Y = value.Y; } }
/// <summary>
/// Gets an OpenTK.Vector2h with the Z and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Zw { get { return new Vector2h(Z, W); } set { Z = value.X; W = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the W and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Wx { get { return new Vector2h(W, X); } set { W = value.X; X = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the W and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Wy { get { return new Vector2h(W, Y); } set { W = value.X; Y = value.Y; } }
/// <summary>
/// Gets or sets an OpenTK.Vector2h with the W and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector2h Wz { get { return new Vector2h(W, Z); } set { W = value.X; Z = value.Y; } }
#endregion
#region 3-component
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the X, Y, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Xyz { get { return new Vector3h(X, Y, Z); } set { X = value.X; Y = value.Y; Z = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the X, Y, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Xyw { get { return new Vector3h(X, Y, W); } set { X = value.X; Y = value.Y; W = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the X, Z, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Xzy { get { return new Vector3h(X, Z, Y); } set { X = value.X; Z = value.Y; Y = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the X, Z, and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Xzw { get { return new Vector3h(X, Z, W); } set { X = value.X; Z = value.Y; W = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the X, W, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Xwy { get { return new Vector3h(X, W, Y); } set { X = value.X; W = value.Y; Y = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the X, W, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Xwz { get { return new Vector3h(X, W, Z); } set { X = value.X; W = value.Y; Z = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Y, X, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Yxz { get { return new Vector3h(Y, X, Z); } set { Y = value.X; X = value.Y; Z = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Y, X, and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Yxw { get { return new Vector3h(Y, X, W); } set { Y = value.X; X = value.Y; W = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Y, Z, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Yzx { get { return new Vector3h(Y, Z, X); } set { Y = value.X; Z = value.Y; X = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Y, Z, and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Yzw { get { return new Vector3h(Y, Z, W); } set { Y = value.X; Z = value.Y; W = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Y, W, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Ywx { get { return new Vector3h(Y, W, X); } set { Y = value.X; W = value.Y; X = value.Z; } }
/// <summary>
/// Gets an OpenTK.Vector3h with the Y, W, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Ywz { get { return new Vector3h(Y, W, Z); } set { Y = value.X; W = value.Y; Z = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, X, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zxy { get { return new Vector3h(Z, X, Y); } set { Z = value.X; X = value.Y; Y = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, X, and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zxw { get { return new Vector3h(Z, X, W); } set { Z = value.X; X = value.Y; W = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, Y, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zyx { get { return new Vector3h(Z, Y, X); } set { Z = value.X; Y = value.Y; X = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, Y, and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zyw { get { return new Vector3h(Z, Y, W); } set { Z = value.X; Y = value.Y; W = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, W, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zwx { get { return new Vector3h(Z, W, X); } set { Z = value.X; W = value.Y; X = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the Z, W, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Zwy { get { return new Vector3h(Z, W, Y); } set { Z = value.X; W = value.Y; Y = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the W, X, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Wxy { get { return new Vector3h(W, X, Y); } set { W = value.X; X = value.Y; Y = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the W, X, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Wxz { get { return new Vector3h(W, X, Z); } set { W = value.X; X = value.Y; Z = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the W, Y, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Wyx { get { return new Vector3h(W, Y, X); } set { W = value.X; Y = value.Y; X = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the W, Y, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Wyz { get { return new Vector3h(W, Y, Z); } set { W = value.X; Y = value.Y; Z = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the W, Z, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Wzx { get { return new Vector3h(W, Z, X); } set { W = value.X; Z = value.Y; X = value.Z; } }
/// <summary>
/// Gets or sets an OpenTK.Vector3h with the W, Z, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector3h Wzy { get { return new Vector3h(W, Z, Y); } set { W = value.X; Z = value.Y; Y = value.Z; } }
#endregion
#region 4-component
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the X, Y, W, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Xywz { get { return new Vector4h(X, Y, W, Z); } set { X = value.X; Y = value.Y; W = value.Z; Z = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the X, Z, Y, and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Xzyw { get { return new Vector4h(X, Z, Y, W); } set { X = value.X; Z = value.Y; Y = value.Z; W = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the X, Z, W, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Xzwy { get { return new Vector4h(X, Z, W, Y); } set { X = value.X; Z = value.Y; W = value.Z; Y = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the X, W, Y, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Xwyz { get { return new Vector4h(X, W, Y, Z); } set { X = value.X; W = value.Y; Y = value.Z; Z = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the X, W, Z, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Xwzy { get { return new Vector4h(X, W, Z, Y); } set { X = value.X; W = value.Y; Z = value.Z; Y = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Y, X, Z, and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Yxzw { get { return new Vector4h(Y, X, Z, W); } set { Y = value.X; X = value.Y; Z = value.Z; W = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Y, X, W, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Yxwz { get { return new Vector4h(Y, X, W, Z); } set { Y = value.X; X = value.Y; W = value.Z; Z = value.W; } }
/// <summary>
/// Gets an OpenTK.Vector4h with the Y, Y, Z, and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Yyzw { get { return new Vector4h(Y, Y, Z, W); } set { X = value.X; Y = value.Y; Z = value.Z; W = value.W; } }
/// <summary>
/// Gets an OpenTK.Vector4h with the Y, Y, W, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Yywz { get { return new Vector4h(Y, Y, W, Z); } set { X = value.X; Y = value.Y; W = value.Z; Z = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Y, Z, X, and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Yzxw { get { return new Vector4h(Y, Z, X, W); } set { Y = value.X; Z = value.Y; X = value.Z; W = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Y, Z, W, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Yzwx { get { return new Vector4h(Y, Z, W, X); } set { Y = value.X; Z = value.Y; W = value.Z; X = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Y, W, X, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Ywxz { get { return new Vector4h(Y, W, X, Z); } set { Y = value.X; W = value.Y; X = value.Z; Z = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Y, W, Z, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Ywzx { get { return new Vector4h(Y, W, Z, X); } set { Y = value.X; W = value.Y; Z = value.Z; X = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Z, X, Y, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Zxyw { get { return new Vector4h(Z, X, Y, W); } set { Z = value.X; X = value.Y; Y = value.Z; W = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Z, X, W, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Zxwy { get { return new Vector4h(Z, X, W, Y); } set { Z = value.X; X = value.Y; W = value.Z; Y = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Z, Y, X, and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Zyxw { get { return new Vector4h(Z, Y, X, W); } set { Z = value.X; Y = value.Y; X = value.Z; W = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Z, Y, W, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Zywx { get { return new Vector4h(Z, Y, W, X); } set { Z = value.X; Y = value.Y; W = value.Z; X = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Z, W, X, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Zwxy { get { return new Vector4h(Z, W, X, Y); } set { Z = value.X; W = value.Y; X = value.Z; Y = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the Z, W, Y, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Zwyx { get { return new Vector4h(Z, W, Y, X); } set { Z = value.X; W = value.Y; Y = value.Z; X = value.W; } }
/// <summary>
/// Gets an OpenTK.Vector4h with the Z, W, Z, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Zwzy { get { return new Vector4h(Z, W, Z, Y); } set { X = value.X; W = value.Y; Z = value.Z; Y = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the W, X, Y, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Wxyz { get { return new Vector4h(W, X, Y, Z); } set { W = value.X; X = value.Y; Y = value.Z; Z = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the W, X, Z, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Wxzy { get { return new Vector4h(W, X, Z, Y); } set { W = value.X; X = value.Y; Z = value.Z; Y = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the W, Y, X, and Z components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Wyxz { get { return new Vector4h(W, Y, X, Z); } set { W = value.X; Y = value.Y; X = value.Z; Z = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the W, Y, Z, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Wyzx { get { return new Vector4h(W, Y, Z, X); } set { W = value.X; Y = value.Y; Z = value.Z; X = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the W, Z, X, and Y components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Wzxy { get { return new Vector4h(W, Z, X, Y); } set { W = value.X; Z = value.Y; X = value.Z; Y = value.W; } }
/// <summary>
/// Gets or sets an OpenTK.Vector4h with the W, Z, Y, and X components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Wzyx { get { return new Vector4h(W, Z, Y, X); } set { W = value.X; Z = value.Y; Y = value.Z; X = value.W; } }
/// <summary>
/// Gets an OpenTK.Vector4h with the W, Z, Y, and W components of this instance.
/// </summary>
[XmlIgnore]
public Vector4h Wzyw { get { return new Vector4h(W, Z, Y, W); } set { X = value.X; Z = value.Y; Y = value.Z; W = value.W; } }
#endregion
#endregion
#region Half -> Single
/// <summary>
/// Returns this Half4 instance's contents as Vector4.
/// </summary>
/// <returns>OpenTK.Vector4</returns>
public Vector4 ToVector4()
{
return new Vector4(X, Y, Z, W);
}
/// <summary>
/// Returns this Half4 instance's contents as Vector4d.
/// </summary>
public Vector4d ToVector4d()
{
return new Vector4d(X, Y, Z, W);
}
#endregion Half -> Single
#region Conversions
/// <summary>Converts OpenTK.Vector4 to OpenTK.Half4.</summary>
/// <param name="v4f">The Vector4 to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector4h(Vector4 v4f)
{
return new Vector4h(v4f);
}
/// <summary>Converts OpenTK.Vector4d to OpenTK.Half4.</summary>
/// <param name="v4d">The Vector4d to convert.</param>
/// <returns>The resulting Half vector.</returns>
public static explicit operator Vector4h(Vector4d v4d)
{
return new Vector4h(v4d);
}
/// <summary>Converts OpenTK.Half4 to OpenTK.Vector4.</summary>
/// <param name="h4">The Half4 to convert.</param>
/// <returns>The resulting Vector4.</returns>
public static explicit operator Vector4(Vector4h h4)
{
Vector4 result = new Vector4();
result.X = h4.X.ToSingle();
result.Y = h4.Y.ToSingle();
result.Z = h4.Z.ToSingle();
result.W = h4.W.ToSingle();
return result;
}
/// <summary>Converts OpenTK.Half4 to OpenTK.Vector4d.</summary>
/// <param name="h4">The Half4 to convert.</param>
/// <returns>The resulting Vector4d.</returns>
public static explicit operator Vector4d(Vector4h h4)
{
Vector4d result = new Vector4d();
result.X = h4.X.ToSingle();
result.Y = h4.Y.ToSingle();
result.Z = h4.Z.ToSingle();
result.W = h4.W.ToSingle();
return result;
}
#endregion Conversions
#region Constants
/// <summary>The size in bytes for an instance of the Half4 struct is 8.</summary>
public static readonly int SizeInBytes = 8;
#endregion Constants
#region ISerializable
/// <summary>Constructor used by ISerializable to deserialize the object.</summary>
/// <param name="info"></param>
/// <param name="context"></param>
public Vector4h(SerializationInfo info, StreamingContext context)
{
this.X = (Half)info.GetValue("X", typeof(Half));
this.Y = (Half)info.GetValue("Y", typeof(Half));
this.Z = (Half)info.GetValue("Z", typeof(Half));
this.W = (Half)info.GetValue("W", typeof(Half));
}
/// <summary>Used by ISerialize to serialize the object.</summary>
/// <param name="info"></param>
/// <param name="context"></param>
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("X", this.X);
info.AddValue("Y", this.Y);
info.AddValue("Z", this.Z);
info.AddValue("W", this.W);
}
#endregion ISerializable
#region Binary dump
/// <summary>Updates the X,Y,Z and W components of this instance by reading from a Stream.</summary>
/// <param name="bin">A BinaryReader instance associated with an open Stream.</param>
public void FromBinaryStream(BinaryReader bin)
{
X.FromBinaryStream(bin);
Y.FromBinaryStream(bin);
Z.FromBinaryStream(bin);
W.FromBinaryStream(bin);
}
/// <summary>Writes the X,Y,Z and W components of this instance into a Stream.</summary>
/// <param name="bin">A BinaryWriter instance associated with an open Stream.</param>
public void ToBinaryStream(BinaryWriter bin)
{
X.ToBinaryStream(bin);
Y.ToBinaryStream(bin);
Z.ToBinaryStream(bin);
W.ToBinaryStream(bin);
}
#endregion Binary dump
#region IEquatable<Half4> Members
/// <summary>Returns a value indicating whether this instance is equal to a specified OpenTK.Half4 vector.</summary>
/// <param name="other">OpenTK.Half4 to compare to this instance..</param>
/// <returns>True, if other is equal to this instance; false otherwise.</returns>
public bool Equals(Vector4h other)
{
return (this.X.Equals(other.X) && this.Y.Equals(other.Y) && this.Z.Equals(other.Z) && this.W.Equals(other.W));
}
#endregion
#region ToString()
private static string listSeparator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
/// <summary>Returns a string that contains this Half4's numbers in human-legible form.</summary>
public override string ToString()
{
return String.Format("({0}{4} {1}{4} {2}{4} {3})", X.ToString(), Y.ToString(), Z.ToString(), W.ToString(), listSeparator);
}
#endregion ToString()
#region BitConverter
/// <summary>Returns the Half4 as an array of bytes.</summary>
/// <param name="h">The Half4 to convert.</param>
/// <returns>The input as byte array.</returns>
public static byte[] GetBytes(Vector4h h)
{
byte[] result = new byte[SizeInBytes];
byte[] temp = Half.GetBytes(h.X);
result[0] = temp[0];
result[1] = temp[1];
temp = Half.GetBytes(h.Y);
result[2] = temp[0];
result[3] = temp[1];
temp = Half.GetBytes(h.Z);
result[4] = temp[0];
result[5] = temp[1];
temp = Half.GetBytes(h.W);
result[6] = temp[0];
result[7] = temp[1];
return result;
}
/// <summary>Converts an array of bytes into Half4.</summary>
/// <param name="value">A Half4 in it's byte[] representation.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A new Half4 instance.</returns>
public static Vector4h FromBytes(byte[] value, int startIndex)
{
Vector4h h4 = new Vector4h();
h4.X = Half.FromBytes(value, startIndex);
h4.Y = Half.FromBytes(value, startIndex + 2);
h4.Z = Half.FromBytes(value, startIndex + 4);
h4.W = Half.FromBytes(value, startIndex + 6);
return h4;
}
#endregion BitConverter
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Collections.Generic;
using System.Reflection;
namespace System.Abstract
{
/// <summary>
/// IServiceCacheRegistration
/// </summary>
public interface IServiceCacheRegistration
{
/// <summary>
/// Gets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
string Name { get; }
/// <summary>
/// Gets the name of the absolute.
/// </summary>
/// <value>
/// The name of the absolute.
/// </value>
string AbsoluteName { get; }
/// <summary>
/// Gets the use headers.
/// </summary>
/// <value>
/// The use headers.
/// </value>
bool UseHeaders { get; }
/// <summary>
/// Gets the registrar.
/// </summary>
/// <value>
/// The registrar.
/// </value>
ServiceCacheRegistrar Registrar { get; }
/// <summary>
/// Attaches the registrar.
/// </summary>
/// <param name="registrar">The registrar.</param>
/// <param name="absoluteName">Name of the absolute.</param>
void AttachRegistrar(ServiceCacheRegistrar registrar, string absoluteName);
}
/// <summary>
/// ServiceCacheRegistration
/// </summary>
public class ServiceCacheRegistration : IServiceCacheRegistration
{
private Dictionary<Type, List<HandlerAction>> _handlers = new Dictionary<Type, List<HandlerAction>>();
internal struct HandlerAction
{
public Type TType;
public MethodInfo Method;
public object Target;
public HandlerAction(Type tType, MethodInfo method, object target)
{
TType = tType;
Method = method;
Target = target;
}
}
/// <summary>
/// HandlerContext
/// </summary>
public class HandlerContext<TData>
{
/// <summary>
/// Gets or sets the get.
/// </summary>
/// <value>
/// The get.
/// </value>
public Func<TData> Get { get; set; }
/// <summary>
/// Gets or sets the update.
/// </summary>
/// <value>
/// The update.
/// </value>
public Action<TData> Update { get; set; }
}
/// <summary>
/// ConsumerInfo
/// </summary>
public struct HandlerInfo
{
private static MethodInfo _consumerInvokeInternalInfo = typeof(HandlerInfo).GetMethod("ConsumerInvokeInternal", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
private static MethodInfo _queryInvokeInternalInfo = typeof(HandlerInfo).GetMethod("QueryInvokeInternal", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
internal HandlerAction Action { get; set; }
/// <summary>
/// Gets the message.
/// </summary>
/// <value>
/// The message.
/// </value>
internal object Message { get; set; }
/// <summary>
/// Consumers the invoke.
/// </summary>
/// <typeparam name="TData">The type of the data.</typeparam>
/// <param name="ctx">The CTX.</param>
/// <param name="message">The message.</param>
/// <param name="tag">The tag.</param>
/// <param name="values">The values.</param>
public void ConsumerInvoke<TData>(HandlerContext<TData> ctx, object message, object tag, object[] values) { Action.Method.Invoke(Action.Target, new object[] { ctx, message, tag, values }); }
/// <summary>
/// Consumers the invoke.
/// </summary>
/// <param name="handlerContextInfos">The handler context infos.</param>
/// <param name="cache">The cache.</param>
/// <param name="registration">The registration.</param>
/// <param name="tag">The tag.</param>
/// <param name="header">The header.</param>
public void ConsumerInvoke(MethodInfo[] handlerContextInfos, IServiceCache cache, IServiceCacheRegistration registration, object tag, CacheItemHeader header) { _consumerInvokeInternalInfo.MakeGenericMethod(Action.TType).Invoke(this, new[] { handlerContextInfos, cache, registration, tag, header }); }
private void ConsumerInvokeInternal<TData>(MethodInfo[] handlerContextInfos, IServiceCache cache, IServiceCacheRegistration registration, object tag, CacheItemHeader header)
{
var getInfo = handlerContextInfos[0].MakeGenericMethod(Action.TType);
var updateInfo = handlerContextInfos[1].MakeGenericMethod(Action.TType);
var ctx = new ServiceCacheRegistration.HandlerContext<TData>
{
Get = () => (TData)getInfo.Invoke(null, new[] { cache, registration, tag, header }),
Update = value => updateInfo.Invoke(null, new[] { cache, registration, tag, header, value }),
};
ConsumerInvoke<TData>(ctx, Message, tag, header.Values);
}
/// <summary>
/// Queries the invoke.
/// </summary>
/// <typeparam name="TData">The type of the data.</typeparam>
/// <param name="ctx">The CTX.</param>
/// <param name="message">The message.</param>
/// <param name="tag">The tag.</param>
/// <param name="values">The values.</param>
/// <returns></returns>
public object QueryInvoke<TData>(HandlerContext<TData> ctx, object message, object tag, object[] values) { return Action.Method.Invoke(Action.Target, new object[] { ctx, message, tag, values }); }
/// <summary>
/// Queries the invoke.
/// </summary>
/// <param name="handlerContextInfos">The handler context infos.</param>
/// <param name="cache">The cache.</param>
/// <param name="registration">The registration.</param>
/// <param name="tag">The tag.</param>
/// <param name="header">The header.</param>
/// <returns></returns>
public object QueryInvoke(MethodInfo[] handlerContextInfos, IServiceCache cache, IServiceCacheRegistration registration, object tag, CacheItemHeader header) { return _queryInvokeInternalInfo.MakeGenericMethod(Action.TType).Invoke(this, new[] { handlerContextInfos, cache, registration, tag, header }); }
private object QueryInvokeInternal<TData>(MethodInfo[] handlerContextInfos, IServiceCache cache, IServiceCacheRegistration registration, object tag, CacheItemHeader header)
{
var getInfo = handlerContextInfos[0].MakeGenericMethod(Action.TType);
var updateInfo = handlerContextInfos[1].MakeGenericMethod(Action.TType);
var ctx = new ServiceCacheRegistration.HandlerContext<TData>
{
Get = () => (TData)getInfo.Invoke(null, new[] { cache, registration, tag, header }),
Update = value => updateInfo.Invoke(null, new[] { cache, registration, tag, header, value }),
};
return QueryInvoke<TData>(ctx, Message, tag, header.Values);
}
}
/// <summary>
/// IDispatcher
/// </summary>
public interface IDispatcher
{
/// <summary>
/// Gets the specified cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cache">The cache.</param>
/// <param name="registration">The registration.</param>
/// <param name="tag">The tag.</param>
/// <param name="values">The values.</param>
/// <returns></returns>
T Get<T>(IServiceCache cache, IServiceCacheRegistration registration, object tag, object[] values);
/// <summary>
/// Sends the specified cache.
/// </summary>
/// <param name="cache">The cache.</param>
/// <param name="registration">The registration.</param>
/// <param name="tag">The tag.</param>
/// <param name="messages">The messages.</param>
void Send(IServiceCache cache, IServiceCacheRegistration registration, object tag, params object[] messages);
/// <summary>
/// Querys the specified cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cache">The cache.</param>
/// <param name="registration">The registration.</param>
/// <param name="tag">The tag.</param>
/// <param name="messages">The messages.</param>
/// <returns></returns>
IEnumerable<T> Query<T>(IServiceCache cache, IServiceCacheRegistration registration, object tag, params object[] messages);
/// <summary>
/// Removes the specified cache.
/// </summary>
/// <param name="cache">The cache.</param>
/// <param name="registration">The registration.</param>
void Remove(IServiceCache cache, IServiceCacheRegistration registration);
}
internal ServiceCacheRegistration(string name)
{
// used for registration-links only
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
Name = name;
ItemPolicy = new CacheItemPolicy(-1);
}
/// <summary>
/// Adds the data source.
/// </summary>
/// <param name="name">The key.</param>
/// <param name="builder">The builder.</param>
public ServiceCacheRegistration(string name, CacheItemBuilder builder)
: this(name, new CacheItemPolicy(), builder) { }
/// <summary>
/// Adds the data source.
/// </summary>
/// <param name="name">The key.</param>
/// <param name="builder">The builder.</param>
/// <param name="cacheTags">The dependency array.</param>
public ServiceCacheRegistration(string name, CacheItemBuilder builder, params string[] cacheTags)
: this(name, new CacheItemPolicy(), builder) { SetItemPolicyDependency(cacheTags); }
/// <summary>
/// Adds the data source.
/// </summary>
/// <param name="name">The key.</param>
/// <param name="builder">The builder.</param>
/// <param name="cacheTags">The dependency array.</param>
public ServiceCacheRegistration(string name, CacheItemBuilder builder, Func<object, object[], string[]> cacheTags)
: this(name, new CacheItemPolicy(), builder) { SetItemPolicyDependency(cacheTags); }
/// <summary>
/// Adds the data source.
/// </summary>
/// <param name="name">The key.</param>
/// <param name="builder">The builder.</param>
/// <param name="dependency">The dependency.</param>
public ServiceCacheRegistration(string name, CacheItemBuilder builder, CacheItemDependency dependency)
: this(name, new CacheItemPolicy(), builder) { SetItemPolicyDependency(dependency); }
/// <summary>
/// Adds the data source.
/// </summary>
/// <param name="name">The key.</param>
/// <param name="minuteTimeout">The minute timeout.</param>
/// <param name="builder">The builder.</param>
/// <param name="cacheTags">The dependency array.</param>
public ServiceCacheRegistration(string name, int minuteTimeout, CacheItemBuilder builder, params string[] cacheTags)
: this(name, new CacheItemPolicy(minuteTimeout), builder) { SetItemPolicyDependency(cacheTags); }
/// <summary>
/// Adds the data source.
/// </summary>
/// <param name="name">The key.</param>
/// <param name="minuteTimeout">The minute timeout.</param>
/// <param name="builder">The builder.</param>
/// <param name="cacheTags">The dependency array.</param>
public ServiceCacheRegistration(string name, int minuteTimeout, CacheItemBuilder builder, Func<object, object[], string[]> cacheTags)
: this(name, new CacheItemPolicy(minuteTimeout), builder) { SetItemPolicyDependency(cacheTags); }
/// <summary>
/// Adds the data source.
/// </summary>
/// <param name="name">The key.</param>
/// <param name="minuteTimeout">The minute timeout.</param>
/// <param name="builder">The builder.</param>
/// <param name="dependency">The dependency.</param>
public ServiceCacheRegistration(string name, int minuteTimeout, CacheItemBuilder builder, CacheItemDependency dependency)
: this(name, new CacheItemPolicy(minuteTimeout), builder) { SetItemPolicyDependency(dependency); }
/// <summary>
/// Adds the data source.
/// </summary>
/// <param name="name">The key.</param>
/// <param name="itemPolicy">The item policy.</param>
/// <param name="builder">The builder.</param>
public ServiceCacheRegistration(string name, CacheItemPolicy itemPolicy, CacheItemBuilder builder)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
if (itemPolicy == null)
throw new ArgumentNullException("itemPolicy");
if (builder == null)
throw new ArgumentNullException("builder");
Name = name;
Builder = builder;
ItemPolicy = itemPolicy;
Namespaces = new List<string>();
}
/// <summary>
/// Adds the data source.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The cache command.</param>
/// <param name="builder">The builder.</param>
/// <param name="cacheTags">The dependency array.</param>
public ServiceCacheRegistration(string name, CacheItemPolicy itemPolicy, CacheItemBuilder builder, params string[] cacheTags)
: this(name, itemPolicy, builder) { SetItemPolicyDependency(cacheTags); }
/// <summary>
/// Adds the data source.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The cache command.</param>
/// <param name="builder">The builder.</param>
/// <param name="cacheTags">The dependency array.</param>
public ServiceCacheRegistration(string name, CacheItemPolicy itemPolicy, CacheItemBuilder builder, Func<object, object[], string[]> cacheTags)
: this(name, itemPolicy, builder) { SetItemPolicyDependency(cacheTags); }
/// <summary>
/// Adds the data source.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The cache command.</param>
/// <param name="builder">The builder.</param>
/// <param name="dependency">The dependency.</param>
public ServiceCacheRegistration(string name, CacheItemPolicy itemPolicy, CacheItemBuilder builder, CacheItemDependency dependency)
: this(name, itemPolicy, builder) { SetItemPolicyDependency(dependency); }
/// <summary>
/// Gets or sets the key.
/// </summary>
/// <value>
/// The key.
/// </value>
public string Name { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [use headers].
/// </summary>
/// <value>
/// <c>true</c> if [use headers]; otherwise, <c>false</c>.
/// </value>
public bool UseHeaders { get; set; }
/// <summary>
/// Gets or sets the cache command.
/// </summary>
/// <value>
/// The cache command.
/// </value>
public CacheItemPolicy ItemPolicy { get; set; }
/// <summary>
/// Gets or sets the builder.
/// </summary>
/// <value>
/// The builder.
/// </value>
public CacheItemBuilder Builder { get; set; }
/// <summary>
/// AbsoluteName
/// </summary>
/// <value>
/// The name of the absolute.
/// </value>
public string AbsoluteName { get; private set; }
/// <summary>
/// Consumeses the specified action.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <param name="action">The action.</param>
/// <returns></returns>
public ServiceCacheRegistration Consume<TMessage>(Action<HandlerContext<object>, TMessage, object, object[]> action) { return Consume<TMessage, object>(action); }
/// <summary>
/// Consumeses the specified action.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <typeparam name="TData">The type of the data.</typeparam>
/// <param name="action">The action.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException"></exception>
public ServiceCacheRegistration Consume<TMessage, TData>(Action<HandlerContext<TData>, TMessage, object, object[]> action)
{
if (action == null)
throw new ArgumentNullException("action");
UseHeaders = true;
List<HandlerAction> consumerActions;
if (!_handlers.TryGetValue(typeof(TMessage), out consumerActions))
_handlers.Add(typeof(TMessage), consumerActions = new List<HandlerAction>());
consumerActions.Add(new HandlerAction(typeof(TData), action.Method, action.Target));
return this;
}
/// <summary>
/// Queries the specified action.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <param name="action">The action.</param>
/// <returns></returns>
public ServiceCacheRegistration Query<TMessage>(Func<HandlerContext<object>, TMessage, object, object[], object> action) { return Query<TMessage, object>(action); }
/// <summary>
/// Queries the specified action.
/// </summary>
/// <typeparam name="TMessage">The type of the message.</typeparam>
/// <typeparam name="TData">The type of the data.</typeparam>
/// <param name="action">The action.</param>
/// <returns></returns>
public ServiceCacheRegistration Query<TMessage, TData>(Func<HandlerContext<TData>, TMessage, object, object[], object> action)
{
if (action == null)
throw new ArgumentNullException("action");
UseHeaders = true;
List<HandlerAction> consumerActions;
if (!_handlers.TryGetValue(typeof(TMessage), out consumerActions))
_handlers.Add(typeof(TMessage), consumerActions = new List<HandlerAction>());
consumerActions.Add(new HandlerAction(typeof(TData), action.Method, action.Target));
return this;
}
/// <summary>
/// Gets the consumers for.
/// </summary>
/// <param name="messages">The messages.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException"></exception>
public IEnumerable<HandlerInfo> GetHandlersFor(object[] messages)
{
if (messages == null)
throw new ArgumentNullException("messages");
List<HandlerAction> handlerActions;
foreach (var message in messages)
if (_handlers.TryGetValue(message.GetType(), out handlerActions))
foreach (var handlerAction in handlerActions)
yield return new HandlerInfo { Message = message, Action = handlerAction };
}
#region Registrar
/// <summary>
/// Gets the registrar.
/// </summary>
/// <value>
/// The registrar.
/// </value>
public ServiceCacheRegistrar Registrar { get; internal set; }
/// <summary>
/// Gets the namespaces.
/// </summary>
/// <value>
/// The namespaces.
/// </value>
public IEnumerable<string> Namespaces { get; private set; }
/// <summary>
/// Gets the names.
/// </summary>
/// <value>
/// The names.
/// </value>
public IEnumerable<string> Keys
{
get
{
var name = AbsoluteName;
if (name != null)
yield return name;
if (Namespaces != null)
foreach (var n in Namespaces)
yield return n + name;
}
}
/// <summary>
/// Attaches the registrar.
/// </summary>
/// <param name="registrar">The registrar.</param>
/// <param name="absoluteName">Name of the absolute.</param>
public void AttachRegistrar(ServiceCacheRegistrar registrar, string absoluteName)
{
Registrar = registrar;
AbsoluteName = absoluteName;
}
#endregion
private void SetItemPolicyDependency(string[] cacheTags)
{
if (cacheTags != null && cacheTags.Length > 0)
{
if (ItemPolicy.Dependency != null)
throw new InvalidOperationException(Local.RedefineCacheDependency);
ItemPolicy.Dependency = (c, r, t, v) => cacheTags;
}
}
private void SetItemPolicyDependency(Func<object, object[], string[]> cacheTags)
{
if (cacheTags != null)
{
if (ItemPolicy.Dependency != null)
throw new InvalidOperationException(Local.RedefineCacheDependency);
ItemPolicy.Dependency = (c, r, t, v) => cacheTags(t, v);
}
}
private void SetItemPolicyDependency(CacheItemDependency dependency)
{
if (dependency != null)
{
if (ItemPolicy.Dependency != null)
throw new InvalidOperationException(Local.RedefineCacheDependency);
ItemPolicy.Dependency = dependency;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Threading;
namespace Internal.Runtime.Augments
{
public sealed partial class RuntimeThread
{
// Extra bits used in _threadState
private const ThreadState ThreadPoolThread = (ThreadState)0x1000;
// Bits of _threadState that are returned by the ThreadState property
private const ThreadState PublicThreadStateMask = (ThreadState)0x1FF;
[ThreadStatic]
private static RuntimeThread t_currentThread;
private ExecutionContext _executionContext;
private SynchronizationContext _synchronizationContext;
private volatile int _threadState;
private ThreadPriority _priority;
private ManagedThreadId _managedThreadId;
private string _name;
private Delegate _threadStart;
private object _threadStartArg;
private int _maxStackSize;
// Protects starting the thread and setting its priority
private Lock _lock;
/// <summary>
/// Used by <see cref="WaitHandle"/>'s multi-wait functions
/// </summary>
private WaitHandleArray<SafeWaitHandle> _waitedSafeWaitHandles;
private RuntimeThread()
{
_waitedSafeWaitHandles = new WaitHandleArray<SafeWaitHandle>(elementInitializer: null);
_threadState = (int)ThreadState.Unstarted;
_priority = ThreadPriority.Normal;
_lock = new Lock();
#if PLATFORM_UNIX
_waitInfo = new WaitSubsystem.ThreadWaitInfo(this);
#endif
PlatformSpecificInitialize();
}
// Constructor for threads created by the Thread class
private RuntimeThread(Delegate threadStart, int maxStackSize)
: this()
{
_threadStart = threadStart;
_maxStackSize = maxStackSize;
_managedThreadId = new ManagedThreadId();
}
public static RuntimeThread Create(ThreadStart start) => new RuntimeThread(start, 0);
public static RuntimeThread Create(ThreadStart start, int maxStackSize) => new RuntimeThread(start, maxStackSize);
public static RuntimeThread Create(ParameterizedThreadStart start) => new RuntimeThread(start, 0);
public static RuntimeThread Create(ParameterizedThreadStart start, int maxStackSize) => new RuntimeThread(start, maxStackSize);
public static RuntimeThread CurrentThread
{
get
{
return t_currentThread ?? InitializeExistingThread(false);
}
}
// Slow path executed once per thread
private static RuntimeThread InitializeExistingThread(bool threadPoolThread)
{
Debug.Assert(t_currentThread == null);
var currentThread = new RuntimeThread();
currentThread._managedThreadId = System.Threading.ManagedThreadId.GetCurrentThreadId();
Debug.Assert(currentThread._threadState == (int)ThreadState.Unstarted);
ThreadState state = threadPoolThread ? ThreadPoolThread : 0;
// The main thread is foreground, other ones are background
if (currentThread._managedThreadId.Id != System.Threading.ManagedThreadId.IdMainThread)
{
state |= ThreadState.Background;
}
currentThread._threadState = (int)(state | ThreadState.Running);
currentThread.PlatformSpecificInitializeExistingThread();
currentThread._priority = currentThread.GetPriorityLive();
t_currentThread = currentThread;
if (threadPoolThread)
{
RoInitialize();
}
return currentThread;
}
// Use ThreadPoolCallbackWrapper instead of calling this function directly
internal static RuntimeThread InitializeThreadPoolThread()
{
return t_currentThread ?? InitializeExistingThread(true);
}
/// <summary>
/// Resets properties of the current thread pool thread that may have been changed by a user callback.
/// </summary>
internal void ResetThreadPoolThread()
{
Debug.Assert(this == RuntimeThread.CurrentThread);
CultureInfo.ResetThreadCulture();
if (_name != null)
{
_name = null;
}
if (!GetThreadStateBit(ThreadState.Background))
{
SetThreadStateBit(ThreadState.Background);
}
ThreadPriority newPriority = ThreadPriority.Normal;
if ((_priority != newPriority) && SetPriorityLive(newPriority))
{
_priority = newPriority;
}
}
/// <summary>
/// Ensures the Windows Runtime is initialized on the current thread.
/// </summary>
internal static void RoInitialize()
{
#if ENABLE_WINRT
Interop.WinRT.RoInitialize();
#endif
}
/// <summary>
/// Returns true if the underlying OS thread has been created and started execution of managed code.
/// </summary>
private bool HasStarted()
{
return !GetThreadStateBit(ThreadState.Unstarted);
}
internal ExecutionContext ExecutionContext
{
get { return _executionContext; }
set { _executionContext = value; }
}
internal SynchronizationContext SynchronizationContext
{
get { return _synchronizationContext; }
set { _synchronizationContext = value; }
}
public bool IsAlive
{
get
{
// Refresh ThreadState.Stopped bit if necessary
ThreadState state = GetThreadState();
return (state & (ThreadState.Unstarted | ThreadState.Stopped | ThreadState.Aborted)) == 0;
}
}
private bool IsDead()
{
// Refresh ThreadState.Stopped bit if necessary
ThreadState state = GetThreadState();
return (state & (ThreadState.Stopped | ThreadState.Aborted)) != 0;
}
public bool IsBackground
{
get
{
if (IsDead())
{
throw new ThreadStateException(SR.ThreadState_Dead_State);
}
return GetThreadStateBit(ThreadState.Background);
}
set
{
if (IsDead())
{
throw new ThreadStateException(SR.ThreadState_Dead_State);
}
// TODO: Keep a counter of running foregroung threads so we can wait on process exit
if (value)
{
SetThreadStateBit(ThreadState.Background);
}
else
{
ClearThreadStateBit(ThreadState.Background);
}
}
}
public bool IsThreadPoolThread
{
get
{
if (IsDead())
{
throw new ThreadStateException(SR.ThreadState_Dead_State);
}
return GetThreadStateBit(ThreadPoolThread);
}
internal set
{
if (IsDead())
{
throw new ThreadStateException(SR.ThreadState_Dead_State);
}
if (value)
{
SetThreadStateBit(ThreadPoolThread);
}
else
{
ClearThreadStateBit(ThreadPoolThread);
}
}
}
public int ManagedThreadId => _managedThreadId.Id;
public string Name
{
get
{
return _name;
}
set
{
if (Interlocked.CompareExchange(ref _name, value, null) != null)
{
throw new InvalidOperationException(SR.InvalidOperation_WriteOnce);
}
// TODO: Inform the debugger and the profiler
}
}
public ThreadPriority Priority
{
get
{
if (IsDead())
{
throw new ThreadStateException(SR.ThreadState_Dead_Priority);
}
if (!HasStarted())
{
// The thread has not been started yet; return the value assigned to the Priority property.
// Race condition with setting the priority or starting the thread is OK, we may return an old value.
return _priority;
}
// The priority might have been changed by external means. Obtain the actual value from the OS
// rather than using the value saved in _priority.
return GetPriorityLive();
}
set
{
if ((value < ThreadPriority.Lowest) || (ThreadPriority.Highest < value))
{
throw new ArgumentOutOfRangeException(SR.Argument_InvalidFlag);
}
if (IsDead())
{
throw new ThreadStateException(SR.ThreadState_Dead_Priority);
}
// Prevent race condition with starting this thread
using (LockHolder.Hold(_lock))
{
if (HasStarted() && !SetPriorityLive(value))
{
throw new ThreadStateException(SR.ThreadState_SetPriorityFailed);
}
_priority = value;
}
}
}
public ThreadState ThreadState => (GetThreadState() & PublicThreadStateMask);
private bool GetThreadStateBit(ThreadState bit)
{
Debug.Assert((bit & ThreadState.Stopped) == 0, "ThreadState.Stopped bit may be stale; use GetThreadState instead.");
return (_threadState & (int)bit) != 0;
}
private void SetThreadStateBit(ThreadState bit)
{
int oldState, newState;
do
{
oldState = _threadState;
newState = oldState | (int)bit;
} while (Interlocked.CompareExchange(ref _threadState, newState, oldState) != oldState);
}
private void ClearThreadStateBit(ThreadState bit)
{
int oldState, newState;
do
{
oldState = _threadState;
newState = oldState & ~(int)bit;
} while (Interlocked.CompareExchange(ref _threadState, newState, oldState) != oldState);
}
internal void SetWaitSleepJoinState()
{
Debug.Assert(this == CurrentThread);
Debug.Assert(!GetThreadStateBit(ThreadState.WaitSleepJoin));
SetThreadStateBit(ThreadState.WaitSleepJoin);
}
internal void ClearWaitSleepJoinState()
{
Debug.Assert(this == CurrentThread);
Debug.Assert(GetThreadStateBit(ThreadState.WaitSleepJoin));
ClearThreadStateBit(ThreadState.WaitSleepJoin);
}
private static int VerifyTimeoutMilliseconds(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(
nameof(millisecondsTimeout),
millisecondsTimeout,
SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
return millisecondsTimeout;
}
public void Join() => Join(Timeout.Infinite);
public bool Join(int millisecondsTimeout)
{
VerifyTimeoutMilliseconds(millisecondsTimeout);
if (GetThreadStateBit(ThreadState.Unstarted))
{
throw new ThreadStateException(SR.ThreadState_NotStarted);
}
return JoinInternal(millisecondsTimeout);
}
public static void Sleep(int millisecondsTimeout) => SleepInternal(VerifyTimeoutMilliseconds(millisecondsTimeout));
/// <summary>
/// Max value to be passed into <see cref="SpinWait(int)"/> for optimal delaying. Currently, the value comes from
/// defaults in CoreCLR's Thread::InitializeYieldProcessorNormalized(). This value is supposed to be normalized to be
/// appropriate for the processor.
/// TODO: See issue https://github.com/dotnet/corert/issues/4430
/// </summary>
internal static readonly int OptimalMaxSpinWaitsPerSpinIteration = 64;
public static void SpinWait(int iterations) => RuntimeImports.RhSpinWait(iterations);
public static bool Yield() => RuntimeImports.RhYield();
public void Start() => StartInternal(null);
public void Start(object parameter)
{
if (_threadStart is ThreadStart)
{
throw new InvalidOperationException(SR.InvalidOperation_ThreadWrongThreadStart);
}
StartInternal(parameter);
}
private void StartInternal(object parameter)
{
using (LockHolder.Hold(_lock))
{
if (!GetThreadStateBit(ThreadState.Unstarted))
{
throw new ThreadStateException(SR.ThreadState_AlreadyStarted);
}
bool waitingForThreadStart = false;
GCHandle threadHandle = GCHandle.Alloc(this);
_threadStartArg = parameter;
try
{
if (!CreateThread(threadHandle))
{
throw new OutOfMemoryException();
}
// Skip cleanup if any asynchronous exception happens while waiting for the thread start
waitingForThreadStart = true;
// Wait until the new thread either dies or reports itself as started
while (GetThreadStateBit(ThreadState.Unstarted) && !JoinInternal(0))
{
Yield();
}
waitingForThreadStart = false;
}
finally
{
Debug.Assert(!waitingForThreadStart, "Leaked threadHandle");
if (!waitingForThreadStart)
{
threadHandle.Free();
_threadStartArg = null;
}
}
if (GetThreadStateBit(ThreadState.Unstarted))
{
// Lack of memory is the only expected reason for thread creation failure
throw new ThreadStartException(new OutOfMemoryException());
}
}
}
private static void StartThread(IntPtr parameter)
{
GCHandle threadHandle = (GCHandle)parameter;
RuntimeThread thread = (RuntimeThread)threadHandle.Target;
Delegate threadStart = thread._threadStart;
// Get the value before clearing the ThreadState.Unstarted bit
object threadStartArg = thread._threadStartArg;
try
{
t_currentThread = thread;
System.Threading.ManagedThreadId.SetForCurrentThread(thread._managedThreadId);
RoInitialize();
}
catch (OutOfMemoryException)
{
#if PLATFORM_UNIX
// This should go away once OnThreadExit stops using t_currentThread to signal
// shutdown of the thread on Unix.
thread._stopped.Set();
#endif
// Terminate the current thread. The creator thread will throw a ThreadStartException.
return;
}
// Report success to the creator thread, which will free threadHandle and _threadStartArg
thread.ClearThreadStateBit(ThreadState.Unstarted);
try
{
// The Thread cannot be started more than once, so we may clean up the delegate
thread._threadStart = null;
ParameterizedThreadStart paramThreadStart = threadStart as ParameterizedThreadStart;
if (paramThreadStart != null)
{
paramThreadStart(threadStartArg);
}
else
{
((ThreadStart)threadStart)();
}
}
finally
{
thread.SetThreadStateBit(ThreadState.Stopped);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuickCheck.Internal
{
public abstract class DataDiff
{
public virtual bool IsEmpty
{
get
{
return false;
}
}
public override string ToString()
{
return AppendTo(new StringBuilder()).ToString();
}
public abstract StringBuilder AppendTo(StringBuilder sb);
private static readonly DataDiff s_Empty = new EmptyDiff();
internal static DataDiff Empty
{
get
{
return s_Empty;
}
}
public abstract DataDiff WithEpsilon(double epsilon);
}
internal class EmptyDiff : DataDiff
{
public override bool IsEmpty
{
get
{
return true;
}
}
public override StringBuilder AppendTo(StringBuilder sb)
{
return sb.Append("<equal>");
}
public override DataDiff WithEpsilon(double epsilon)
{
return this;
}
}
internal class GeneralDiff : DataDiff
{
private readonly Data m_Old;
private readonly Data m_New;
public GeneralDiff(Data old, Data new_)
{
m_Old = old;
m_New = new_;
}
public override StringBuilder AppendTo(StringBuilder sb)
{
return sb.Append(m_Old).Append(" => ").Append(m_New);
}
public override DataDiff WithEpsilon(double epsilon)
{
return this;
}
}
internal class ObjectDiff : DataDiff
{
private readonly KeyValuePair<string, DataDiff>[] m_Fields;
public override bool IsEmpty
{
get
{
return m_Fields.Length == 0;
}
}
private ObjectDiff(KeyValuePair<string, DataDiff>[] fields)
{
m_Fields = fields;
}
public ObjectDiff(
IEnumerable<KeyValuePair<string, Data>> olds,
IEnumerable<KeyValuePair<string, Data>> news)
{
var fields = new List<KeyValuePair<string, DataDiff>>();
var newDict = news.ToDictionary(x => x.Key, x => x.Value);
foreach (var old in olds)
{
Data newValue;
if (!newDict.TryGetValue(old.Key, out newValue))
{
continue;
}
DataDiff diff = old.Value.Diff(newValue);
if (!diff.IsEmpty)
{
fields.Add(new KeyValuePair<string, DataDiff>(old.Key, diff));
}
}
m_Fields = fields.ToArray();
}
public override StringBuilder AppendTo(StringBuilder sb)
{
if (m_Fields.Length == 0)
{
return sb;
}
sb.Append("{");
bool comma = false;
foreach (var field in m_Fields)
{
if (comma)
{
sb.Append(", ");
}
sb.Append(field.Key);
sb.Append(": ");
if (field.Value == null)
{
sb.Append("null");
}
else
{
sb.Append(field.Value);
}
comma = true;
}
return sb.Append("}");
}
public override DataDiff WithEpsilon(double epsilon)
{
var fields = m_Fields
.Select(x => new KeyValuePair<string, DataDiff>(x.Key, x.Value.WithEpsilon(epsilon)))
.Where(x => !x.Value.IsEmpty)
.ToArray();
if (fields.Length == 0)
{
return Empty;
}
return new ObjectDiff(fields);
}
}
internal class FloatDiff : DataDiff
{
private readonly float m_Old;
private readonly float m_New;
public FloatDiff(float old, float new_)
{
m_Old = old;
m_New = new_;
}
public override StringBuilder AppendTo(StringBuilder sb)
{
return sb.Append(m_Old).Append(" => ").Append(m_New);
}
public override DataDiff WithEpsilon(double epsilon)
{
return Math.Abs(m_Old - m_New) < epsilon ? Empty : this;
}
}
internal class DoubleDiff : DataDiff
{
private readonly double m_Old;
private readonly double m_New;
public DoubleDiff(double old, double new_)
{
m_Old = old;
m_New = new_;
}
public override StringBuilder AppendTo(StringBuilder sb)
{
sb.Append(m_Old);
double diff = m_New - m_Old;
if (diff >= 0)
{
sb.Append(" + ").Append(diff);
}
else
{
sb.Append(" - ").Append(-diff);
}
return sb.Append(" => ").Append(m_New);
}
public override DataDiff WithEpsilon(double epsilon)
{
return Math.Abs(m_Old - m_New) < epsilon ? Empty : this;
}
}
}
| |
// File: CommandLineOptions.cs
//
// This is a re-usable component to be used when you
// need to parse command-line options/parameters.
//
// Separates command line parameters from command line options.
// Uses reflection to populate member variables the derived class with the values
// of the options.
//
// An option can start with "/", "-" or "--".
//
// I define 3 types of "options":
// 1. Boolean options (yes/no values), e.g: /r to recurse
// 2. Value options, e.g: /loglevel=3
// 2. Parameters: standalone strings like file names
//
// An example to explain:
// csc /nologo /t:exe myfile.cs
// | | |
// | | + parameter
// | |
// | + value option
// |
// + boolean option
//
// Please see a short description of the CommandLineOptions class
// at http://codeblast.com/~gert/dotnet/sells.html
//
// Gert Lombard ([email protected])
// James Newkirk ([email protected])
namespace Codeblast
{
using System;
using System.Reflection;
using System.Collections;
using System.Text;
//
// The Attributes
//
[AttributeUsage(AttributeTargets.Field)]
public class OptionAttribute : Attribute
{
protected object optValue;
protected string optName;
protected string description;
public string Short
{
get { return optName; }
set { optName = value; }
}
public object Value
{
get { return optValue; }
set { optValue = value; }
}
public string Description
{
get { return description; }
set { description = value; }
}
}
//
// The CommandLineOptions members
//
public abstract class CommandLineOptions
{
protected ArrayList parameters;
private int optionCount;
public CommandLineOptions(string[] args)
{
optionCount = Init(args);
}
public bool NoArgs
{
get
{
return ParameterCount == 0 && optionCount == 0;
}
}
public int Init(string[] args)
{
int count = 0;
int n = 0;
while (n < args.Length)
{
int pos = IsOption(args[n]);
if (pos > 0)
{
// It's an option:
if (GetOption(args, ref n, pos))
count++;
else
InvalidOption(args[Math.Min(n, args.Length-1)]);
}
else
{
// It's a parameter:
if (parameters == null) parameters = new ArrayList();
parameters.Add(args[n]);
}
n++;
}
return count;
}
// An option starts with "/", "-" or "--":
protected virtual int IsOption(string opt)
{
char[] c = null;
if (opt.Length < 2)
{
return 0;
}
else if (opt.Length > 2)
{
c = opt.ToCharArray(0, 3);
if (c[0] == '-' && c[1] == '-' && IsOptionNameChar(c[2])) return 2;
}
else
{
c = opt.ToCharArray(0, 2);
}
if ((c[0] == '-' || c[0] == '/') && IsOptionNameChar(c[1])) return 1;
return 0;
}
protected virtual bool IsOptionNameChar(char c)
{
return Char.IsLetterOrDigit(c) || c == '?';
}
protected abstract void InvalidOption(string name);
protected virtual bool MatchShortName(FieldInfo field, string name)
{
object[] atts = field.GetCustomAttributes(typeof(OptionAttribute), true);
foreach (OptionAttribute att in atts)
{
if (string.Compare(att.Short, name, true) == 0) return true;
}
return false;
}
protected virtual FieldInfo GetMemberField(string name)
{
Type t = this.GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.Instance|BindingFlags.Public);
foreach (FieldInfo field in fields)
{
if (string.Compare(field.Name, name, true) == 0) return field;
if (MatchShortName(field, name)) return field;
}
return null;
}
protected virtual object GetOptionValue(FieldInfo field)
{
object[] atts = field.GetCustomAttributes(typeof(OptionAttribute), true);
if (atts.Length > 0)
{
OptionAttribute att = (OptionAttribute)atts[0];
return att.Value;
}
return null;
}
protected virtual bool GetOption(string[] args, ref int index, int pos)
{
try
{
object cmdLineVal = null;
string opt = args[index].Substring(pos, args[index].Length-pos);
SplitOptionAndValue(ref opt, ref cmdLineVal);
FieldInfo field = GetMemberField(opt);
if (field != null)
{
object value = GetOptionValue(field);
if (value == null)
{
if (field.FieldType == typeof(bool))
value = true; // default for bool values is true
else if(field.FieldType == typeof(string))
{
value = cmdLineVal != null ? cmdLineVal : args[++index];
field.SetValue(this, Convert.ChangeType(value, field.FieldType));
string stringValue = (string)value;
if(stringValue == null || stringValue.Length == 0) return false;
return true;
}
else
value = cmdLineVal != null ? cmdLineVal : args[++index];
}
field.SetValue(this, Convert.ChangeType(value, field.FieldType));
return true;
}
}
catch (Exception)
{
// Ignore exceptions like type conversion errors.
}
return false;
}
protected virtual void SplitOptionAndValue(ref string opt, ref object val)
{
// Look for ":" or "=" separator in the option:
int pos = opt.IndexOfAny( new char[] { ':', '=' } );
if (pos < 1) return;
val = opt.Substring(pos+1);
opt = opt.Substring(0, pos);
}
// Parameter accessor:
public string this[int index]
{
get
{
if (parameters != null) return (string)parameters[index];
return null;
}
}
public ArrayList Parameters
{
get { return parameters; }
}
public int ParameterCount
{
get
{
return parameters == null ? 0 : parameters.Count;
}
}
public virtual void Help()
{
Console.WriteLine(GetHelpText());
}
public virtual string GetHelpText()
{
StringBuilder helpText = new StringBuilder();
Type t = this.GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.Instance|BindingFlags.Public);
foreach (FieldInfo field in fields)
{
object[] atts = field.GetCustomAttributes(typeof(OptionAttribute), true);
if (atts.Length > 0)
{
OptionAttribute att = (OptionAttribute)atts[0];
if (att.Description != null)
{
string valType = "";
if (att.Value == null)
{
if (field.FieldType == typeof(float)) valType = "=FLOAT";
else if (field.FieldType == typeof(string)) valType = "=STR";
else if (field.FieldType != typeof(bool)) valType = "=X";
}
helpText.AppendFormat("/{0,-20}{1}", field.Name+valType, att.Description);
if (att.Short != null)
helpText.AppendFormat(" (Short format: /{0}{1})", att.Short, valType);
helpText.Append( Environment.NewLine );
}
}
}
return helpText.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;
using Xunit;
namespace System.Net.Sockets.Tests
{
public class OSSupportTest
{
[Fact]
public void SupportsIPv4_MatchesOSSupportsIPv4()
{
#pragma warning disable 0618 // Supports* are obsoleted
Assert.Equal(Socket.SupportsIPv4, Socket.OSSupportsIPv4);
#pragma warning restore
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "SupportsIPv6 factors in config data")]
[Fact]
public void SupportsIPv6_MatchesOSSupportsIPv6()
{
#pragma warning disable 0618 // Supports* are obsoleted
Assert.Equal(Socket.SupportsIPv6, Socket.OSSupportsIPv6);
#pragma warning restore
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[Fact]
public void UseOnlyOverlappedIO_AlwaysFalse()
{
using (var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Equal(AddressFamily.InterNetwork, s.AddressFamily);
Assert.Equal(SocketType.Stream, s.SocketType);
Assert.Equal(ProtocolType.Tcp, s.ProtocolType);
Assert.False(s.UseOnlyOverlappedIO);
s.UseOnlyOverlappedIO = true;
Assert.False(s.UseOnlyOverlappedIO);
}
}
[Fact]
public void IOControl_FIONREAD_Success()
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.DataToRead, null, null));
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.DataToRead, null, new byte[0]));
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.DataToRead, null, new byte[sizeof(int) - 1]));
byte[] fionreadResult = new byte[sizeof(int)];
Assert.Equal(4, client.IOControl(IOControlCode.DataToRead, null, fionreadResult));
Assert.Equal(client.Available, BitConverter.ToInt32(fionreadResult, 0));
Assert.Equal(0, BitConverter.ToInt32(fionreadResult, 0));
Assert.Equal(4, client.IOControl((int)IOControlCode.DataToRead, null, fionreadResult));
Assert.Equal(client.Available, BitConverter.ToInt32(fionreadResult, 0));
Assert.Equal(0, BitConverter.ToInt32(fionreadResult, 0));
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
client.Connect(listener.LocalEndPoint);
using (Socket server = listener.Accept())
{
server.Send(new byte[] { 42 });
Assert.True(SpinWait.SpinUntil(() => client.Available != 0, 10_000));
Assert.Equal(4, client.IOControl(IOControlCode.DataToRead, null, fionreadResult));
Assert.Equal(client.Available, BitConverter.ToInt32(fionreadResult, 0));
Assert.Equal(1, BitConverter.ToInt32(fionreadResult, 0));
}
}
}
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Fact]
public void IOControl_SIOCATMARK_Unix_Success()
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.OobDataRead, null, null));
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.OobDataRead, null, new byte[0]));
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.OobDataRead, null, new byte[sizeof(int) - 1]));
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
client.Connect(listener.LocalEndPoint);
using (Socket server = listener.Accept())
{
byte[] siocatmarkResult = new byte[sizeof(int)];
// Socket connected but no data sent.
Assert.Equal(4, client.IOControl(IOControlCode.OobDataRead, null, siocatmarkResult));
Assert.Equal(0, BitConverter.ToInt32(siocatmarkResult, 0));
server.Send(new byte[] { 42 }, SocketFlags.None);
server.Send(new byte[] { 43 }, SocketFlags.OutOfBand);
// OOB data recieved, but read pointer not at mark.
Assert.True(SpinWait.SpinUntil(() =>
{
Assert.Equal(4, client.IOControl(IOControlCode.OobDataRead, null, siocatmarkResult));
return BitConverter.ToInt32(siocatmarkResult, 0) == 0;
}, 10_000));
var received = new byte[1];
Assert.Equal(1, client.Receive(received));
Assert.Equal(42, received[0]);
// OOB data recieved, read pointer at mark.
Assert.Equal(4, client.IOControl(IOControlCode.OobDataRead, null, siocatmarkResult));
Assert.Equal(1, BitConverter.ToInt32(siocatmarkResult, 0));
Assert.Equal(1, client.Receive(received, SocketFlags.OutOfBand));
Assert.Equal(43, received[0]);
// OOB data read, read pointer at mark.
Assert.Equal(4, client.IOControl(IOControlCode.OobDataRead, null, siocatmarkResult));
Assert.Equal(PlatformDetection.IsOSX ? 0 : 1, BitConverter.ToInt32(siocatmarkResult, 0));
}
}
}
}
[PlatformSpecific(TestPlatforms.Windows)]
[Fact]
public void IOControl_SIOCATMARK_Windows_Success()
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.OobDataRead, null, null));
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.OobDataRead, null, new byte[0]));
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.OobDataRead, null, new byte[sizeof(int) - 1]));
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
client.Connect(listener.LocalEndPoint);
using (Socket server = listener.Accept())
{
byte[] siocatmarkResult = new byte[sizeof(int)];
// Socket connected but no data sent.
Assert.Equal(4, client.IOControl(IOControlCode.OobDataRead, null, siocatmarkResult));
Assert.Equal(1, BitConverter.ToInt32(siocatmarkResult, 0));
server.Send(new byte[] { 42 }, SocketFlags.None);
server.Send(new byte[] { 43 }, SocketFlags.OutOfBand);
// OOB data recieved, but read pointer not at mark
Assert.True(SpinWait.SpinUntil(() =>
{
Assert.Equal(4, client.IOControl(IOControlCode.OobDataRead, null, siocatmarkResult));
return BitConverter.ToInt32(siocatmarkResult, 0) == 0;
}, 10_000));
var received = new byte[1];
Assert.Equal(1, client.Receive(received));
Assert.Equal(42, received[0]);
// OOB data recieved, read pointer at mark.
Assert.Equal(4, client.IOControl(IOControlCode.OobDataRead, null, siocatmarkResult));
Assert.Equal(0, BitConverter.ToInt32(siocatmarkResult, 0));
Assert.Equal(1, client.Receive(received, SocketFlags.OutOfBand));
Assert.Equal(43, received[0]);
// OOB data read, read pointer at mark.
Assert.Equal(4, client.IOControl(IOControlCode.OobDataRead, null, siocatmarkResult));
Assert.Equal(1, BitConverter.ToInt32(siocatmarkResult, 0));
}
}
}
}
[Fact]
public void IOControl_FIONBIO_Throws()
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<InvalidOperationException>(() => client.IOControl(unchecked((int)IOControlCode.NonBlockingIO), null, null));
Assert.Throws<InvalidOperationException>(() => client.IOControl(IOControlCode.NonBlockingIO, null, null));
}
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Fact]
public void IOControl_UnknownValues_Unix_Throws()
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
foreach (IOControlCode code in Enum.GetValues(typeof(IOControlCode)))
{
switch (code)
{
case IOControlCode.NonBlockingIO:
case IOControlCode.DataToRead:
case IOControlCode.OobDataRead:
// These three codes are currently enabled on Unix.
break;
default:
// The rest should throw PNSE.
Assert.Throws<PlatformNotSupportedException>(() => client.IOControl((int)code, null, null));
Assert.Throws<PlatformNotSupportedException>(() => client.IOControl(code, null, null));
break;
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using eQuantic.Core.Utils;
namespace eQuantic.Core.Extensions
{
public static class Reflection
{
private static List<string> GetBreadcrumbMemberList(Expression expression)
{
if (expression == null || expression is ParameterExpression || expression is ConstantExpression)
return new List<string>();
var memberExpression = expression as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("Expression must have property accessors only");
var list = GetBreadcrumbMemberList(memberExpression.Expression);
list.Add(memberExpression.Member.Name);
return list;
}
public static IEnumerable<string> GetBreadcrumbMemberList<TResult>(Expression<Func<TResult>> action)
{
return GetBreadcrumbMemberList(action as LambdaExpression);
}
internal static IEnumerable<string> GetBreadcrumbMemberList(LambdaExpression action)
{
#region Input Validation
if (action == null)
{
throw new ArgumentNullException("action");
}
#endregion
var member = action.Body as MemberExpression;
if (member == null)
throw new ArgumentException("Expression must be a property accessor");
return GetBreadcrumbMemberList(member);
}
internal static string GetBreadcrumbMemberName(LambdaExpression action, string separator = ".", int skip = 0)
{
return string.Join(separator, GetBreadcrumbMemberList(action).Skip(skip));
}
public static string GetBreadcrumbMemberName<TResult>(Expression<Func<TResult>> action, string separator = ".",
int skip = 0)
{
return GetBreadcrumbMemberName(action as LambdaExpression, separator, skip);
}
public static string GetBreadcrumbMemberName<TResult>(Expression<Func<TResult>> action, int skip)
{
return GetBreadcrumbMemberName(action as LambdaExpression, skip: skip);
}
public static string GetMemberName<T, TResult>(IEnumerable<T> obj, Expression<Func<T, TResult>> action)
{
return GetMemberName(action);
}
public static string GetObjectMemberName<T, TResult>(T obj, Expression<Func<T, TResult>> action)
{
return GetMemberName(action);
}
public static string GetMemberName<TParam, TResult>(Expression<Func<TParam, TResult>> action)
{
return GetMemberName(action as LambdaExpression);
}
public static string GetMemberName<TResult>(Expression<Func<TResult>> action)
{
return GetMemberName(action as LambdaExpression);
}
public static string GetMemberName(Expression<Action> action)
{
return GetMemberName(action as LambdaExpression);
}
internal static string GetMemberName(LambdaExpression action)
{
#region Input Validation
if (action == null)
{
throw new ArgumentNullException("action");
}
#endregion
var member = action.Body as MemberExpression;
if (member != null)
{
return member.Member.Name;
}
var method = action.Body as MethodCallExpression;
if (method == null)
{
throw new ArgumentException("Expression must be a property accessor or method call");
}
return method.Method.Name;
}
public static Type GetMemberType<TResult>(Expression<Func<TResult>> action)
{
return typeof(TResult);
}
public static Type GetMemberType<T, TResult>(IEnumerable<T> obj, Expression<Func<T, TResult>> action)
{
return typeof(TResult);
}
public static PropertyInfo GetPropertyInfo<T>(T obj, Expression<Func<T, object>> func)
{
return GetPropertyInfo<T>(func);
}
public static PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> func)
{
var unary = (func.Body as UnaryExpression);
MemberExpression member;
if (unary == null)
{
member = func.Body as MemberExpression;
}
else
{
member = unary.Operand as MemberExpression;
}
if ((member.Member is PropertyInfo) == false)
{
throw new ArgumentException("Lambda is not a Property");
}
var type = (member.Expression as ParameterExpression)?.Type;
#if NETSTANDARD1_6
return type.GetTypeInfo().GetDeclaredProperty(member.Member.Name);
#else
return
type.GetProperty(member.Member.Name)
as PropertyInfo;
#endif
}
public static MethodInfo GetMethodInfo<T1, T2>(Expression<Func<T1, Action<T2>>> a)
{
UnaryExpression exp = a.Body as UnaryExpression;
MethodCallExpression call = exp.Operand as MethodCallExpression;
ConstantExpression arg = call.Arguments[2] as ConstantExpression;
return arg.Value as MethodInfo;
}
public static MethodInfo GetMethodInfo<TResult>(Expression<Func<TResult>> action)
{
var method = action.Body as MethodCallExpression;
if (method == null)
{
throw new ArgumentException("Expression must be a method call");
}
return method.Method;
}
}
public static class Reflection<T>
{
public static MethodInfo GetMethod<TResult>(Expression<Func<T, TResult>> action)
{
var methodExtractor = new MethodExtractorVisitor();
methodExtractor.Visit(action);
return methodExtractor.Method;
}
public static string GetMemberName<TResult>(Expression<Func<T, TResult>> action)
{
return Reflection.GetMemberName(action);
}
public static string GetMemberName(Expression<Action<T>> action)
{
return Reflection.GetMemberName(action);
}
public static Type GetMemberType<TResult>(Expression<Func<T, TResult>> action)
{
return typeof(TResult);
}
public static string GetPropertiesPath<TResult>(Expression<Func<T, TResult>> propertyExpression)
{
return string.Join(".", GetProperties(propertyExpression).Select(p => p.Name).ToArray());
}
public static IEnumerable<PropertyInfo> GetProperties<TResult>(Expression<Func<T, TResult>> propertyExpression)
{
var unary = (propertyExpression.Body as UnaryExpression);
if (unary != null)
{
return GetProperties(unary.Operand);
}
return GetProperties(propertyExpression.Body);
}
private static IEnumerable<PropertyInfo> GetProperties(Expression expression)
{
var memberExpression = expression as MemberExpression;
if (memberExpression == null) yield break;
var property = memberExpression.Member as PropertyInfo;
if (property == null)
{
throw new ArgumentException("Expression is not a property accessor");
}
foreach (var propertyInfo in GetProperties(memberExpression.Expression))
{
yield return propertyInfo;
}
yield return property;
}
public static IEnumerable<TAttribute> GetPropertyAttributes<TAttribute>(
Expression<Func<T, object>> propertyExpression, bool inherit = true) where TAttribute : Attribute
{
var memberExpression = propertyExpression.Body as MemberExpression;
if (memberExpression == null)
return new TAttribute[0];
return memberExpression.Member.GetCustomAttributes<TAttribute>(inherit);
}
public static IEnumerable<string> GetBreadcrumbMemberList<TResult>(Expression<Func<T, TResult>> action)
{
return Reflection.GetBreadcrumbMemberList(action as LambdaExpression);
}
public static string GetBreadcrumbMemberName<TResult>(Expression<Func<T, TResult>> action,
string separator = ".")
{
return Reflection.GetBreadcrumbMemberName(action as LambdaExpression, separator);
}
}
}
| |
// 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.Data;
using System.Diagnostics;
using System.Threading;
#pragma warning disable 618 // ignore obsolete warning about XmlDataDocument
namespace System.Xml
{
internal enum ElementState
{
None,
Defoliated,
WeakFoliation,
StrongFoliation,
Foliating,
Defoliating,
}
internal sealed class XmlBoundElement : XmlElement
{
private DataRow _row;
private ElementState _state;
internal XmlBoundElement(string prefix, string localName, string namespaceURI, XmlDocument doc) : base(prefix, localName, namespaceURI, doc)
{
_state = ElementState.None;
}
public override XmlAttributeCollection Attributes
{
get
{
AutoFoliate();
return base.Attributes;
}
}
public override bool HasAttributes => Attributes.Count > 0;
public override XmlNode FirstChild
{
get
{
AutoFoliate();
return base.FirstChild;
}
}
internal XmlNode SafeFirstChild => base.FirstChild;
public override XmlNode LastChild
{
get
{
AutoFoliate();
return base.LastChild;
}
}
public override XmlNode PreviousSibling
{
get
{
XmlNode prev = base.PreviousSibling;
if (prev == null)
{
XmlBoundElement parent = ParentNode as XmlBoundElement;
if (parent != null)
{
parent.AutoFoliate();
return base.PreviousSibling;
}
}
return prev;
}
}
internal XmlNode SafePreviousSibling => base.PreviousSibling;
public override XmlNode NextSibling
{
get
{
XmlNode next = base.NextSibling;
if (next == null)
{
XmlBoundElement parent = ParentNode as XmlBoundElement;
if (parent != null)
{
parent.AutoFoliate();
return base.NextSibling;
}
}
return next;
}
}
internal XmlNode SafeNextSibling => base.NextSibling;
public override bool HasChildNodes
{
get
{
AutoFoliate();
return base.HasChildNodes;
}
}
public override XmlNode InsertBefore(XmlNode newChild, XmlNode refChild)
{
AutoFoliate();
return base.InsertBefore(newChild, refChild);
}
public override XmlNode InsertAfter(XmlNode newChild, XmlNode refChild)
{
AutoFoliate();
return base.InsertAfter(newChild, refChild);
}
public override XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild)
{
AutoFoliate();
return base.ReplaceChild(newChild, oldChild);
}
public override XmlNode AppendChild(XmlNode newChild)
{
AutoFoliate();
return base.AppendChild(newChild);
}
internal void RemoveAllChildren()
{
XmlNode child = FirstChild;
XmlNode sibling = null;
while (child != null)
{
sibling = child.NextSibling;
RemoveChild(child);
child = sibling;
}
}
public override string InnerXml
{
get { return base.InnerXml; }
set
{
RemoveAllChildren();
XmlDataDocument doc = (XmlDataDocument)OwnerDocument;
bool bOrigIgnoreXmlEvents = doc.IgnoreXmlEvents;
bool bOrigIgnoreDataSetEvents = doc.IgnoreDataSetEvents;
doc.IgnoreXmlEvents = true;
doc.IgnoreDataSetEvents = true;
base.InnerXml = value;
doc.SyncTree(this);
doc.IgnoreDataSetEvents = bOrigIgnoreDataSetEvents;
doc.IgnoreXmlEvents = bOrigIgnoreXmlEvents;
}
}
internal DataRow Row
{
get { return _row; }
set { _row = value; }
}
internal bool IsFoliated
{
get
{
while (_state == ElementState.Foliating || _state == ElementState.Defoliating)
{
Thread.Sleep(0);
}
//has to be sure that we are either foliated or defoliated when ask for IsFoliated.
return _state != ElementState.Defoliated;
}
}
internal ElementState ElementState
{
get { return _state; }
set { _state = value; }
}
internal void Foliate(ElementState newState)
{
XmlDataDocument doc = (XmlDataDocument)OwnerDocument;
if (doc != null)
{
doc.Foliate(this, newState);
}
}
// Foliate the node as a side effect of user calling functions on this node (like NextSibling) OR as a side effect of DataDocNav using nodes to do editing
private void AutoFoliate()
{
XmlDataDocument doc = (XmlDataDocument)OwnerDocument;
if (doc != null)
{
doc.Foliate(this, doc.AutoFoliationState);
}
}
public override XmlNode CloneNode(bool deep)
{
XmlDataDocument doc = (XmlDataDocument)(OwnerDocument);
ElementState oldAutoFoliationState = doc.AutoFoliationState;
doc.AutoFoliationState = ElementState.WeakFoliation;
XmlElement element;
try
{
Foliate(ElementState.WeakFoliation);
element = (XmlElement)(base.CloneNode(deep));
// Clone should create a XmlBoundElement node
Debug.Assert(element is XmlBoundElement);
}
finally
{
doc.AutoFoliationState = oldAutoFoliationState;
}
return element;
}
public override void WriteContentTo(XmlWriter w)
{
DataPointer dp = new DataPointer((XmlDataDocument)OwnerDocument, this);
try
{
dp.AddPointer();
WriteBoundElementContentTo(dp, w);
}
finally
{
dp.SetNoLongerUse();
}
}
public override void WriteTo(XmlWriter w)
{
DataPointer dp = new DataPointer((XmlDataDocument)OwnerDocument, this);
try
{
dp.AddPointer();
WriteRootBoundElementTo(dp, w);
}
finally
{
dp.SetNoLongerUse();
}
}
private void WriteRootBoundElementTo(DataPointer dp, XmlWriter w)
{
Debug.Assert(dp.NodeType == XmlNodeType.Element);
XmlDataDocument doc = (XmlDataDocument)OwnerDocument;
w.WriteStartElement(dp.Prefix, dp.LocalName, dp.NamespaceURI);
int cAttr = dp.AttributeCount;
bool bHasXSI = false;
if (cAttr > 0)
{
for (int iAttr = 0; iAttr < cAttr; iAttr++)
{
dp.MoveToAttribute(iAttr);
if (dp.Prefix == "xmlns" && dp.LocalName == XmlDataDocument.XSI)
{
bHasXSI = true;
}
WriteTo(dp, w);
dp.MoveToOwnerElement();
}
}
if (!bHasXSI && doc._bLoadFromDataSet && doc._bHasXSINIL)
{
w.WriteAttributeString("xmlns", "xsi", "http://www.w3.org/2000/xmlns/", Keywords.XSINS);
}
WriteBoundElementContentTo(dp, w);
// Force long end tag when the elem is not empty, even if there are no children.
if (dp.IsEmptyElement)
{
w.WriteEndElement();
}
else
{
w.WriteFullEndElement();
}
}
private static void WriteBoundElementTo(DataPointer dp, XmlWriter w)
{
Debug.Assert(dp.NodeType == XmlNodeType.Element);
w.WriteStartElement(dp.Prefix, dp.LocalName, dp.NamespaceURI);
int cAttr = dp.AttributeCount;
if (cAttr > 0)
{
for (int iAttr = 0; iAttr < cAttr; iAttr++)
{
dp.MoveToAttribute(iAttr);
WriteTo(dp, w);
dp.MoveToOwnerElement();
}
}
WriteBoundElementContentTo(dp, w);
// Force long end tag when the elem is not empty, even if there are no children.
if (dp.IsEmptyElement)
{
w.WriteEndElement();
}
else
{
w.WriteFullEndElement();
}
}
private static void WriteBoundElementContentTo(DataPointer dp, XmlWriter w)
{
if (!dp.IsEmptyElement && dp.MoveToFirstChild())
{
do
{
WriteTo(dp, w);
}
while (dp.MoveToNextSibling());
dp.MoveToParent();
}
}
private static void WriteTo(DataPointer dp, XmlWriter w)
{
switch (dp.NodeType)
{
case XmlNodeType.Attribute:
if (!dp.IsDefault)
{
w.WriteStartAttribute(dp.Prefix, dp.LocalName, dp.NamespaceURI);
if (dp.MoveToFirstChild())
{
do
{
WriteTo(dp, w);
}
while (dp.MoveToNextSibling());
dp.MoveToParent();
}
w.WriteEndAttribute();
}
break;
case XmlNodeType.Element:
WriteBoundElementTo(dp, w);
break;
case XmlNodeType.Text:
w.WriteString(dp.Value);
break;
default:
Debug.Assert(((IXmlDataVirtualNode)dp).IsOnColumn(null));
if (dp.GetNode() != null)
{
dp.GetNode().WriteTo(w);
}
break;
}
}
public override XmlNodeList GetElementsByTagName(string name)
{
// Retrieving nodes from the returned nodelist may cause foliation which causes new nodes to be created,
// so the System.Xml iterator will throw if this happens during iteration. To avoid this, foliate everything
// before iteration, so iteration will not cause foliation (and as a result of this, creation of new nodes).
XmlNodeList tempNodeList = base.GetElementsByTagName(name);
int tempint = tempNodeList.Count;
return tempNodeList;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Activities
{
using System.Activities;
using System.Activities.Hosting;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime;
using System.Runtime.DurableInstancing;
using System.ServiceModel.Activation;
using System.ServiceModel.Activities.Configuration;
using System.ServiceModel.Activities.Description;
using System.ServiceModel.Activities.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Activities.Diagnostics;
using System.Xml;
using System.Xml.Linq;
[Fx.Tag.XamlVisible(false)]
public class WorkflowServiceHost : ServiceHostBase
{
static readonly XName mexContractXName = XName.Get(ServiceMetadataBehavior.MexContractName, ServiceMetadataBehavior.MexContractNamespace);
static readonly Type mexBehaviorType = typeof(ServiceMetadataBehavior);
static readonly TimeSpan defaultPersistTimeout = TimeSpan.FromSeconds(30);
static readonly TimeSpan defaultTrackTimeout = TimeSpan.FromSeconds(30);
static readonly TimeSpan defaultFilterResumeTimeout = TimeSpan.FromMinutes(1);
static readonly Type baseActivityType = typeof(Activity);
static readonly Type correlationQueryBehaviorType = typeof(CorrelationQueryBehavior);
static readonly Type bufferedReceiveServiceBehaviorType = typeof(BufferedReceiveServiceBehavior);
WorkflowServiceHostExtensions workflowExtensions;
DurableInstanceManager durableInstanceManager;
WorkflowDefinitionProvider workflowDefinitionProvider;
Activity activity;
WorkflowService serviceDefinition;
IDictionary<XName, ContractDescription> inferredContracts;
IDictionary<XName, Collection<CorrelationQuery>> correlationQueries;
WorkflowUnhandledExceptionAction unhandledExceptionAction;
TimeSpan idleTimeToPersist;
TimeSpan idleTimeToUnload;
WorkflowServiceHostPerformanceCounters workflowServiceHostPerformanceCounters;
[SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors,
Justification = "Based on prior are from WCF3: By design, don't want to complicate ServiceHost state model")]
public WorkflowServiceHost(object serviceImplementation, params Uri[] baseAddresses)
: base()
{
if (serviceImplementation == null)
{
throw FxTrace.Exception.ArgumentNull("serviceImplementation");
}
if (serviceImplementation is WorkflowService)
{
InitializeFromConstructor((WorkflowService)serviceImplementation, baseAddresses);
}
else
{
Activity activity = serviceImplementation as Activity;
if (activity == null)
{
throw FxTrace.Exception.Argument("serviceImplementation", SR.InvalidServiceImplementation);
}
InitializeFromConstructor(activity, baseAddresses);
}
}
[SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors,
Justification = "Based on prior are from WCF3: By design, don't want to complicate ServiceHost state model")]
public WorkflowServiceHost(Activity activity, params Uri[] baseAddresses)
: base()
{
if (activity == null)
{
throw FxTrace.Exception.ArgumentNull("activity");
}
InitializeFromConstructor(activity, baseAddresses);
}
[SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors,
Justification = "Based on prior art from WCF 3.0: By design, don't want to complicate ServiceHost state model")]
public WorkflowServiceHost(WorkflowService serviceDefinition, params Uri[] baseAddresses)
: base()
{
if (serviceDefinition == null)
{
throw FxTrace.Exception.ArgumentNull("serviceDefinition");
}
InitializeFromConstructor(serviceDefinition, baseAddresses);
}
[SuppressMessage(FxCop.Category.Usage, FxCop.Rule.DoNotCallOverridableMethodsInConstructors,
Justification = "Based on prior art from WCF 3.0: By design, don't want to complicate ServiceHost state model")]
protected WorkflowServiceHost()
{
InitializeFromConstructor((WorkflowService)null);
}
public Activity Activity
{
get
{
return this.activity;
}
}
public WorkflowInstanceExtensionManager WorkflowExtensions
{
get
{
return this.workflowExtensions;
}
}
public DurableInstancingOptions DurableInstancingOptions
{
get
{
return this.durableInstanceManager.DurableInstancingOptions;
}
}
public ICollection<WorkflowService> SupportedVersions
{
get
{
return this.workflowDefinitionProvider.SupportedVersions;
}
}
internal XName ServiceName
{
get;
set;
}
internal TimeSpan PersistTimeout
{
get;
set;
}
internal TimeSpan TrackTimeout
{
get;
set;
}
//
internal TimeSpan FilterResumeTimeout
{
get;
set;
}
internal DurableInstanceManager DurableInstanceManager
{
get
{
return this.durableInstanceManager;
}
}
internal bool IsLoadTransactionRequired
{
get;
private set;
}
// set by WorkflowUnhandledExceptionBehavior.ApplyDispatchBehavior, used by WorkflowServiceInstance.UnhandledExceptionPolicy
internal WorkflowUnhandledExceptionAction UnhandledExceptionAction
{
get { return this.unhandledExceptionAction; }
set
{
Fx.Assert(WorkflowUnhandledExceptionActionHelper.IsDefined(value), "Undefined WorkflowUnhandledExceptionAction");
this.unhandledExceptionAction = value;
}
}
// set by WorkflowIdleBehavior.ApplyDispatchBehavior, used by WorkflowServiceInstance.UnloadInstancePolicy
internal TimeSpan IdleTimeToPersist
{
get { return this.idleTimeToPersist; }
set
{
Fx.Assert(value >= TimeSpan.Zero, "IdleTimeToPersist cannot be less than zero");
this.idleTimeToPersist = value;
}
}
internal TimeSpan IdleTimeToUnload
{
get { return this.idleTimeToUnload; }
set
{
Fx.Assert(value >= TimeSpan.Zero, "IdleTimeToUnload cannot be less than zero");
this.idleTimeToUnload = value;
}
}
internal bool IsConfigurable
{
get
{
lock (this.ThisLock)
{
return this.State == CommunicationState.Created || this.State == CommunicationState.Opening;
}
}
}
internal WorkflowServiceHostPerformanceCounters WorkflowServiceHostPerformanceCounters
{
get
{
return this.workflowServiceHostPerformanceCounters;
}
}
internal bool OverrideSiteName
{
get;
set;
}
void InitializeFromConstructor(Activity activity, params Uri[] baseAddresses)
{
WorkflowService serviceDefinition = new WorkflowService
{
Body = activity
};
InitializeFromConstructor(serviceDefinition, baseAddresses);
}
void InitializeFromConstructor(WorkflowService serviceDefinition, params Uri[] baseAddresses)
{
// first initialize some values to their defaults
this.idleTimeToPersist = WorkflowIdleBehavior.defaultTimeToPersist;
this.idleTimeToUnload = WorkflowIdleBehavior.defaultTimeToUnload;
this.unhandledExceptionAction = WorkflowUnhandledExceptionBehavior.defaultAction;
this.workflowExtensions = new WorkflowServiceHostExtensions();
// If the AppSettings.DefaultAutomaticInstanceKeyDisassociation is specified and is true, create a DisassociateInstanceKeysExtension, set its
// AutomaticDisassociationEnabled property to true, and add it to the extensions collection so that System.Activities.BookmarkScopeHandle will
// unregister its BookmarkScope, which will cause key disassociation. KB2669774.
if (AppSettings.DefaultAutomaticInstanceKeyDisassociation)
{
DisassociateInstanceKeysExtension extension = new DisassociateInstanceKeysExtension();
extension.AutomaticDisassociationEnabled = true;
this.workflowExtensions.Add(extension);
}
if (TD.CreateWorkflowServiceHostStartIsEnabled())
{
TD.CreateWorkflowServiceHostStart();
}
if (serviceDefinition != null)
{
this.workflowDefinitionProvider = new WorkflowDefinitionProvider(serviceDefinition, this);
InitializeDescription(serviceDefinition, new UriSchemeKeyedCollection(baseAddresses));
}
this.durableInstanceManager = new DurableInstanceManager(this);
if (TD.CreateWorkflowServiceHostStopIsEnabled())
{
TD.CreateWorkflowServiceHostStop();
}
this.workflowServiceHostPerformanceCounters = new WorkflowServiceHostPerformanceCounters(this);
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DefaultParametersShouldNotBeUsed, Justification = "Temporary suppression - to be addressed by DCR 127467")]
public ServiceEndpoint AddServiceEndpoint(XName serviceContractName, Binding binding, string address,
Uri listenUri = null, string behaviorConfigurationName = null)
{
return AddServiceEndpoint(serviceContractName, binding, new Uri(address, UriKind.RelativeOrAbsolute), listenUri, behaviorConfigurationName);
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DefaultParametersShouldNotBeUsed, Justification = "Temporary suppression - to be addressed by DCR 127467")]
public ServiceEndpoint AddServiceEndpoint(XName serviceContractName, Binding binding, Uri address,
Uri listenUri = null, string behaviorConfigurationName = null)
{
if (binding == null)
{
throw FxTrace.Exception.ArgumentNull("binding");
}
if (address == null)
{
throw FxTrace.Exception.ArgumentNull("address");
}
Uri via = this.MakeAbsoluteUri(address, binding);
return AddServiceEndpointCore(serviceContractName, binding, new EndpointAddress(via), listenUri, behaviorConfigurationName);
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.DefaultParametersShouldNotBeUsed, Justification = "Temporary suppression - to be addressed by DCR 127467")]
ServiceEndpoint AddServiceEndpointCore(XName serviceContractName, Binding binding, EndpointAddress address,
Uri listenUri = null, string behaviorConfigurationName = null)
{
if (serviceContractName == null)
{
throw FxTrace.Exception.ArgumentNull("serviceContractName");
}
if (this.inferredContracts == null)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(
SR.ContractNotFoundInAddServiceEndpoint(serviceContractName.LocalName, serviceContractName.NamespaceName)));
}
ServiceEndpoint serviceEndpoint;
ContractDescription description;
ContractInferenceHelper.ProvideDefaultNamespace(ref serviceContractName);
if (this.inferredContracts.TryGetValue(serviceContractName, out description))
{
serviceEndpoint = new ServiceEndpoint(description, binding, address);
if (!string.IsNullOrEmpty(behaviorConfigurationName))
{
ConfigLoader.LoadChannelBehaviors(behaviorConfigurationName, null, serviceEndpoint.Behaviors);
}
}
else if (serviceContractName == mexContractXName) // Special case for mex endpoint
{
if (!this.Description.Behaviors.Contains(mexBehaviorType))
{
throw FxTrace.Exception.AsError(new InvalidOperationException(
SR.ServiceMetadataBehaviorNotFoundForServiceMetadataEndpoint(this.Description.Name)));
}
serviceEndpoint = new ServiceMetadataEndpoint(binding, address);
}
else
{
throw FxTrace.Exception.AsError(new InvalidOperationException(
SR.ContractNotFoundInAddServiceEndpoint(serviceContractName.LocalName, serviceContractName.NamespaceName)));
}
if (listenUri != null)
{
listenUri = base.MakeAbsoluteUri(listenUri, binding);
serviceEndpoint.ListenUri = listenUri;
}
base.Description.Endpoints.Add(serviceEndpoint);
if (TD.ServiceEndpointAddedIsEnabled())
{
TD.ServiceEndpointAdded(address.Uri.ToString(), binding.GetType().ToString(), serviceEndpoint.Contract.Name);
}
return serviceEndpoint;
}
// Duplicate public AddServiceEndpoint methods from the base class
// This is to ensure that base class methods with string are not hidden by derived class methods with XName
public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address)
{
return base.AddServiceEndpoint(implementedContract, binding, address);
}
public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address)
{
return base.AddServiceEndpoint(implementedContract, binding, address);
}
public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, string address, Uri listenUri)
{
return base.AddServiceEndpoint(implementedContract, binding, address, listenUri);
}
public new ServiceEndpoint AddServiceEndpoint(string implementedContract, Binding binding, Uri address, Uri listenUri)
{
return base.AddServiceEndpoint(implementedContract, binding, address, listenUri);
}
public override void AddServiceEndpoint(ServiceEndpoint endpoint)
{
if (!endpoint.IsSystemEndpoint)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CannotUseAddServiceEndpointOverloadForWorkflowServices));
}
base.AddServiceEndpoint(endpoint);
}
internal override void AddDefaultEndpoints(Binding defaultBinding, List<ServiceEndpoint> defaultEndpoints)
{
if (this.inferredContracts != null)
{
foreach (XName contractName in this.inferredContracts.Keys)
{
ServiceEndpoint endpoint = AddServiceEndpoint(contractName, defaultBinding, String.Empty);
ConfigLoader.LoadDefaultEndpointBehaviors(endpoint);
AddCorrelationQueryBehaviorToServiceEndpoint(endpoint);
defaultEndpoints.Add(endpoint);
}
}
}
[SuppressMessage(FxCop.Category.Design, FxCop.Rule.AvoidOutParameters, MessageId = "0#", Justification = "This is defined by the ServiceHost base class")]
protected override ServiceDescription CreateDescription(out IDictionary<string, ContractDescription> implementedContracts)
{
Fx.AssertAndThrow(this.serviceDefinition != null, "serviceDefinition is null");
this.activity = this.serviceDefinition.Body;
Dictionary<string, ContractDescription> result = new Dictionary<string, ContractDescription>();
// Note: We do not check whether this.inferredContracts == null || this.inferredContracts.Count == 0,
// because we need to support hosting workflow with zero contract.
this.inferredContracts = this.serviceDefinition.GetContractDescriptions();
if (this.inferredContracts != null)
{
foreach (ContractDescription contract in this.inferredContracts.Values)
{
if (!string.IsNullOrEmpty(contract.ConfigurationName))
{
if (result.ContainsKey(contract.ConfigurationName))
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.DifferentContractsSameConfigName));
}
result.Add(contract.ConfigurationName, contract);
}
}
}
implementedContracts = result;
// Currently, only WorkflowService has CorrelationQueries property
this.correlationQueries = this.serviceDefinition.CorrelationQueries;
ServiceDescription serviceDescription = this.serviceDefinition.GetEmptyServiceDescription();
serviceDescription.Behaviors.Add(new WorkflowServiceBehavior(this.workflowDefinitionProvider));
return serviceDescription;
}
void InitializeDescription(WorkflowService serviceDefinition, UriSchemeKeyedCollection baseAddresses)
{
Fx.Assert(serviceDefinition != null, "caller must verify");
this.serviceDefinition = serviceDefinition;
base.InitializeDescription(baseAddresses);
foreach (Endpoint endpoint in serviceDefinition.Endpoints)
{
if (endpoint.Binding == null)
{
string endpointName = ContractValidationHelper.GetErrorMessageEndpointName(endpoint.Name);
string contractName = ContractValidationHelper.GetErrorMessageEndpointServiceContractName(endpoint.ServiceContractName);
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.MissingBindingInEndpoint(endpointName, contractName)));
}
ServiceEndpoint serviceEndpoint = AddServiceEndpointCore(endpoint.ServiceContractName, endpoint.Binding,
endpoint.GetAddress(this), endpoint.ListenUri, endpoint.BehaviorConfigurationName);
if (!string.IsNullOrEmpty(endpoint.Name))
{
serviceEndpoint.Name = endpoint.Name;
}
serviceEndpoint.UnresolvedAddress = endpoint.AddressUri;
serviceEndpoint.UnresolvedListenUri = endpoint.ListenUri;
}
this.PersistTimeout = defaultPersistTimeout;
this.TrackTimeout = defaultTrackTimeout;
this.FilterResumeTimeout = defaultFilterResumeTimeout;
}
protected override void InitializeRuntime()
{
if (base.Description != null)
{
FixupEndpoints();
this.SetScopeName();
if (this.DurableInstancingOptions.ScopeName == null)
{
this.DurableInstancingOptions.ScopeName = XNamespace.Get(this.Description.Namespace).GetName(this.Description.Name);
}
}
base.InitializeRuntime();
this.WorkflowServiceHostPerformanceCounters.InitializePerformanceCounters();
this.ServiceName = XNamespace.Get(this.Description.Namespace).GetName(this.Description.Name);
// add a host-wide SendChannelCache (with default settings) if one doesn't exist
this.workflowExtensions.EnsureChannelCache();
// add a host-wide (free-threaded) CorrelationExtension based on our ServiceName
this.WorkflowExtensions.Add(new CorrelationExtension(this.DurableInstancingOptions.ScopeName));
this.WorkflowExtensions.MakeReadOnly();
// now calculate if IsLoadTransactionRequired
this.IsLoadTransactionRequired = WorkflowServiceInstance.IsLoadTransactionRequired(this);
if (this.serviceDefinition != null)
{
ValidateBufferedReceiveProperty();
this.serviceDefinition.ResetServiceDescription();
}
}
internal override void AfterInitializeRuntime(TimeSpan timeout)
{
this.durableInstanceManager.Open(timeout);
}
internal override IAsyncResult BeginAfterInitializeRuntime(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.durableInstanceManager.BeginOpen(timeout, callback, state);
}
internal override void EndAfterInitializeRuntime(IAsyncResult result)
{
this.durableInstanceManager.EndOpen(result);
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.OnClose(timeoutHelper.RemainingTime());
this.durableInstanceManager.Close(timeoutHelper.RemainingTime());
this.workflowServiceHostPerformanceCounters.Dispose();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new CloseAsyncResult(this, timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CloseAsyncResult.End(result);
}
protected override void OnAbort()
{
base.OnAbort();
this.durableInstanceManager.Abort();
this.workflowServiceHostPerformanceCounters.Dispose();
}
internal void FaultServiceHostIfNecessary(Exception exception)
{
if (exception is InstancePersistenceException && !(exception is InstancePersistenceCommandException))
{
this.Fault(exception);
}
}
IAsyncResult BeginHostClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return base.OnBeginClose(timeout, callback, state);
}
void EndHostClose(IAsyncResult result)
{
base.OnEndClose(result);
}
void AddCorrelationQueryBehaviorToServiceEndpoint(ServiceEndpoint serviceEndpoint)
{
Fx.Assert(serviceEndpoint != null, "Argument cannot be null!");
Fx.Assert(serviceEndpoint.Contract != null, "ServiceEndpoint must have a contract!");
Fx.Assert(this.serviceDefinition != null, "Missing WorkflowService!");
Fx.Assert(!serviceEndpoint.Behaviors.Contains(correlationQueryBehaviorType),
"ServiceEndpoint should not have CorrelationQueryBehavior before this point!");
XName endpointContractName = XName.Get(serviceEndpoint.Contract.Name, serviceEndpoint.Contract.Namespace);
Collection<CorrelationQuery> queries;
if (this.correlationQueries != null && this.correlationQueries.TryGetValue(endpointContractName, out queries))
{
// Filter out duplicate CorrelationQueries in the collection.
// Currently, we only do reference comparison and Where message filter comparison.
Collection<CorrelationQuery> uniqueQueries = new Collection<CorrelationQuery>();
foreach (CorrelationQuery correlationQuery in queries)
{
if (!uniqueQueries.Contains(correlationQuery))
{
uniqueQueries.Add(correlationQuery);
}
else
{
if (TD.DuplicateCorrelationQueryIsEnabled())
{
TD.DuplicateCorrelationQuery(correlationQuery.Where.ToString());
}
}
}
serviceEndpoint.Behaviors.Add(new CorrelationQueryBehavior(uniqueQueries) { ServiceContractName = endpointContractName });
}
else if (CorrelationQueryBehavior.BindingHasDefaultQueries(serviceEndpoint.Binding))
{
if (!serviceEndpoint.Behaviors.Contains(typeof(CorrelationQueryBehavior)))
{
serviceEndpoint.Behaviors.Add(new CorrelationQueryBehavior(new Collection<CorrelationQuery>()) { ServiceContractName = endpointContractName });
}
}
}
void FixupEndpoints()
{
Fx.Assert(this.Description != null, "ServiceDescription cannot be null");
Dictionary<Type, ContractDescription> contractDescriptionDictionary = new Dictionary<Type, ContractDescription>();
foreach (ServiceEndpoint serviceEndpoint in this.Description.Endpoints)
{
if (this.serviceDefinition.AllowBufferedReceive)
{
// All application-level endpoints need to support ReceiveContext
SetupReceiveContextEnabledAttribute(serviceEndpoint);
}
// Need to add CorrelationQueryBehavior here so that endpoints added from config are included.
// It is possible that some endpoints already have CorrelationQueryBehavior from
// the AddDefaultEndpoints code path. We should skip them.
if (!serviceEndpoint.Behaviors.Contains(correlationQueryBehaviorType))
{
AddCorrelationQueryBehaviorToServiceEndpoint(serviceEndpoint);
}
// Need to ensure that any WorkflowHostingEndpoints using the same contract type actually use the
// same contractDescription instance since this is required by WCF.
if (serviceEndpoint is WorkflowHostingEndpoint)
{
ContractDescription contract;
if (contractDescriptionDictionary.TryGetValue(serviceEndpoint.Contract.ContractType, out contract))
{
serviceEndpoint.Contract = contract;
}
else
{
contractDescriptionDictionary[serviceEndpoint.Contract.ContractType] = serviceEndpoint.Contract;
}
}
}
if (this.serviceDefinition.AllowBufferedReceive && !this.Description.Behaviors.Contains(bufferedReceiveServiceBehaviorType))
{
this.Description.Behaviors.Add(new BufferedReceiveServiceBehavior());
}
}
void SetScopeName()
{
VirtualPathExtension virtualPathExtension = this.Extensions.Find<VirtualPathExtension>();
if (virtualPathExtension != null)
{
// Web Hosted scenario
WorkflowHostingOptionsSection hostingOptions = (WorkflowHostingOptionsSection)ConfigurationManager.GetSection(ConfigurationStrings.WorkflowHostingOptionsSectionPath);
if (hostingOptions != null && hostingOptions.OverrideSiteName)
{
this.OverrideSiteName = hostingOptions.OverrideSiteName;
string fullVirtualPath = virtualPathExtension.VirtualPath.Substring(1);
fullVirtualPath = ("/" == virtualPathExtension.ApplicationVirtualPath) ? fullVirtualPath : virtualPathExtension.ApplicationVirtualPath + fullVirtualPath;
int index = fullVirtualPath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);
string virtualDirectoryPath = fullVirtualPath.Substring(0, index + 1);
this.DurableInstancingOptions.ScopeName = XName.Get(XmlConvert.EncodeLocalName(Path.GetFileName(virtualPathExtension.VirtualPath)),
string.Format(CultureInfo.InvariantCulture, "/{0}{1}", this.Description.Name, virtualDirectoryPath));
}
}
}
void SetupReceiveContextEnabledAttribute(ServiceEndpoint serviceEndpoint)
{
if (BufferedReceiveServiceBehavior.IsWorkflowEndpoint(serviceEndpoint))
{
foreach (OperationDescription operation in serviceEndpoint.Contract.Operations)
{
ReceiveContextEnabledAttribute behavior = operation.Behaviors.Find<ReceiveContextEnabledAttribute>();
if (behavior == null)
{
operation.Behaviors.Add(new ReceiveContextEnabledAttribute() { ManualControl = true });
}
else
{
behavior.ManualControl = true;
}
}
}
}
void ValidateBufferedReceiveProperty()
{
// Validate that the AttachedProperty is indeed being used when the behavior is also used
bool hasBehavior = this.Description.Behaviors.Contains(bufferedReceiveServiceBehaviorType);
if (hasBehavior && !this.serviceDefinition.AllowBufferedReceive)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.BufferedReceiveBehaviorUsedWithoutProperty));
}
}
// specialized WorkflowInstanceExtensionManager that can default in a SendMessageChannelCache
class WorkflowServiceHostExtensions : WorkflowInstanceExtensionManager
{
static Type SendReceiveExtensionType = typeof(SendReceiveExtension);
bool hasChannelCache;
public WorkflowServiceHostExtensions()
: base()
{
}
public override void Add<T>(Func<T> extensionCreationFunction)
{
ThrowIfNotSupported(typeof(T));
if (TypeHelper.AreTypesCompatible(typeof(T), typeof(SendMessageChannelCache)))
{
this.hasChannelCache = true;
}
base.Add<T>(extensionCreationFunction);
}
public override void Add(object singletonExtension)
{
ThrowIfNotSupported(singletonExtension.GetType());
if (singletonExtension is SendMessageChannelCache)
{
this.hasChannelCache = true;
}
base.Add(singletonExtension);
}
public void EnsureChannelCache()
{
if (!this.hasChannelCache)
{
Add(new SendMessageChannelCache());
this.hasChannelCache = true;
}
}
void ThrowIfNotSupported(Type type)
{
if (TypeHelper.AreTypesCompatible(type, SendReceiveExtensionType))
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.ExtensionTypeNotSupported(SendReceiveExtensionType.FullName)));
}
}
}
class CloseAsyncResult : AsyncResult
{
static AsyncCompletion handleDurableInstanceManagerEndClose = new AsyncCompletion(HandleDurableInstanceManagerEndClose);
static AsyncCompletion handleEndHostClose = new AsyncCompletion(HandleEndHostClose);
TimeoutHelper timeoutHelper;
WorkflowServiceHost host;
public CloseAsyncResult(WorkflowServiceHost host, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.timeoutHelper = new TimeoutHelper(timeout);
this.host = host;
if (CloseHost())
{
Complete(true);
}
}
bool CloseDurableInstanceManager()
{
IAsyncResult result = this.host.durableInstanceManager.BeginClose(
this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleDurableInstanceManagerEndClose), this);
return SyncContinue(result);
}
bool CloseHost()
{
IAsyncResult result = this.host.BeginHostClose(
this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleEndHostClose), this);
return SyncContinue(result);
}
static bool HandleDurableInstanceManagerEndClose(IAsyncResult result)
{
CloseAsyncResult thisPtr = (CloseAsyncResult)result.AsyncState;
thisPtr.host.durableInstanceManager.EndClose(result);
thisPtr.host.WorkflowServiceHostPerformanceCounters.Dispose();
return true;
}
static bool HandleEndHostClose(IAsyncResult result)
{
CloseAsyncResult thisPtr = (CloseAsyncResult)result.AsyncState;
thisPtr.host.EndHostClose(result);
return thisPtr.CloseDurableInstanceManager();
}
public static void End(IAsyncResult result)
{
AsyncResult.End<CloseAsyncResult>(result);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Services.Connectors.Friends;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.InstantMessage;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Server.Base;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using OpenMetaverse;
using log4net;
using Nini.Config;
namespace OpenSim.Services.HypergridService
{
/// <summary>
/// Inter-grid IM
/// </summary>
public class HGInstantMessageService : IInstantMessage
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private const double CACHE_EXPIRATION_SECONDS = 120000.0; // 33 hours
static bool m_Initialized = false;
protected static IGridService m_GridService;
protected static IPresenceService m_PresenceService;
protected static IUserAgentService m_UserAgentService;
protected static IOfflineIMService m_OfflineIMService;
protected static IInstantMessageSimConnector m_IMSimConnector;
protected static Dictionary<UUID, object> m_UserLocationMap = new Dictionary<UUID, object>();
private static ExpiringCache<UUID, GridRegion> m_RegionCache;
private static bool m_ForwardOfflineGroupMessages;
private static bool m_InGatekeeper;
public HGInstantMessageService(IConfigSource config)
: this(config, null)
{
}
public HGInstantMessageService(IConfigSource config, IInstantMessageSimConnector imConnector)
{
if (imConnector != null)
m_IMSimConnector = imConnector;
if (!m_Initialized)
{
m_Initialized = true;
IConfig serverConfig = config.Configs["HGInstantMessageService"];
if (serverConfig == null)
throw new Exception(String.Format("No section HGInstantMessageService in config file"));
string gridService = serverConfig.GetString("GridService", String.Empty);
string presenceService = serverConfig.GetString("PresenceService", String.Empty);
string userAgentService = serverConfig.GetString("UserAgentService", String.Empty);
m_InGatekeeper = serverConfig.GetBoolean("InGatekeeper", false);
m_log.DebugFormat("[HG IM SERVICE]: Starting... InRobust? {0}", m_InGatekeeper);
if (gridService == string.Empty || presenceService == string.Empty)
throw new Exception(String.Format("Incomplete specifications, InstantMessage Service cannot function."));
Object[] args = new Object[] { config };
m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
m_UserAgentService = ServerUtils.LoadPlugin<IUserAgentService>(userAgentService, args);
m_RegionCache = new ExpiringCache<UUID, GridRegion>();
IConfig cnf = config.Configs["Messaging"];
if (cnf == null)
{
return;
}
m_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", false);
if (m_InGatekeeper)
{
string offlineIMService = cnf.GetString("OfflineIMService", string.Empty);
if (offlineIMService != string.Empty)
m_OfflineIMService = ServerUtils.LoadPlugin<IOfflineIMService>(offlineIMService, args);
}
}
}
public bool IncomingInstantMessage(GridInstantMessage im)
{
// m_log.DebugFormat("[HG IM SERVICE]: Received message from {0} to {1}", im.fromAgentID, im.toAgentID);
// UUID toAgentID = new UUID(im.toAgentID);
bool success = false;
if (m_IMSimConnector != null)
{
//m_log.DebugFormat("[XXX] SendIMToRegion local im connector");
success = m_IMSimConnector.SendInstantMessage(im);
}
else
{
success = TrySendInstantMessage(im, "", true, false);
}
if (!success && m_InGatekeeper) // we do this only in the Gatekeeper IM service
UndeliveredMessage(im);
return success;
}
public bool OutgoingInstantMessage(GridInstantMessage im, string url, bool foreigner)
{
// m_log.DebugFormat("[HG IM SERVICE]: Sending message from {0} to {1}@{2}", im.fromAgentID, im.toAgentID, url);
if (url != string.Empty)
return TrySendInstantMessage(im, url, true, foreigner);
else
{
PresenceInfo upd = new PresenceInfo();
upd.RegionID = UUID.Zero;
return TrySendInstantMessage(im, upd, true, foreigner);
}
}
protected bool TrySendInstantMessage(GridInstantMessage im, object previousLocation, bool firstTime, bool foreigner)
{
UUID toAgentID = new UUID(im.toAgentID);
PresenceInfo upd = null;
string url = string.Empty;
bool lookupAgent = false;
lock (m_UserLocationMap)
{
if (m_UserLocationMap.ContainsKey(toAgentID))
{
object o = m_UserLocationMap[toAgentID];
if (o is PresenceInfo)
upd = (PresenceInfo)o;
else if (o is string)
url = (string)o;
// We need to compare the current location with the previous
// or the recursive loop will never end because it will never try to lookup the agent again
if (!firstTime)
{
lookupAgent = true;
upd = null;
}
}
else
{
lookupAgent = true;
}
}
//m_log.DebugFormat("[XXX] Neeed lookup ? {0}", (lookupAgent ? "yes" : "no"));
// Are we needing to look-up an agent?
if (lookupAgent)
{
// Non-cached user agent lookup.
PresenceInfo[] presences = m_PresenceService.GetAgents(new string[] { toAgentID.ToString() });
if (presences != null && presences.Length > 0)
{
foreach (PresenceInfo p in presences)
{
if (p.RegionID != UUID.Zero)
{
//m_log.DebugFormat("[XXX]: Found presence in {0}", p.RegionID);
upd = p;
break;
}
}
}
if (upd == null && !foreigner)
{
// Let's check with the UAS if the user is elsewhere
m_log.DebugFormat("[HG IM SERVICE]: User is not present. Checking location with User Agent service");
url = m_UserAgentService.LocateUser(toAgentID);
}
// check if we've tried this before..
// This is one way to end the recursive loop
//
if (!firstTime && ((previousLocation is PresenceInfo && upd != null && upd.RegionID == ((PresenceInfo)previousLocation).RegionID) ||
(previousLocation is string && upd == null && previousLocation.Equals(url))))
{
// m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
m_log.DebugFormat("[HG IM SERVICE]: Fail 2 {0} {1}", previousLocation, url);
return false;
}
}
if (upd != null)
{
// ok, the user is around somewhere. Let's send back the reply with "success"
// even though the IM may still fail. Just don't keep the caller waiting for
// the entire time we're trying to deliver the IM
return SendIMToRegion(upd, im, toAgentID, foreigner);
}
else if (url != string.Empty)
{
// ok, the user is around somewhere. Let's send back the reply with "success"
// even though the IM may still fail. Just don't keep the caller waiting for
// the entire time we're trying to deliver the IM
return ForwardIMToGrid(url, im, toAgentID, foreigner);
}
else if (firstTime && previousLocation is string && (string)previousLocation != string.Empty)
{
return ForwardIMToGrid((string)previousLocation, im, toAgentID, foreigner);
}
else
m_log.DebugFormat("[HG IM SERVICE]: Unable to locate user {0}", toAgentID);
return false;
}
bool SendIMToRegion(PresenceInfo upd, GridInstantMessage im, UUID toAgentID, bool foreigner)
{
bool imresult = false;
GridRegion reginfo = null;
if (!m_RegionCache.TryGetValue(upd.RegionID, out reginfo))
{
reginfo = m_GridService.GetRegionByUUID(UUID.Zero /*!!!*/, upd.RegionID);
if (reginfo != null)
m_RegionCache.AddOrUpdate(upd.RegionID, reginfo, CACHE_EXPIRATION_SECONDS);
}
if (reginfo != null)
{
imresult = InstantMessageServiceConnector.SendInstantMessage(reginfo.ServerURI, im);
}
else
{
m_log.DebugFormat("[HG IM SERVICE]: Failed to deliver message to {0}", reginfo.ServerURI);
return false;
}
if (imresult)
{
// IM delivery successful, so store the Agent's location in our local cache.
lock (m_UserLocationMap)
{
if (m_UserLocationMap.ContainsKey(toAgentID))
{
m_UserLocationMap[toAgentID] = upd;
}
else
{
m_UserLocationMap.Add(toAgentID, upd);
}
}
return true;
}
else
{
// try again, but lookup user this time.
// Warning, this must call the Async version
// of this method or we'll be making thousands of threads
// The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync
// The version that spawns the thread is SendGridInstantMessageViaXMLRPC
// This is recursive!!!!!
return TrySendInstantMessage(im, upd, false, foreigner);
}
}
bool ForwardIMToGrid(string url, GridInstantMessage im, UUID toAgentID, bool foreigner)
{
if (InstantMessageServiceConnector.SendInstantMessage(url, im))
{
// IM delivery successful, so store the Agent's location in our local cache.
lock (m_UserLocationMap)
{
if (m_UserLocationMap.ContainsKey(toAgentID))
{
m_UserLocationMap[toAgentID] = url;
}
else
{
m_UserLocationMap.Add(toAgentID, url);
}
}
return true;
}
else
{
// try again, but lookup user this time.
// This is recursive!!!!!
return TrySendInstantMessage(im, url, false, foreigner);
}
}
private bool UndeliveredMessage(GridInstantMessage im)
{
if (m_OfflineIMService == null)
return false;
if (im.dialog != (byte)InstantMessageDialog.MessageFromObject &&
im.dialog != (byte)InstantMessageDialog.MessageFromAgent &&
im.dialog != (byte)InstantMessageDialog.GroupNotice &&
im.dialog != (byte)InstantMessageDialog.GroupInvitation &&
im.dialog != (byte)InstantMessageDialog.InventoryOffered)
{
return false;
}
if (!m_ForwardOfflineGroupMessages)
{
if (im.dialog == (byte)InstantMessageDialog.GroupNotice ||
im.dialog == (byte)InstantMessageDialog.GroupInvitation)
return false;
}
// m_log.DebugFormat("[HG IM SERVICE]: Message saved");
string reason = string.Empty;
return m_OfflineIMService.StoreMessage(im, out reason);
}
}
}
| |
using System;
using System.Drawing;
using System.Windows.Forms;
namespace NHunspellComponent.SupportClasses
{
public class TextBoxAPIHelper
{
private const double anInch = 14.4;
public static int GetBaselineOffsetAtCharIndex(System.Windows.Forms.TextBoxBase tb, int index)
{
System.Windows.Forms.RichTextBox rtb = tb as RichTextBox;
if (rtb == null)
{
return tb.Font.Height;
}
int lineNumber = rtb.GetLineFromCharIndex(index);
int lineIndex =
NativeMethods.SendMessageInt(rtb.Handle, NativeMethods.EM_LINEINDEX, new IntPtr(lineNumber), IntPtr.Zero).
ToInt32();
int lineLength =
NativeMethods.SendMessageInt(rtb.Handle, NativeMethods.EM_LINELENGTH, new IntPtr(lineNumber), IntPtr.Zero).
ToInt32();
NativeMethods.CHARRANGE charRange;
charRange.cpMin = lineIndex;
charRange.cpMax = lineIndex + lineLength;
// charRange.cpMin = index;
// charRange.cpMax = index + 1;
NativeMethods.RECT rect;
rect.Top = 0;
rect.Bottom = (int) anInch;
rect.Left = 0;
rect.Right = 10000000; //(int)(rtb.Width * anInch + 20);
NativeMethods.RECT rectPage;
rectPage.Top = 0;
rectPage.Bottom = (int) anInch;
rectPage.Left = 0;
rectPage.Right = 10;//10000000; //(int)(rtb.Width * anInch + 20);
Graphics canvas = Graphics.FromHwnd(rtb.Handle);
IntPtr canvasHdc = canvas.GetHdc();
NativeMethods.FORMATRANGE formatRange;
formatRange.chrg = charRange;
formatRange.hdc = canvasHdc;
formatRange.hdcTarget = canvasHdc;
formatRange.rc = rect;
formatRange.rcPage = rectPage;
NativeMethods.SendMessage(rtb.Handle, NativeMethods.EM_FORMATRANGE, IntPtr.Zero, ref formatRange).ToInt32();
canvas.ReleaseHdc(canvasHdc);
canvas.Dispose();
return (int) ((formatRange.rc.Bottom - formatRange.rc.Top)/anInch);
}
/// <summary>
/// Returns the index of the character under the specified
/// point in the control, or the nearest character if there
/// is no character under the point.
/// </summary>
/// <param name="txt">The text box control to check.</param>
/// <param name="pt">The point to find the character for,
/// specified relative to the client area of the text box.</param>
/// <returns></returns>
internal static int CharFromPos(System.Windows.Forms.TextBoxBase txt, Point pt)
{
unchecked
{
// Convert the point into a DWord with horizontal position
// in the loword and vertical position in the hiword:
int xy = (pt.X & 0xFFFF) + ((pt.Y & 0xFFFF) << 16);
// Get the position from the text box.
int res =
NativeMethods.SendMessageInt(txt.Handle, NativeMethods.EM_CHARFROMPOS, IntPtr.Zero, new IntPtr(xy)).
ToInt32();
// the Platform SDK appears to be incorrect on this matter.
// the hiword is the line number and the loword is the index
// of the character on this line
int lineNumber = ((res & 0xFFFF) >> 16);
int charIndex = (res & 0xFFFF);
// Find the index of the first character on the line within
// the control:
int lineStartIndex = NativeMethods.SendMessageInt(txt.Handle, NativeMethods.EM_LINEINDEX,
new IntPtr(lineNumber), IntPtr.Zero).ToInt32();
// Return the combined index:
return lineStartIndex + charIndex;
}
}
/// <summary>
/// Returns the position of the specified character
/// </summary>
/// <param name="txt">The text box to find the character in.</param>
/// <param name="charIndex">The index of the character whose
/// position needs to be found.</param>
/// <returns>The position of the character relative to the client
/// area of the control.</returns>
internal static Point PosFromChar(System.Windows.Forms.TextBoxBase txt, int charIndex)
{
unchecked
{
int xy =
NativeMethods.SendMessageInt(txt.Handle, NativeMethods.EM_POSFROMCHAR, new IntPtr(charIndex), IntPtr.Zero)
.ToInt32();
return new Point(xy);
}
}
internal static int GetFirstVisibleLine(System.Windows.Forms.TextBoxBase txt)
{
return
NativeMethods.SendMessageInt(txt.Handle, NativeMethods.EM_GETFIRSTVISIBLELINE, IntPtr.Zero, IntPtr.Zero).
ToInt32();
}
// private constructor, methods are static
private TextBoxAPIHelper()
{
// intentionally left blank
}
}
}
/*internal static int GetTextWidthAtCharIndex(System.Windows.Forms.TextBoxBase tb, int index, int length)
{
System.Windows.Forms.RichTextBox rtb = tb as RichTextBox;
//TODO!
if (rtb == null) { return tb.Font.Height; }
NativeMethods.CHARRANGE charRange;
charRange.cpMin = index;
charRange.cpMax = index + length;
NativeMethods.RECT rect;
rect.Top = 0;
rect.Bottom = (int)anInch;
rect.Left = 0;
rect.Right = (int)(rtb.ClientSize.Width * anInch);
NativeMethods.RECT rectPage;
rectPage.Top = 0;
rectPage.Bottom = (int)anInch;
rectPage.Left = 0;
rectPage.Right = (int)(rtb.ClientSize.Width * anInch);
Graphics canvas = Graphics.FromHwnd(rtb.Handle);
IntPtr canvasHdc = canvas.GetHdc();
NativeMethods.FORMATRANGE formatRange;
formatRange.chrg = charRange;
formatRange.hdc = canvasHdc;
formatRange.hdcTarget = canvasHdc;
formatRange.rc = rect;
formatRange.rcPage = rectPage;
NativeMethods.SendMessage(rtb.Handle, NativeMethods.EM_FORMATRANGE, IntPtr.Zero, ref formatRange);
canvas.ReleaseHdc(canvasHdc);
canvas.Dispose();
return (int)((formatRange.rc.Right - formatRange.rc.Left) / anInch);
}
*/
/*
/// <summary>
/// Attempts to make the caret visible in a TextBox control.
/// This will not always succeed since the TextBox control
/// appears to destroy its caret fairly frequently.
/// </summary>
/// <param name="txt">The text box to show the caret in.</param>
internal static void ShowCaret(System.Windows.Forms.TextBox txt)
{
bool ret = false;
int iter = 0;
while (!ret && iter < 10)
{
ret = NativeMethods.ShowCaretAPI(txt.Handle);
iter++;
}
}
*/
/*
}
*/
/*
internal static int GetLineIndex(TextBoxBase txt, int line)
{
return NativeMethods.SendMessageInt(txt.Handle, 0xbb, new IntPtr(line), IntPtr.Zero).ToInt32();
}
*/
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Sample.WebApi.Areas.HelpPage.ModelDescriptions;
using Sample.WebApi.Areas.HelpPage.Models;
namespace Sample.WebApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.CompletionProviders.XmlDocCommentCompletion;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.Completion.CompletionProviders.XmlDocCommentCompletion
{
[ExportCompletionProvider("DocCommentCompletionProvider", LanguageNames.CSharp)]
internal partial class XmlDocCommentCompletionProvider : AbstractDocCommentCompletionProvider
{
public override bool IsCommitCharacter(CompletionItem completionItem, char ch, string textTypedSoFar)
{
if ((ch == '"' || ch == ' ')
&& completionItem.DisplayText.Contains(ch))
{
return false;
}
return CompletionUtilities.IsCommitCharacter(completionItem, ch, textTypedSoFar) || ch == '>' || ch == '\t';
}
public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options)
{
return text[characterPosition] == '<';
}
public override bool SendEnterThroughToEditor(CompletionItem completionItem, string textTypedSoFar)
{
return false;
}
protected override async Task<IEnumerable<CompletionItem>> GetItemsWorkerAsync(Document document, int position, CompletionTriggerInfo triggerInfo, CancellationToken cancellationToken)
{
if (triggerInfo.IsDebugger)
{
return null;
}
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = tree.FindTokenOnLeftOfPosition(position, cancellationToken);
var parentTrivia = token.GetAncestor<DocumentationCommentTriviaSyntax>();
if (parentTrivia == null)
{
return null;
}
var items = new List<CompletionItem>();
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var span = CompletionUtilities.GetTextChangeSpan(text, position);
var attachedToken = parentTrivia.ParentTrivia.Token;
if (attachedToken.Kind() == SyntaxKind.None)
{
return null;
}
var semanticModel = await document.GetSemanticModelForNodeAsync(attachedToken.Parent, cancellationToken).ConfigureAwait(false);
ISymbol declaredSymbol = null;
var memberDeclaration = attachedToken.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null)
{
declaredSymbol = semanticModel.GetDeclaredSymbol(memberDeclaration, cancellationToken);
}
else
{
var typeDeclaration = attachedToken.GetAncestor<TypeDeclarationSyntax>();
if (typeDeclaration != null)
{
declaredSymbol = semanticModel.GetDeclaredSymbol(typeDeclaration, cancellationToken);
}
}
if (declaredSymbol != null)
{
items.AddRange(GetTagsForSymbol(declaredSymbol, span, parentTrivia, token));
}
if (token.Parent.Kind() == SyntaxKind.XmlEmptyElement || token.Parent.Kind() == SyntaxKind.XmlText ||
(token.Parent.IsKind(SyntaxKind.XmlElementEndTag) && token.IsKind(SyntaxKind.GreaterThanToken)) ||
(token.Parent.IsKind(SyntaxKind.XmlName) && token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement)))
{
if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement)
{
items.AddRange(GetNestedTags(span));
}
if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == "list")
{
items.AddRange(GetListItems(span));
}
if (token.Parent.IsParentKind(SyntaxKind.XmlEmptyElement) & token.Parent.Parent.IsParentKind(SyntaxKind.XmlElement))
{
var element = (XmlElementSyntax)token.Parent.Parent.Parent;
if (element.StartTag.Name.LocalName.ValueText == "list")
{
items.AddRange(GetListItems(span));
}
}
if (token.Parent.Parent.Kind() == SyntaxKind.XmlElement && ((XmlElementSyntax)token.Parent.Parent).StartTag.Name.LocalName.ValueText == "listheader")
{
items.AddRange(GetListHeaderItems(span));
}
if (token.Parent.Parent is DocumentationCommentTriviaSyntax)
{
items.AddRange(GetTopLevelSingleUseNames(parentTrivia, span));
items.AddRange(GetTopLevelRepeatableItems(span));
}
}
if (token.Parent.Kind() == SyntaxKind.XmlElementStartTag)
{
var startTag = (XmlElementStartTagSyntax)token.Parent;
if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == "list")
{
items.AddRange(GetListItems(span));
}
if (token == startTag.GreaterThanToken && startTag.Name.LocalName.ValueText == "listheader")
{
items.AddRange(GetListHeaderItems(span));
}
}
items.AddRange(GetAlwaysVisibleItems(span));
return items;
}
private IEnumerable<CompletionItem> GetTopLevelSingleUseNames(DocumentationCommentTriviaSyntax parentTrivia, TextSpan span)
{
var names = new HashSet<string>(new[] { "summary", "remarks", "example", "completionlist" });
RemoveExistingTags(parentTrivia, names, (x) => x.StartTag.Name.LocalName.ValueText);
return names.Select(n => GetItem(n, span));
}
private void RemoveExistingTags(DocumentationCommentTriviaSyntax parentTrivia, ISet<string> names, Func<XmlElementSyntax, string> selector)
{
if (parentTrivia != null)
{
foreach (var node in parentTrivia.Content)
{
var element = node as XmlElementSyntax;
if (element != null)
{
names.Remove(selector(element));
}
}
}
}
private IEnumerable<CompletionItem> GetTagsForSymbol(ISymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token)
{
if (symbol is IMethodSymbol)
{
return GetTagsForMethod((IMethodSymbol)symbol, filterSpan, trivia, token);
}
if (symbol is IPropertySymbol)
{
return GetTagsForProperty((IPropertySymbol)symbol, filterSpan, trivia);
}
if (symbol is INamedTypeSymbol)
{
return GetTagsForType((INamedTypeSymbol)symbol, filterSpan, trivia);
}
return SpecializedCollections.EmptyEnumerable<CompletionItem>();
}
private IEnumerable<CompletionItem> GetTagsForType(INamedTypeSymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia)
{
var items = new List<CompletionItem>();
var typeParameters = symbol.TypeParameters.Select(p => p.Name).ToSet();
RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, "typeparam"));
items.AddRange(typeParameters.Select(t => new XmlItem(this,
filterSpan,
FormatParameter("typeparam", t))));
return items;
}
private string AttributeSelector(XmlElementSyntax element, string attribute)
{
if (!element.StartTag.IsMissing && !element.EndTag.IsMissing)
{
var startTag = element.StartTag;
var nameAttribute = startTag.Attributes.OfType<XmlNameAttributeSyntax>().FirstOrDefault(a => a.Name.LocalName.ValueText == "name");
if (nameAttribute != null)
{
if (startTag.Name.LocalName.ValueText == attribute)
{
return nameAttribute.Identifier.Identifier.ValueText;
}
}
}
return null;
}
private IEnumerable<CompletionItem> GetTagsForProperty(IPropertySymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia)
{
var items = new List<CompletionItem>();
var typeParameters = symbol.GetTypeArguments().Select(p => p.Name).ToSet();
RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, "typeparam"));
items.AddRange(typeParameters.Select(t => new XmlItem(this, filterSpan, "typeparam", "name", t)));
items.Add(new XmlItem(this, filterSpan, "value"));
return items;
}
private IEnumerable<CompletionItem> GetTagsForMethod(IMethodSymbol symbol, TextSpan filterSpan, DocumentationCommentTriviaSyntax trivia, SyntaxToken token)
{
var items = new List<CompletionItem>();
var parameters = symbol.GetParameters().Select(p => p.Name).ToSet();
var typeParameters = symbol.TypeParameters.Select(t => t.Name).ToSet();
// User is trying to write a name, try to suggest only names.
if (token.Parent.IsKind(SyntaxKind.XmlNameAttribute) ||
(token.Parent.IsKind(SyntaxKind.IdentifierName) && token.Parent.IsParentKind(SyntaxKind.XmlNameAttribute)))
{
string parentElementName = null;
var emptyElement = token.GetAncestor<XmlEmptyElementSyntax>();
if (emptyElement != null)
{
parentElementName = emptyElement.Name.LocalName.Text;
}
// We're writing the name of a paramref or typeparamref
if (parentElementName == "paramref")
{
items.AddRange(parameters.Select(p => new XmlItem(this, filterSpan, p)));
}
else if (parentElementName == "typeparamref")
{
items.AddRange(typeParameters.Select(t => new XmlItem(this, filterSpan, t)));
}
return items;
}
var returns = true;
RemoveExistingTags(trivia, parameters, x => AttributeSelector(x, "param"));
RemoveExistingTags(trivia, typeParameters, x => AttributeSelector(x, "typeparam"));
foreach (var node in trivia.Content)
{
var element = node as XmlElementSyntax;
if (element != null && !element.StartTag.IsMissing && !element.EndTag.IsMissing)
{
var startTag = element.StartTag;
if (startTag.Name.LocalName.ValueText == "returns")
{
returns = false;
break;
}
}
}
items.AddRange(parameters.Select(p => new XmlItem(this, filterSpan, FormatParameter("param", p))));
items.AddRange(typeParameters.Select(t => new XmlItem(this, filterSpan, FormatParameter("typeparam", t))));
if (returns && !symbol.ReturnsVoid)
{
items.Add(new XmlItem(this, filterSpan, "returns"));
}
return items;
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Filtering\Testing\Tcl\closedSplines.tcl
// output file is AVclosedSplines.cs
/// <summary>
/// The testing class derived from AVclosedSplines
/// </summary>
public class AVclosedSplinesClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVclosedSplines(String [] argv)
{
//Prefix Content is: ""
// get the interactor ui[]
// Now create the RenderWindow, Renderer and Interactor[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
math = new vtkMath();
numberOfInputPoints = 30;
aKSplineX = new vtkKochanekSpline();
aKSplineX.ClosedOn();
aKSplineY = new vtkKochanekSpline();
aKSplineY.ClosedOn();
aKSplineZ = new vtkKochanekSpline();
aKSplineZ.ClosedOn();
aCSplineX = new vtkCardinalSpline();
aCSplineX.ClosedOn();
aCSplineY = new vtkCardinalSpline();
aCSplineY.ClosedOn();
aCSplineZ = new vtkCardinalSpline();
aCSplineZ.ClosedOn();
// add some points[]
inputPoints = new vtkPoints();
x = -1.0;
y = -1.0;
z = 0.0;
aKSplineX.AddPoint((double)0,(double)x);
aKSplineY.AddPoint((double)0,(double)y);
aKSplineZ.AddPoint((double)0,(double)z);
aCSplineX.AddPoint((double)0,(double)x);
aCSplineY.AddPoint((double)0,(double)y);
aCSplineZ.AddPoint((double)0,(double)z);
inputPoints.InsertPoint((int)0,(double)x,(double)y,(double)z);
x = 1.0;
y = -1.0;
z = 0.0;
aKSplineX.AddPoint((double)1,(double)x);
aKSplineY.AddPoint((double)1,(double)y);
aKSplineZ.AddPoint((double)1,(double)z);
aCSplineX.AddPoint((double)1,(double)x);
aCSplineY.AddPoint((double)1,(double)y);
aCSplineZ.AddPoint((double)1,(double)z);
inputPoints.InsertPoint((int)1,(double)x,(double)y,(double)z);
x = 1.0;
y = 1.0;
z = 0.0;
aKSplineX.AddPoint((double)2,(double)x);
aKSplineY.AddPoint((double)2,(double)y);
aKSplineZ.AddPoint((double)2,(double)z);
aCSplineX.AddPoint((double)2,(double)x);
aCSplineY.AddPoint((double)2,(double)y);
aCSplineZ.AddPoint((double)2,(double)z);
inputPoints.InsertPoint((int)2,(double)x,(double)y,(double)z);
x = -1.0;
y = 1.0;
z = 0.0;
aKSplineX.AddPoint((double)3,(double)x);
aKSplineY.AddPoint((double)3,(double)y);
aKSplineZ.AddPoint((double)3,(double)z);
aCSplineX.AddPoint((double)3,(double)x);
aCSplineY.AddPoint((double)3,(double)y);
aCSplineZ.AddPoint((double)3,(double)z);
inputPoints.InsertPoint((int)3,(double)x,(double)y,(double)z);
inputData = new vtkPolyData();
inputData.SetPoints((vtkPoints)inputPoints);
balls = new vtkSphereSource();
balls.SetRadius((double).04);
balls.SetPhiResolution((int)10);
balls.SetThetaResolution((int)10);
glyphPoints = new vtkGlyph3D();
glyphPoints.SetInput((vtkDataObject)inputData);
glyphPoints.SetSource((vtkPolyData)balls.GetOutput());
glyphMapper = vtkPolyDataMapper.New();
glyphMapper.SetInputConnection((vtkAlgorithmOutput)glyphPoints.GetOutputPort());
glyph = new vtkActor();
glyph.SetMapper((vtkMapper)glyphMapper);
glyph.GetProperty().SetDiffuseColor((double) 1.0000, 0.3882, 0.2784 );
glyph.GetProperty().SetSpecular((double).3);
glyph.GetProperty().SetSpecularPower((double)30);
ren1.AddActor((vtkProp)glyph);
Kpoints = new vtkPoints();
Cpoints = new vtkPoints();
profileKData = new vtkPolyData();
profileCData = new vtkPolyData();
numberOfInputPoints = 5;
numberOfOutputPoints = 100;
offset = 1.0;
//method moved
fit();
lines = new vtkCellArray();
lines.InsertNextCell((int)numberOfOutputPoints);
i = 0;
while((i) < numberOfOutputPoints)
{
lines.InsertCellPoint((int)i);
i = i + 1;
}
profileKData.SetPoints((vtkPoints)Kpoints);
profileKData.SetLines((vtkCellArray)lines);
profileCData.SetPoints((vtkPoints)Cpoints);
profileCData.SetLines((vtkCellArray)lines);
profileKTubes = new vtkTubeFilter();
profileKTubes.SetNumberOfSides((int)8);
profileKTubes.SetInput((vtkDataObject)profileKData);
profileKTubes.SetRadius((double).01);
profileKMapper = vtkPolyDataMapper.New();
profileKMapper.SetInputConnection((vtkAlgorithmOutput)profileKTubes.GetOutputPort());
profileK = new vtkActor();
profileK.SetMapper((vtkMapper)profileKMapper);
profileK.GetProperty().SetDiffuseColor((double) 0.8900, 0.8100, 0.3400 );
profileK.GetProperty().SetSpecular((double).3);
profileK.GetProperty().SetSpecularPower((double)30);
ren1.AddActor((vtkProp)profileK);
profileCTubes = new vtkTubeFilter();
profileCTubes.SetNumberOfSides((int)8);
profileCTubes.SetInput((vtkDataObject)profileCData);
profileCTubes.SetRadius((double).01);
profileCMapper = vtkPolyDataMapper.New();
profileCMapper.SetInputConnection((vtkAlgorithmOutput)profileCTubes.GetOutputPort());
profileC = new vtkActor();
profileC.SetMapper((vtkMapper)profileCMapper);
profileC.GetProperty().SetDiffuseColor((double) 0.2000, 0.6300, 0.7900 );
profileC.GetProperty().SetSpecular((double).3);
profileC.GetProperty().SetSpecularPower((double)30);
ren1.AddActor((vtkProp)profileC);
ren1.ResetCamera();
ren1.GetActiveCamera().Dolly((double)1.5);
ren1.ResetCameraClippingRange();
renWin.SetSize((int)300,(int)300);
// render the image[]
//[]
iren.Initialize();
// prevent the tk window from showing up then start the event loop[]
//method moved
//method moved
//method moved
//method moved
//method moved
//method moved
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkMath math;
static int numberOfInputPoints;
static vtkKochanekSpline aKSplineX;
static vtkKochanekSpline aKSplineY;
static vtkKochanekSpline aKSplineZ;
static vtkCardinalSpline aCSplineX;
static vtkCardinalSpline aCSplineY;
static vtkCardinalSpline aCSplineZ;
static vtkPoints inputPoints;
static double x;
static double y;
static double z;
static vtkPolyData inputData;
static vtkSphereSource balls;
static vtkGlyph3D glyphPoints;
static vtkPolyDataMapper glyphMapper;
static vtkActor glyph;
static vtkPoints Kpoints;
static vtkPoints Cpoints;
static vtkPolyData profileKData;
static vtkPolyData profileCData;
static int numberOfOutputPoints;
static double offset;
static int i;
static double t;
static vtkCellArray lines;
static vtkTubeFilter profileKTubes;
static vtkPolyDataMapper profileKMapper;
static vtkActor profileK;
static vtkTubeFilter profileCTubes;
static vtkPolyDataMapper profileCMapper;
static vtkActor profileC;
static double bias;
static double tension;
static double Continuity;
/// <summary>
///A process translated from the tcl scripts
/// </summary>
public static void fit ( )
{
//Global Variable Declaration Skipped
Kpoints.Reset();
Cpoints.Reset();
i = 0;
while((i) < numberOfOutputPoints)
{
t = (numberOfInputPoints-offset)/(numberOfOutputPoints-1)*i;
Kpoints.InsertPoint((int)i,(double)aKSplineX.Evaluate((double)t),(double)aKSplineY.Evaluate((double)t),(double)aKSplineZ.Evaluate((double)t));
Cpoints.InsertPoint((int)i,(double)aCSplineX.Evaluate((double)t),(double)aCSplineY.Evaluate((double)t),(double)aCSplineZ.Evaluate((double)t));
i = i + 1;
}
profileKData.Modified();
profileCData.Modified();
}
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkMath Getmath()
{
return math;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmath(vtkMath toSet)
{
math = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int GetnumberOfInputPoints()
{
return numberOfInputPoints;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetnumberOfInputPoints(int toSet)
{
numberOfInputPoints = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkKochanekSpline GetaKSplineX()
{
return aKSplineX;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetaKSplineX(vtkKochanekSpline toSet)
{
aKSplineX = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkKochanekSpline GetaKSplineY()
{
return aKSplineY;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetaKSplineY(vtkKochanekSpline toSet)
{
aKSplineY = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkKochanekSpline GetaKSplineZ()
{
return aKSplineZ;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetaKSplineZ(vtkKochanekSpline toSet)
{
aKSplineZ = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCardinalSpline GetaCSplineX()
{
return aCSplineX;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetaCSplineX(vtkCardinalSpline toSet)
{
aCSplineX = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCardinalSpline GetaCSplineY()
{
return aCSplineY;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetaCSplineY(vtkCardinalSpline toSet)
{
aCSplineY = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCardinalSpline GetaCSplineZ()
{
return aCSplineZ;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetaCSplineZ(vtkCardinalSpline toSet)
{
aCSplineZ = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPoints GetinputPoints()
{
return inputPoints;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetinputPoints(vtkPoints toSet)
{
inputPoints = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Getx()
{
return x;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setx(double toSet)
{
x = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Gety()
{
return y;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sety(double toSet)
{
y = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Getz()
{
return z;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setz(double toSet)
{
z = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyData GetinputData()
{
return inputData;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetinputData(vtkPolyData toSet)
{
inputData = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkSphereSource Getballs()
{
return balls;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setballs(vtkSphereSource toSet)
{
balls = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkGlyph3D GetglyphPoints()
{
return glyphPoints;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetglyphPoints(vtkGlyph3D toSet)
{
glyphPoints = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetglyphMapper()
{
return glyphMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetglyphMapper(vtkPolyDataMapper toSet)
{
glyphMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getglyph()
{
return glyph;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setglyph(vtkActor toSet)
{
glyph = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPoints GetKpoints()
{
return Kpoints;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetKpoints(vtkPoints toSet)
{
Kpoints = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPoints GetCpoints()
{
return Cpoints;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetCpoints(vtkPoints toSet)
{
Cpoints = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyData GetprofileKData()
{
return profileKData;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetprofileKData(vtkPolyData toSet)
{
profileKData = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyData GetprofileCData()
{
return profileCData;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetprofileCData(vtkPolyData toSet)
{
profileCData = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int GetnumberOfOutputPoints()
{
return numberOfOutputPoints;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetnumberOfOutputPoints(int toSet)
{
numberOfOutputPoints = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Getoffset()
{
return offset;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setoffset(double toSet)
{
offset = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Geti()
{
return i;
}
///<summary> A Set Method for Static Variables </summary>
public static void Seti(int toSet)
{
i = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Gett()
{
return t;
}
///<summary> A Set Method for Static Variables </summary>
public static void Sett(double toSet)
{
t = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCellArray Getlines()
{
return lines;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setlines(vtkCellArray toSet)
{
lines = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTubeFilter GetprofileKTubes()
{
return profileKTubes;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetprofileKTubes(vtkTubeFilter toSet)
{
profileKTubes = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetprofileKMapper()
{
return profileKMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetprofileKMapper(vtkPolyDataMapper toSet)
{
profileKMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetprofileK()
{
return profileK;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetprofileK(vtkActor toSet)
{
profileK = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkTubeFilter GetprofileCTubes()
{
return profileCTubes;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetprofileCTubes(vtkTubeFilter toSet)
{
profileCTubes = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper GetprofileCMapper()
{
return profileCMapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetprofileCMapper(vtkPolyDataMapper toSet)
{
profileCMapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor GetprofileC()
{
return profileC;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetprofileC(vtkActor toSet)
{
profileC = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Getbias()
{
return bias;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setbias(double toSet)
{
bias = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Gettension()
{
return tension;
}
///<summary> A Set Method for Static Variables </summary>
public static void Settension(double toSet)
{
tension = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double GetContinuity()
{
return Continuity;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetContinuity(double toSet)
{
Continuity = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(math!= null){math.Dispose();}
if(aKSplineX!= null){aKSplineX.Dispose();}
if(aKSplineY!= null){aKSplineY.Dispose();}
if(aKSplineZ!= null){aKSplineZ.Dispose();}
if(aCSplineX!= null){aCSplineX.Dispose();}
if(aCSplineY!= null){aCSplineY.Dispose();}
if(aCSplineZ!= null){aCSplineZ.Dispose();}
if(inputPoints!= null){inputPoints.Dispose();}
if(inputData!= null){inputData.Dispose();}
if(balls!= null){balls.Dispose();}
if(glyphPoints!= null){glyphPoints.Dispose();}
if(glyphMapper!= null){glyphMapper.Dispose();}
if(glyph!= null){glyph.Dispose();}
if(Kpoints!= null){Kpoints.Dispose();}
if(Cpoints!= null){Cpoints.Dispose();}
if(profileKData!= null){profileKData.Dispose();}
if(profileCData!= null){profileCData.Dispose();}
if(lines!= null){lines.Dispose();}
if(profileKTubes!= null){profileKTubes.Dispose();}
if(profileKMapper!= null){profileKMapper.Dispose();}
if(profileK!= null){profileK.Dispose();}
if(profileCTubes!= null){profileCTubes.Dispose();}
if(profileCMapper!= null){profileCMapper.Dispose();}
if(profileC!= null){profileC.Dispose();}
}
}
//--- end of script --//
| |
namespace Post_Publisher.Data.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class InitialCreate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.PageComments",
c => new
{
Id = c.Guid(nullable: false),
Title = c.String(),
Content = c.String(),
Posted = c.DateTime(nullable: false),
Author_Id = c.String(maxLength: 128),
OriginalContent_Id = c.Guid(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.Author_Id)
.ForeignKey("dbo.Pages", t => t.OriginalContent_Id)
.Index(t => t.Author_Id)
.Index(t => t.OriginalContent_Id);
CreateTable(
"dbo.AspNetUsers",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Email = c.String(maxLength: 256),
EmailConfirmed = c.Boolean(nullable: false),
PasswordHash = c.String(),
SecurityStamp = c.String(),
PhoneNumber = c.String(),
PhoneNumberConfirmed = c.Boolean(nullable: false),
TwoFactorEnabled = c.Boolean(nullable: false),
LockoutEndDateUtc = c.DateTime(),
LockoutEnabled = c.Boolean(nullable: false),
AccessFailedCount = c.Int(nullable: false),
UserName = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.UserName, unique: true, name: "UserNameIndex");
CreateTable(
"dbo.AspNetUserClaims",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(nullable: false, maxLength: 128),
ClaimType = c.String(),
ClaimValue = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUserLogins",
c => new
{
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 128),
UserId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId })
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AspNetUserRoles",
c => new
{
UserId = c.String(nullable: false, maxLength: 128),
RoleId = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => new { t.UserId, t.RoleId })
.ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.UserId)
.Index(t => t.RoleId);
CreateTable(
"dbo.Pages",
c => new
{
Id = c.Guid(nullable: false),
Title = c.String(),
Posted = c.DateTime(nullable: false),
LastEdited = c.DateTime(nullable: false),
Content = c.String(),
Author_Id = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.Author_Id)
.Index(t => t.Author_Id);
CreateTable(
"dbo.PostComments",
c => new
{
Id = c.Guid(nullable: false),
Title = c.String(),
Content = c.String(),
Posted = c.DateTime(nullable: false),
Author_Id = c.String(maxLength: 128),
OriginalContent_Id = c.Guid(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.Author_Id)
.ForeignKey("dbo.Posts", t => t.OriginalContent_Id)
.Index(t => t.Author_Id)
.Index(t => t.OriginalContent_Id);
CreateTable(
"dbo.Posts",
c => new
{
Id = c.Guid(nullable: false),
Title = c.String(),
Posted = c.DateTime(nullable: false),
LastEdited = c.DateTime(nullable: false),
Content = c.String(),
Author_Id = c.String(maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AspNetUsers", t => t.Author_Id)
.Index(t => t.Author_Id);
CreateTable(
"dbo.PostTags",
c => new
{
Id = c.Int(nullable: false, identity: true),
Tag = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AspNetRoles",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.Index(t => t.Name, unique: true, name: "RoleNameIndex");
CreateTable(
"dbo.Settings",
c => new
{
Id = c.Guid(nullable: false),
BlogName = c.String(nullable: false),
BlogDescription = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.PostTagPosts",
c => new
{
PostTag_Id = c.Int(nullable: false),
Post_Id = c.Guid(nullable: false),
})
.PrimaryKey(t => new { t.PostTag_Id, t.Post_Id })
.ForeignKey("dbo.PostTags", t => t.PostTag_Id, cascadeDelete: true)
.ForeignKey("dbo.Posts", t => t.Post_Id, cascadeDelete: true)
.Index(t => t.PostTag_Id)
.Index(t => t.Post_Id);
}
public override void Down()
{
DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles");
DropForeignKey("dbo.PostTagPosts", "Post_Id", "dbo.Posts");
DropForeignKey("dbo.PostTagPosts", "PostTag_Id", "dbo.PostTags");
DropForeignKey("dbo.PostComments", "OriginalContent_Id", "dbo.Posts");
DropForeignKey("dbo.Posts", "Author_Id", "dbo.AspNetUsers");
DropForeignKey("dbo.PostComments", "Author_Id", "dbo.AspNetUsers");
DropForeignKey("dbo.PageComments", "OriginalContent_Id", "dbo.Pages");
DropForeignKey("dbo.Pages", "Author_Id", "dbo.AspNetUsers");
DropForeignKey("dbo.PageComments", "Author_Id", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers");
DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers");
DropIndex("dbo.PostTagPosts", new[] { "Post_Id" });
DropIndex("dbo.PostTagPosts", new[] { "PostTag_Id" });
DropIndex("dbo.AspNetRoles", "RoleNameIndex");
DropIndex("dbo.Posts", new[] { "Author_Id" });
DropIndex("dbo.PostComments", new[] { "OriginalContent_Id" });
DropIndex("dbo.PostComments", new[] { "Author_Id" });
DropIndex("dbo.Pages", new[] { "Author_Id" });
DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" });
DropIndex("dbo.AspNetUserRoles", new[] { "UserId" });
DropIndex("dbo.AspNetUserLogins", new[] { "UserId" });
DropIndex("dbo.AspNetUserClaims", new[] { "UserId" });
DropIndex("dbo.AspNetUsers", "UserNameIndex");
DropIndex("dbo.PageComments", new[] { "OriginalContent_Id" });
DropIndex("dbo.PageComments", new[] { "Author_Id" });
DropTable("dbo.PostTagPosts");
DropTable("dbo.Settings");
DropTable("dbo.AspNetRoles");
DropTable("dbo.PostTags");
DropTable("dbo.Posts");
DropTable("dbo.PostComments");
DropTable("dbo.Pages");
DropTable("dbo.AspNetUserRoles");
DropTable("dbo.AspNetUserLogins");
DropTable("dbo.AspNetUserClaims");
DropTable("dbo.AspNetUsers");
DropTable("dbo.PageComments");
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.BinaryAuthorization.V1Beta1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedSystemPolicyV1Beta1ClientTest
{
[xunit::FactAttribute]
public void GetSystemPolicyRequestObject()
{
moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SystemPolicyV1Beta1Client client = new SystemPolicyV1Beta1ClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetSystemPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSystemPolicyRequestObjectAsync()
{
moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SystemPolicyV1Beta1Client client = new SystemPolicyV1Beta1ClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetSystemPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetSystemPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSystemPolicy()
{
moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SystemPolicyV1Beta1Client client = new SystemPolicyV1Beta1ClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetSystemPolicy(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSystemPolicyAsync()
{
moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SystemPolicyV1Beta1Client client = new SystemPolicyV1Beta1ClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetSystemPolicyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetSystemPolicyAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetSystemPolicyResourceNames()
{
moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
SystemPolicyV1Beta1Client client = new SystemPolicyV1Beta1ClientImpl(mockGrpcClient.Object, null);
Policy response = client.GetSystemPolicy(request.PolicyName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetSystemPolicyResourceNamesAsync()
{
moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client> mockGrpcClient = new moq::Mock<SystemPolicyV1Beta1.SystemPolicyV1Beta1Client>(moq::MockBehavior.Strict);
GetSystemPolicyRequest request = new GetSystemPolicyRequest
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
};
Policy expectedResponse = new Policy
{
PolicyName = PolicyName.FromProject("[PROJECT]"),
AdmissionWhitelistPatterns =
{
new AdmissionWhitelistPattern(),
},
ClusterAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
DefaultAdmissionRule = new AdmissionRule(),
UpdateTime = new wkt::Timestamp(),
Description = "description2cf9da67",
GlobalPolicyEvaluationMode = Policy.Types.GlobalPolicyEvaluationMode.Disable,
KubernetesServiceAccountAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
IstioServiceIdentityAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
KubernetesNamespaceAdmissionRules =
{
{
"key8a0b6e3c",
new AdmissionRule()
},
},
};
mockGrpcClient.Setup(x => x.GetSystemPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
SystemPolicyV1Beta1Client client = new SystemPolicyV1Beta1ClientImpl(mockGrpcClient.Object, null);
Policy responseCallSettings = await client.GetSystemPolicyAsync(request.PolicyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Policy responseCancellationToken = await client.GetSystemPolicyAsync(request.PolicyName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using Microsoft.SPOT;
using System;
using System.Threading;
using Microsoft.SPOT.Hardware;
using GTI = Gadgeteer.SocketInterfaces;
using GTM = Gadgeteer.Modules;
namespace Gadgeteer.Modules.GHIElectronics
{
/// <summary>A SerialCameraL1 module for Microsoft .NET Gadgeteer</summary>
public class SerialCameraL1 : GTM.Module
{
private const int CMD_DELAY_TIME = 50;
private const int RESET_DELAY_TIME = 1000;
private const int POWERUP_DELAY_TIME = 2000;
private GTI.Serial port;
private bool newImageReady;
private bool updateStreaming;
private bool paused;
private byte[] imageData;
private int dataSize;
private Thread worker;
private Resolution resolution;
public event ImageAcquiredEvent ImageAcquired;
public delegate void ImageAcquiredEvent(Bitmap img);
/// <summary>Whether or not a new image is ready.</summary>
public bool NewImageReady
{
get
{
return this.newImageReady;
}
}
/// <summary>The image resolution</summary>
public Resolution ImageResolution
{
get
{
return this.resolution;
}
set
{
this.port.Write(0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x19, (byte)value);
Thread.Sleep(SerialCameraL1.CMD_DELAY_TIME);
byte[] received = this.ReadBytes();
if (!(received != null && received[0] == 0x76 && received[1] == 0x00 && received[2] == 0x31 && received[3] == 0x00 && received[4] == 0x00))
throw new InvalidOperationException("The resolution failed to set.");
this.resolution = value;
}
}
/// <summary>The possible resolutions.</summary>
public enum Resolution
{
/// <summary>640x480</summary>
VGA = 0x00,
/// <summary>320x240</summary>
QVGA = 0x11,
/// <summary>160x120</summary>
QQVGA = 0x22,
}
/// <summary>Constructs a new instance.</summary>
/// <param name="socketNumber">The socket that this module is plugged in to.</param>
public SerialCameraL1(int socketNumber)
{
Socket socket = Socket.GetSocket(socketNumber, true, this, null);
socket.EnsureTypeIsSupported('U', this);
this.port = GTI.SerialFactory.Create(socket, 115200, GTI.SerialParity.None, GTI.SerialStopBits.One, 8, GTI.HardwareFlowControl.NotRequired, this);
this.port.ReadTimeout = 500;
this.port.WriteTimeout = 500;
this.port.Open();
this.ResetCamera();
this.newImageReady = false;
this.updateStreaming = false;
this.paused = false;
}
/// <summary>Sets the ratio.</summary>
/// <param name="ratio">The ratio.</param>
/// <returns>Whether it was successful or not.</returns>
public bool SetRatio(byte ratio)
{
this.DiscardBuffers();
this.port.Write(0x56, 0x00, 0x31, 0x05, 0x04, 0x01, 0x00, 0x1A, ratio);
Thread.Sleep(SerialCameraL1.CMD_DELAY_TIME);
byte[] received = this.ReadBytes();
if (received != null && received.Length >= 5 && received[0] == 0x76 && received[1] == 0 && received[2] == 0x31 && received[3] == 0 && received[4] == 0x0)
{
this.ResetCamera();
return true;
}
return false;
}
/// <summary>Starts streaming from the device.</summary>
public void StartStreaming()
{
this.StopStreaming();
this.updateStreaming = true;
this.newImageReady = false;
this.paused = false;
this.worker = new Thread(this.UpdateStreaming);
this.worker.Start();
}
/// <summary>Stops streaming from the device.</summary>
public void StopStreaming()
{
this.updateStreaming = false;
this.newImageReady = false;
if (this.worker != null)
{
while (this.worker.IsAlive)
Thread.Sleep(SerialCameraL1.CMD_DELAY_TIME);
this.worker = null;
}
}
/// <summary>Pauses streaming from the device.</summary>
public void PauseStreaming()
{
this.paused = true;
}
/// <summary>Resumes streaming from the device.</summary>
public void ResumeStreaming()
{
this.paused = false;
}
public Bitmap TakePicture()
{
return ReadPictureFromCamera();
}
/// <summary>Returns the image data.</summary>
/// <returns>The image data.</returns>
public byte[] GetImageData()
{
if (this.newImageReady && this.imageData != null && this.imageData.Length > 0)
{
this.newImageReady = false;
return this.imageData;
}
return null;
}
/// <summary>Returns the image.</summary>
/// <returns>The image.</returns>
public Bitmap GetImage()
{
Bitmap bmp = null;
switch (this.resolution)
{
case Resolution.VGA: bmp = new Bitmap(640, 480); break;
case Resolution.QVGA: bmp = new Bitmap(320, 240); break;
case Resolution.QQVGA: bmp = new Bitmap(160, 120); break;
default: throw new InvalidOperationException("Invalid resolution specified.");
}
this.DrawImage(bmp);
return bmp;
}
//public Picture GetImage2()
//{
// if (this.newImageReady && this.imageData != null && this.imageData.Length > 0)
// {
// this.newImageReady = false;
// this.PauseStreaming();
// var image = new Picture(this.imageData, Picture.PictureEncoding.JPEG);
// this.ResumeStreaming();
// return image;
// }
// return null;
//}
/// <summary>Draws the image onto the bitmap.</summary>
/// <param name="bitmap">The bitmap to draw.</param>
private void DrawImage(Bitmap bitmap)
{
if (bitmap == null) throw new ArgumentNullException("bitmap");
if (bitmap.Width <= 0) throw new ArgumentOutOfRangeException("bitmap", "bitmap.Width must be positive.");
if (bitmap.Height <= 0) throw new ArgumentOutOfRangeException("bitmap", "bitmap.Height must be positive.");
if (this.newImageReady && this.imageData != null && this.imageData.Length > 0)
{
this.newImageReady = false;
//this.PauseStreaming();
var image = new Bitmap(this.imageData, Bitmap.BitmapImageType.Jpeg);
bitmap.DrawImage(0, 0, image, 0, 0, bitmap.Width, bitmap.Height);
//this.ResumeStreaming();
}
}
/// <summary>Draws the image onto the bitmap.</summary>
/// <param name="bitmap">The bitmap to draw.</param>
/// <param name="x">The x coordinate to draw at.</param>
/// <param name="y">The y coordinate to draw at.</param>
/// <param name="width">The width of the image to draw.</param>
/// <param name="height">The height of the image to draw.</param>
private void DrawImage(Bitmap bitmap, int x, int y, int width, int height)
{
if (bitmap == null) throw new ArgumentNullException("bitmap");
if (x < 0) throw new ArgumentOutOfRangeException("x", "x must be non-negative.");
if (y < 0) throw new ArgumentOutOfRangeException("y", "y must be non-negative.");
if (width <= 0) throw new ArgumentOutOfRangeException("width", "width must be positive.");
if (height <= 0) throw new ArgumentOutOfRangeException("height", "height must be positive.");
if (x + width > bitmap.Width) throw new ArgumentOutOfRangeException("bitmap", "x + width must be no more than bitmap.Width.");
if (y + height > bitmap.Height) throw new ArgumentOutOfRangeException("bitmap", "x + height must be no more than bitmap.Height.");
if (this.newImageReady && this.imageData != null && this.imageData.Length > 0)
{
this.newImageReady = false;
var image = new Bitmap(this.imageData, Bitmap.BitmapImageType.Jpeg);
bitmap.DrawImage(x, y, image, 0, 0, width, height);
}
}
private void DiscardBuffers()
{
this.port.DiscardInBuffer();
this.port.DiscardOutBuffer();
}
private byte[] ReadBytes()
{
int available = this.port.BytesToRead;
if (available <= 0)
return null;
byte[] buffer = new byte[available];
this.ReadBytes(buffer, 0, buffer.Length);
return buffer;
}
private void ReadBytes(byte[] buffer, int offset, int count)
{
int attempts = 0;
do
{
int read = this.port.Read(buffer, offset, count);
offset += read;
count -= read;
if (read == 0)
{
this.port.DiscardInBuffer();
if (attempts++ > 1)
throw new InvalidOperationException("Failed to read all of the bytes from the port.");
continue;
}
Thread.Sleep(1);
} while (count > 0);
}
private bool ResetCamera()
{
this.port.Write(0x56, 0x00, 0x26, 0x00);
Thread.Sleep(SerialCameraL1.RESET_DELAY_TIME);
var received = this.ReadBytes();
return received != null && received.Length > 0;
}
private bool StopFrameBufferControl()
{
this.DiscardBuffers();
this.port.Write(0x56, 0x00, 0x36, 0x01, 0x00);
Thread.Sleep(SerialCameraL1.CMD_DELAY_TIME);
byte[] received = this.ReadBytes();
return received != null && received.Length >= 4 && received[0] == 0x76 && received[1] == 0 && received[2] == 0x36 && received[3] == 0 && received[4] == 0;
}
private void ResumeToNextFrame()
{
this.DiscardBuffers();
this.port.Write(0x56, 0x00, 0x36, 0x01, 0x03);
this.ReadBytes(new byte[5], 0, 5);
}
private int GetFrameBufferLength()
{
this.DiscardBuffers();
this.port.Write(0x56, 0x00, 0x34, 0x01, 0x00);
Thread.Sleep(SerialCameraL1.CMD_DELAY_TIME);
int size = 0;
byte[] receive = this.ReadBytes();
if (receive != null && receive.Length >= 9 && receive[0] == 0x76 && receive[1] == 0 && receive[2] == 0x34 && receive[3] == 0 && receive[4] == 0x4)
size = receive[5] << 24 | receive[6] << 16 | receive[7] << 8 | receive[8];
return size;
}
private bool ReadFrameBuffer()
{
this.DiscardBuffers();
this.port.Write(0x56, 0x00, 0x32, 0x0C, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, (byte)(this.dataSize >> 24), (byte)(this.dataSize >> 16), (byte)(this.dataSize >> 8), (byte)(this.dataSize), 0x10, 0x00);
Thread.Sleep(10);
try
{
byte[] header = new byte[5];
this.ReadBytes(header, 0, 5);
this.ReadBytes(this.imageData, 0, this.dataSize);
this.ReadBytes(header, 0, 5);
}
catch
{
this.imageData = null;
return false;
}
if (this.imageData[0] == 0xFF && this.imageData[1] == 0xD8 && this.imageData[this.dataSize - 2] == 0xFF && this.imageData[this.dataSize - 1] == 0xD9)
return true;
this.imageData = null;
return false;
}
private void UpdateStreaming()
{
while (this.updateStreaming)
{
if (this.paused)
{
Thread.Sleep(10);continue;
}
ReadPictureFromCamera();
}
}
private Bitmap ReadPictureFromCamera()
{
Bitmap bitmap=null;
try
{
this.StopFrameBufferControl();
this.dataSize = this.GetFrameBufferLength();
if (this.dataSize > 0)
{
this.newImageReady = false;
this.imageData = null;
this.imageData = new byte[dataSize];
try
{
this.newImageReady = this.ReadFrameBuffer();
}
catch (InvalidOperationException)
{
this.newImageReady = false;
}
if (!this.newImageReady)
{
Debug.Print("Camera read failed. Resetting camera.");
this.ResetCamera();
}
else
{
if (updateStreaming)
{
this.PauseStreaming();
}
bitmap = GetImage();
if (ImageAcquired != null)
{
ImageAcquired(bitmap);
}
if (updateStreaming)
{
this.ResumeStreaming();
}
this.ResumeToNextFrame();
}
}
else
{
Debug.Print("Camera read buffer size read failed... Rebooting.");
PowerState.RebootDevice(true);
this.ResetCamera();
}
}
catch (Exception e)
{
Debug.Print("Error in SerialCameraL1. - " + e.Message + " " + e.StackTrace);
}
return bitmap;
}
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class Tutorial : MonoBehaviour
{
//FLAGS:
private bool finalTurn = false;
public const int NUM_PLAYERS = 2;
[HideInInspector]
public int numPlayers = NUM_PLAYERS;
public float turnSpeed = 20;
public float zoomSpeed = 20;
private GameObject[] squads;
//Attacking variables
[HideInInspector]
public List<GameObject> targetsInRange;
//DON'T HIDE LAYER MASKS: Uses inspector.
public LayerMask detectCover;
public LayerMask detectPartial;
public LayerMask detectWall;
[HideInInspector]
public Projector attackProj;
[HideInInspector]
public int selectedTargetIndex;
[HideInInspector]
public Projector changeUnit;
private int selectedSquadIndex = -1;
private Light selectedLight;
private Rigidbody selectedRB; //used to move selected squad
private Vector3 lightOffset = new Vector3(0, 2, 0);
private TurnStage currentStage = TurnStage.None;
private AttackType currentAttack = AttackType.Basic;
[HideInInspector]
public GameObject marker;
[HideInInspector]
public int currentPlayersTurn = 0;
private bool isRoundOver = false;
public bool isOtherRoundOver = false;
private ArrayList allSquads;//taken on init from LoadGame
private bool isTurn = false;
private static bool isRunning = false;
public static bool getIsRunning(){
return isRunning;
}
public NetworkLogic nLogic;
public NetworkView nLogicView;
public AudioSource[] sounds;
public AudioSource click;
public AudioSource move;
public AudioSource attack;
//used in updateUI
Canvas movCanvas;
Canvas comCanvas;
Canvas firstActCanvas;
Canvas secondActCanvas;
Canvas waitCanvas;
Canvas mainCanvas;
//called by loadgame
public void init()
{
sounds = GetComponents<AudioSource>();
click = sounds [0];
move = sounds [1];
attack = sounds [2];
movCanvas = GameObject.Find("MovementCanvas").GetComponent<Canvas>();
comCanvas = GameObject.Find("CombatCanvas").GetComponent<Canvas>();
firstActCanvas = GameObject.Find("FirstActionCanvas").GetComponent<Canvas>();
secondActCanvas = GameObject.Find("SecondActionCanvas").GetComponent<Canvas>();
//waitCanvas = GameObject.Find ("WaitingCanvas").GetComponent<Canvas> ();
//mainCanvas = GameObject.Find ("MainMenu").GetComponent<Canvas> ();
TutorialCombat.gameLogic = this;
marker = new GameObject();
marker.transform.position = Vector3.zero;
allSquads = GetComponent<TutorialLoad> ().getAllSquads();
selectedLight = GameObject.Find("SelectedLight").GetComponent<Light>();
if (selectedLight == null) throw new MissingReferenceException("Need SelectedLight");
targetsInRange = new List<GameObject>();
selectedTargetIndex = -1;
attackProj = GameObject.Find("AttackRadius").GetComponent<Projector>();
changeUnit = GameObject.Find("ChangeUnit").GetComponent<Projector>();
//needed for unit movement to work out, no one should fly away
Physics.IgnoreLayerCollision(LayerMask.NameToLayer("Squad"),LayerMask.NameToLayer("Squad"));
Physics.IgnoreLayerCollision(LayerMask.NameToLayer("Unit"),LayerMask.NameToLayer("Squad"));
Physics.IgnoreLayerCollision(LayerMask.NameToLayer("Unit"),LayerMask.NameToLayer("Unit"));
Physics.IgnoreLayerCollision(LayerMask.NameToLayer("Unit"), LayerMask.NameToLayer("PartialCover"));
Physics.IgnoreLayerCollision(LayerMask.NameToLayer("Squad"), LayerMask.NameToLayer("PartialCover"));
Physics.IgnoreLayerCollision(LayerMask.NameToLayer("PartialCover"), LayerMask.NameToLayer("Squad"));
Physics.IgnoreLayerCollision(LayerMask.NameToLayer("PartialCover"), LayerMask.NameToLayer("Unit"));
updateUI();
}
public void updateSquadList(string tag)
{
squads = GameObject.FindGameObjectsWithTag(tag);
selectedSquadIndex = 0;
selectNextAvailableSquad();
if (squads.Length == 0) throw new UnityException("Failed to find squad.");
getMainCamController ().setCameraTarget (squads [selectedSquadIndex].transform.position);
setLight();
}
private void setLight()
{
selectedLight.transform.position = squads[selectedSquadIndex].transform.position + lightOffset;
}
private void checkChangeSquad()
{
if (Input.GetButtonUp("R1"))
{
getSelectedManager().disableSelect();
selectNextAvailableSquad();
click.Play();
if (selectedRB != null) selectedRB.velocity = Vector3.zero;
//Camera.main.GetComponent<CameraController>().setCameraTarget(squads[selectedSquadIndex].transform.position);
}
if (Input.GetButtonUp("L1"))
{
getSelectedManager().disableSelect();
click.Play();
selectPrevAvailableSquad();
if (selectedRB != null) selectedRB.velocity = Vector3.zero;
//Camera.main.GetComponent<CameraController>().setCameraTarget(squads[selectedSquadIndex].transform.position);
}
selectedRB = squads[selectedSquadIndex].GetComponent<Rigidbody>();
if (selectedRB != null) selectedRB.velocity = Vector3.zero;
}
private CameraController getMainCamController(){
return Camera.main.GetComponent<CameraController> ();
}
private TutorialManager getSelectedManager()
{
return squads[selectedSquadIndex].GetComponent<TutorialManager>();
}
private void checkNewAction()
{
//start move
if (Input.GetAxis("DpadH") == -1)
{
if (getSelectedManager().numActions > 0)
{
move.Play();
changeUnit.enabled = false;
currentStage = TurnStage.Moving;
getSelectedManager().startMovement();
updateUI();
}
}
//start start combat
if (Input.GetAxis("DpadH") == 1)
{
if (getSelectedManager().numActions > 0)
{
attack.Play();
currentStage = TurnStage.Combat;
TutorialCombat.findTargets(selectedRB.gameObject);
updateUI();
}
}
}
private void selectNextAvailableSquad(){
for(int i =0; i<squads.Length; i++)
{
selectedSquadIndex++;
selectedSquadIndex%=squads.Length;
if(squads[selectedSquadIndex].activeInHierarchy && getSelectedManager().numActions>0)
{
Vector3 myPos = getSelectedManager().transform.position;
getMainCamController().setCameraTarget(squads[selectedSquadIndex].transform.position);
getSelectedManager().enableSelect();
//changeUnit.transform.position = new Vector3(myPos.x,9,myPos.z);
//changeUnit.transform.position.y = 9;
break;
}
}
}
private void selectPrevAvailableSquad(){
for(int i =0; i<squads.Length; i++)
{
selectedSquadIndex--;
if(selectedSquadIndex<0)selectedSquadIndex=squads.Length-1;
if(squads[selectedSquadIndex].activeInHierarchy && getSelectedManager().numActions>0)
{
Vector3 myPos = getSelectedManager().transform.position;
getMainCamController().setCameraTarget(squads[selectedSquadIndex].transform.position);
getSelectedManager().enableSelect();
//changeUnit.transform.position = new Vector3(myPos.x, 9, myPos.z);
break;
}
}
}
public void gameOver(int playerWinner)
{
Debug.Log("GAME OVER! PLAYER " + playerWinner + " victory!");
isRunning = false;
currentStage = TurnStage.None;
updateUI();
Application.LoadLevel("Sprint 2");
return;
}
public void checkStateEndOfAction()
{
TutorialCombat.reset();
currentAttack = AttackType.Basic;
getSelectedManager().disableSelect();
attackProj.enabled = false;
changeUnit.enabled = false;
if (GameObject.FindGameObjectsWithTag("Player0Squad").Length == 0)
{
gameOver(2);
return;
}
if (GameObject.FindGameObjectsWithTag("Player1Squad").Length == 0)
{
gameOver(1);
return;
}
if (getSelectedManager ().numActions == SquadManager.MAX_ACTIONS) {
currentStage = TurnStage.None;
}
else if(getSelectedManager ().numActions == 0) {
//getSelectedManager().nView.RPC("activeSquadColor", RPCMode.All, false);
getSelectedManager().activeSquadColor(false);
nextTurn();
}
else
currentStage = TurnStage.InBetween;
updateUI();
}
/// <summary>
/// Called by network logic to communicate who's turn it is
/// </summary>
/// <param name="turn"></param>
public void setTurn(bool turn)
{
isTurn = turn;
if (isTurn)
{
selectedLight.enabled = true;
if(isRunning)
selectNextAvailableSquad();
}
else if(selectedSquadIndex >= 0)
{
Debug.Log(selectedSquadIndex);
getSelectedManager().disableSelect();
}
updateUI();
}
float GetSquadAngle()
{
return 90 - Mathf.Rad2Deg * Mathf.Atan2(transform.forward.z, transform.forward.x); // Left handed CW. z = angle 0, x = angle 90
}
public bool hasActiveSquads()
{
foreach(GameObject g in allSquads)
{
if (g.GetComponent<TutorialManager>().numActions > 0 && g.activeInHierarchy)
{
Debug.Log("I still have squads left!");
if (Network.isServer)
Debug.Log("Client");
else if(Network.isClient)
Debug.Log("Server");
return true;
}
}
return false;
}
/// <summary>
/// Handles checking if the round is over and ending the last turn of the round
/// </summary>
/// <returns></returns>
bool checkRoundComplete()
{
if (!isRoundOver)
{
foreach (GameObject g in allSquads)
{
if (g.GetComponent<TutorialManager>().numActions > 0 && g.activeInHierarchy)
return isRoundOver = false;
}
//This is here so it is only called once per round
if (!isOtherRoundOver)
{
setTurn(false);
}
}
return isRoundOver = true;
}
public void nextTurn(){ //What happens if the last dude to go dies, but hasn't called end of round?
nextRound();
setTurn(true);
}
public void begin()
{
isRunning = true;
updateUI ();
}
//call at end of turn
public void nextRound()
{
foreach (GameObject g in allSquads)
{
if(g.activeInHierarchy)
g.GetComponent<TutorialManager>().resetActions();
}
isRoundOver = false;
isOtherRoundOver = false;
currentStage = TurnStage.None;
}
// Update is called once per frame
void Update()
{
if (!isRunning)
return;
if (squads == null || !isTurn)
{
//checkRound();
return;
}
if (squads.Length > 0)
{
if (currentStage == TurnStage.None)
{
//skip turn button
if (Input.GetButtonDown("Select")) { nextTurn(); }
if (isRoundOver) nextTurn();
checkChangeSquad();
checkNewAction();
}
else if (currentStage == TurnStage.InBetween)
{
checkNewAction();
}
else if (currentStage == TurnStage.Moving)
{
//if the squad is no longer moving (triggered if max distance is met)
if (!getSelectedManager().midMovement)
{
//if we have another action
if (getSelectedManager().numActions > 0)
{
currentStage = TurnStage.InBetween;
}
else currentStage = TurnStage.None;
}
//user undo
else if (Input.GetButtonDown("Circle")) //B
{
getSelectedManager().undoMove();
checkStateEndOfAction();
getMainCamController().setCameraTarget(squads[selectedSquadIndex].transform.position);
changeUnit.enabled = true;
}
//user ends early
else if (Input.GetButtonDown("Cross")) //A
{
getSelectedManager().endMovement();
changeUnit.enabled = true;
checkStateEndOfAction();
}
else
{
selectedRB = squads[selectedSquadIndex].GetComponent<Rigidbody>();
float v = Input.GetAxis("JoystickLV");
float h = Input.GetAxis("JoystickLH");
selectedRB.velocity = (Quaternion.Euler(0, getMainCamController().angle, 0) * new Vector3(h, 0, v).normalized) * 20;
getMainCamController().setCameraTarget(squads[selectedSquadIndex].transform.position,true);
attackProj.transform.position = new Vector3(getSelectedManager().transform.position.x, 9, getSelectedManager().transform.position.z);
}
}
else if (currentStage == TurnStage.Combat)
{
//TODO: enable combat in squad
//skip
if (Input.GetAxis("DpadV") == -1)
{
getSelectedManager().skipAction();
checkStateEndOfAction();
}
if (currentAttack == AttackType.Basic)
{
if (TutorialCombat.UpdateTarget(selectedRB.GetComponent<TutorialManager>())) //A
{
getMainCamController().freezeCamera (2);
Debug.Log("I shot someone!");
StartCoroutine(TutorialCombat.fightTarget(selectedRB.gameObject,getSelectedManager().getPower()));
getSelectedManager().skipAction();
checkStateEndOfAction();
updateUI();
}
if (Input.GetButtonDown("Circle")) //B
{
if (getSelectedManager().numActions == 2) currentStage = TurnStage.None;
if (getSelectedManager().numActions == 1) currentStage = TurnStage.InBetween;
//getSelectedManager().skipAction();
checkStateEndOfAction();
getMainCamController().setCameraTarget(squads[selectedSquadIndex].transform.position, true);
}
if (Input.GetButtonUp("Square"))
{
currentAttack = AttackType.Unit;
TutorialCombat.reset();
attackProj.enabled = false;
Debug.Log("Unit Ability");
getSelectedManager().unitAbility();
}
if (Input.GetButtonUp("Triangle"))
{
currentAttack = AttackType.Squad;
TutorialCombat.reset();
attackProj.enabled = false;
changeUnit.enabled = true;
getSelectedManager().squadAbility();
Debug.Log("Squad Ability");
}
}
else if(currentAttack == AttackType.Squad && getSelectedManager() != null) // && Input.GetButtonUp("Triangle")
{
getSelectedManager().squadAbilityUpdate();
}
//else if(currentAttack == AttackType.Unit && getSelectedManager() != null) // && Input.GetButtonUp("Square")
//{
// getSelectedManager().unitAbilityUpdate();
//}
if(Input.GetButtonUp("Circle")) //Reset to basic ability
{
currentAttack = AttackType.Basic;
TutorialCombat.findTargets(selectedRB.gameObject);
}
}
setLight();
}
}
public void updateUI(bool showNetScreen=false){
//waitCanvas.enabled = mainCanvas.enabled =
movCanvas.enabled = comCanvas.enabled = firstActCanvas.enabled = secondActCanvas.enabled = false;
if (showNetScreen)
showNetScreen = true;
else
{
if (isTurn && isRunning)
{
selectedLight.enabled = true;
switch (currentStage)
{
case TurnStage.Combat:
getSelectedManager().disableSelect();
comCanvas.enabled = true;
break;
case TurnStage.InBetween:
getSelectedManager().disableSelect();
secondActCanvas.enabled = true;
break;
case TurnStage.Moving:
getSelectedManager().disableSelect();
movCanvas.enabled = true;
break;
case TurnStage.None:
getSelectedManager().enableSelect();
firstActCanvas.enabled = true;
break;
}
}
else
{
changeUnit.enabled = false;
selectedLight.enabled = false;
//waitCanvas.enabled = true;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 AndByte()
{
var test = new SimpleBinaryOpTest__AndByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local 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__AndByte
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Byte);
private const int Op2ElementCount = VectorSize / sizeof(Byte);
private const int RetElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector256<Byte> _clsVar1;
private static Vector256<Byte> _clsVar2;
private Vector256<Byte> _fld1;
private Vector256<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte, Byte, Byte> _dataTable;
static SimpleBinaryOpTest__AndByte()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__AndByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte, Byte, Byte>(_data1, _data2, new Byte[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.And(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.And(
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.And(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.And(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr);
var result = Avx2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr));
var result = Avx2.And(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__AndByte();
var result = Avx2.And(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.And(_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(Vector256<Byte> left, Vector256<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, 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 = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
if ((byte)(left[0] & right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((byte)(left[i] & right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.And)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using OpenMetaverse;
using Aurora.Framework;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Serialize and deserialize scene objects.
/// </summary>
/// This should really be in Aurora.Framework.Serialization but this would mean circular dependency problems
/// right now - hopefully this isn't forever.
public class SceneObjectSerializer
{
/// <summary>
/// Restore this part from the serialized xml representation.
/// </summary>
/// <param name = "fromUserInventoryItemId">The inventory id from which this part came, if applicable</param>
/// <param name = "xmlReader"></param>
/// <returns></returns>
public static SceneObjectPart FromXml(XmlTextReader xmlReader, IRegistryCore scene)
{
SceneObjectPart part = Xml2ToSOP(xmlReader, scene);
// for tempOnRez objects, we have to fix the Expire date.
if ((part.Flags & PrimFlags.TemporaryOnRez) != 0) part.ResetExpire();
part.GenerateRotationalVelocityFromOmega(); //Fix the rotational velocity
return part;
}
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name = "serialization"></param>
/// <returns></returns>
public static SceneObjectGroup FromOriginalXmlFormat(string serialization, IRegistryCore scene)
{
return FromOriginalXmlFormat(UUID.Zero, serialization, scene);
}
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name = "serialization"></param>
/// <returns></returns>
public static SceneObjectGroup FromOriginalXmlFormat(UUID fromUserInventoryItemID, string xmlData,
IRegistryCore scene)
{
//MainConsole.Instance.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = Util.EnvironmentTickCount();
try
{
StringReader sr;
XmlTextReader reader;
XmlNodeList parts;
XmlDocument doc;
doc = new XmlDocument();
doc.LoadXml(xmlData);
parts = doc.GetElementsByTagName("RootPart");
IScene m_sceneForGroup = scene is IScene ? (IScene) scene : null;
SceneObjectGroup sceneObject;
if (parts.Count == 0)
{
sceneObject = FromXml2Format(xmlData, m_sceneForGroup);
if (sceneObject == null)
throw new Exception("Invalid Xml format - no root part");
else
return sceneObject;
}
sr = new StringReader(parts[0].InnerXml);
reader = new XmlTextReader(sr);
sceneObject = new SceneObjectGroup(FromXml(reader, scene), m_sceneForGroup, false);
sceneObject.RootPart.FromUserInventoryItemID = fromUserInventoryItemID;
reader.Close();
sr.Close();
parts = doc.GetElementsByTagName("Part");
for (int i = 0; i < parts.Count; i++)
{
sr = new StringReader(parts[i].InnerXml);
reader = new XmlTextReader(sr);
SceneObjectPart part = FromXml(reader, scene);
sceneObject.AddChild(part, part.LinkNum);
part.TrimPermissions();
part.StoreUndoState();
reader.Close();
sr.Close();
}
return sceneObject;
}
catch (Exception e)
{
MainConsole.Instance.ErrorFormat(
"[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData);
return null;
}
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name = "sceneObject"></param>
/// <returns></returns>
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
ToOriginalXmlFormat(sceneObject, writer);
}
return sw.ToString();
}
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name = "sceneObject"></param>
/// <returns></returns>
public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer)
{
//MainConsole.Instance.DebugFormat("[SERIALIZER]: Starting serialization of {0}", Name);
//int time = Util.EnvironmentTickCount();
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
writer.WriteStartElement(String.Empty, "RootPart", String.Empty);
ToXmlFormat(sceneObject.RootPart, writer);
writer.WriteEndElement();
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
SceneObjectPart[] parts = sceneObject.Parts;
#if (!ISWIN)
foreach (SceneObjectPart part in parts)
{
if (part.UUID != sceneObject.RootPart.UUID)
{
writer.WriteStartElement(String.Empty, "Part", String.Empty);
ToXmlFormat(part, writer);
writer.WriteEndElement();
}
}
#else
foreach (SceneObjectPart part in parts.Where(part => part.UUID != sceneObject.RootPart.UUID))
{
writer.WriteStartElement(String.Empty, "Part", String.Empty);
ToXmlFormat(part, writer);
writer.WriteEndElement();
}
#endif
writer.WriteEndElement(); // OtherParts
writer.WriteEndElement(); // SceneObjectGroup
//MainConsole.Instance.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0}, {1}ms", Name, Util.EnvironmentTickCount() - time);
}
protected static void ToXmlFormat(SceneObjectPart part, XmlTextWriter writer)
{
SOPToXml2(writer, part, new Dictionary<string, object>());
}
public static SceneObjectGroup FromXml2Format(string xmlData, IScene scene)
{
//MainConsole.Instance.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = Util.EnvironmentTickCount();
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(xmlData);
SceneObjectGroup grp = InternalFromXml2Format(doc, scene);
xmlData = null;
return grp;
}
catch (Exception e)
{
MainConsole.Instance.ErrorFormat("[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, xmlData);
return null;
}
finally
{
doc.RemoveAll();
doc = null;
}
}
public static SceneObjectGroup FromXml2Format(ref MemoryStream ms, IScene scene)
{
//MainConsole.Instance.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = Util.EnvironmentTickCount();
XmlDocument doc = new XmlDocument();
SceneObjectGroup grp = null;
try
{
doc.Load(ms);
grp = InternalFromXml2Format(doc, scene);
foreach(var c in grp.ChildrenList)
c.FinishedSerializingGenericProperties();
return grp;
}
catch (Exception e)
{
MainConsole.Instance.ErrorFormat("[SERIALIZER]: Deserialization of xml failed with {0}", e);
return grp;
}
finally
{
doc = null;
}
}
private static SceneObjectGroup InternalFromXml2Format(XmlDocument doc, IScene scene)
{
//MainConsole.Instance.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = Util.EnvironmentTickCount();
try
{
XmlNodeList parts = doc.GetElementsByTagName("SceneObjectPart");
if (parts.Count == 0)
{
MainConsole.Instance.ErrorFormat(
"[SERIALIZER]: Deserialization of xml failed: No SceneObjectPart nodes. xml was " + doc.Value);
return null;
}
StringReader sr = new StringReader(parts[0].OuterXml);
XmlTextReader reader = new XmlTextReader(sr);
SceneObjectGroup sceneObject = new SceneObjectGroup(FromXml(reader, scene), scene);
reader.Close();
sr.Close();
// Then deal with the rest
for (int i = 1; i < parts.Count; i++)
{
sr = new StringReader(parts[i].OuterXml);
reader = new XmlTextReader(sr);
SceneObjectPart part = FromXml(reader, scene);
sceneObject.AddChild(part, part.LinkNum);
part.StoreUndoState();
reader.Close();
sr.Close();
}
parts = null;
doc = null;
return sceneObject;
}
catch (Exception e)
{
MainConsole.Instance.ErrorFormat("[SERIALIZER]: Deserialization of xml failed with {0}. xml was {1}", e, doc.Value);
return null;
}
}
/// <summary>
/// Serialize a scene object to the 'xml2' format.
/// </summary>
/// <param name = "sceneObject"></param>
/// <returns></returns>
public static string ToXml2Format(SceneObjectGroup sceneObject)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
SOGToXml2(writer, sceneObject, new Dictionary<string, object>());
writer.Close();
}
string str = sw.ToString();
sw.Flush();
sw.Close();
return str;
}
}
/// <summary>
/// Serialize a scene object to the 'xml2' format.
/// </summary>
/// <param name = "sceneObject"></param>
/// <returns></returns>
public static byte[] ToBinaryXml2Format(SceneObjectGroup sceneObject)
{
using (MemoryStream sw = new MemoryStream())
{
using (StreamWriter wr = new StreamWriter(sw, Encoding.UTF8))
{
using (XmlTextWriter writer = new XmlTextWriter(wr))
{
SOGToXml2(writer, sceneObject, new Dictionary<string, object>());
}
return sw.ToArray();
}
}
}
#region manual serialization
#region Delegates
public delegate void SOPXmlProcessor(SceneObjectPart sop, XmlTextReader reader);
#endregion
private static readonly Dictionary<string, SOPXmlProcessor> m_SOPXmlProcessors =
new Dictionary<string, SOPXmlProcessor>();
private static readonly Dictionary<string, TaskInventoryXmlProcessor> m_TaskInventoryXmlProcessors =
new Dictionary<string, TaskInventoryXmlProcessor>();
private static readonly Dictionary<string, ShapeXmlProcessor> m_ShapeXmlProcessors =
new Dictionary<string, ShapeXmlProcessor>();
private static readonly Dictionary<string, Serialization> m_genericSerializers =
new Dictionary<string, Serialization>();
static SceneObjectSerializer()
{
#region SOPXmlProcessors initialization
m_SOPXmlProcessors.Add("AllowedDrop", ProcessAllowedDrop);
m_SOPXmlProcessors.Add("CreatorID", ProcessCreatorID);
m_SOPXmlProcessors.Add("CreatorData", ProcessCreatorData);
m_SOPXmlProcessors.Add("InventorySerial", ProcessInventorySerial);
m_SOPXmlProcessors.Add("TaskInventory", ProcessTaskInventory);
m_SOPXmlProcessors.Add("UUID", ProcessUUID);
m_SOPXmlProcessors.Add("LocalId", ProcessLocalId);
m_SOPXmlProcessors.Add("Name", ProcessName);
m_SOPXmlProcessors.Add("Material", ProcessMaterial);
m_SOPXmlProcessors.Add("PassTouch", ProcessPassTouch);
m_SOPXmlProcessors.Add("PassCollisions", ProcessPassCollisions);
m_SOPXmlProcessors.Add("ScriptAccessPin", ProcessScriptAccessPin);
m_SOPXmlProcessors.Add("GroupPosition", ProcessGroupPosition);
m_SOPXmlProcessors.Add("OffsetPosition", ProcessOffsetPosition);
m_SOPXmlProcessors.Add("RotationOffset", ProcessRotationOffset);
m_SOPXmlProcessors.Add("Velocity", ProcessVelocity);
//m_SOPXmlProcessors.Add("AngularVelocity", ProcessAngularVelocity);
m_SOPXmlProcessors.Add("Acceleration", ProcessAcceleration);
m_SOPXmlProcessors.Add("Description", ProcessDescription);
m_SOPXmlProcessors.Add("Color", ProcessColor);
m_SOPXmlProcessors.Add("Text", ProcessText);
m_SOPXmlProcessors.Add("SitName", ProcessSitName);
m_SOPXmlProcessors.Add("TouchName", ProcessTouchName);
m_SOPXmlProcessors.Add("LinkNum", ProcessLinkNum);
m_SOPXmlProcessors.Add("ClickAction", ProcessClickAction);
m_SOPXmlProcessors.Add("Shape", ProcessShape);
m_SOPXmlProcessors.Add("Scale", ProcessScale);
m_SOPXmlProcessors.Add("UpdateFlag", ProcessUpdateFlag);
m_SOPXmlProcessors.Add("SitTargetOrientation", ProcessSitTargetOrientation);
m_SOPXmlProcessors.Add("SitTargetPosition", ProcessSitTargetPosition);
m_SOPXmlProcessors.Add("SitTargetPositionLL", ProcessSitTargetPositionLL);
m_SOPXmlProcessors.Add("SitTargetOrientationLL", ProcessSitTargetOrientationLL);
m_SOPXmlProcessors.Add("ParentID", ProcessParentID);
m_SOPXmlProcessors.Add("CreationDate", ProcessCreationDate);
m_SOPXmlProcessors.Add("Category", ProcessCategory);
m_SOPXmlProcessors.Add("SalePrice", ProcessSalePrice);
m_SOPXmlProcessors.Add("ObjectSaleType", ProcessObjectSaleType);
m_SOPXmlProcessors.Add("OwnershipCost", ProcessOwnershipCost);
m_SOPXmlProcessors.Add("GroupID", ProcessGroupID);
m_SOPXmlProcessors.Add("OwnerID", ProcessOwnerID);
m_SOPXmlProcessors.Add("LastOwnerID", ProcessLastOwnerID);
m_SOPXmlProcessors.Add("BaseMask", ProcessBaseMask);
m_SOPXmlProcessors.Add("OwnerMask", ProcessOwnerMask);
m_SOPXmlProcessors.Add("GroupMask", ProcessGroupMask);
m_SOPXmlProcessors.Add("EveryoneMask", ProcessEveryoneMask);
m_SOPXmlProcessors.Add("NextOwnerMask", ProcessNextOwnerMask);
m_SOPXmlProcessors.Add("Flags", ProcessFlags);
m_SOPXmlProcessors.Add("CollisionSound", ProcessCollisionSound);
m_SOPXmlProcessors.Add("CollisionSoundVolume", ProcessCollisionSoundVolume);
m_SOPXmlProcessors.Add("MediaUrl", ProcessMediaUrl);
m_SOPXmlProcessors.Add("TextureAnimation", ProcessTextureAnimation);
m_SOPXmlProcessors.Add("ParticleSystem", ProcessParticleSystem);
m_SOPXmlProcessors.Add("PayPrice0", ProcessPayPrice0);
m_SOPXmlProcessors.Add("PayPrice1", ProcessPayPrice1);
m_SOPXmlProcessors.Add("PayPrice2", ProcessPayPrice2);
m_SOPXmlProcessors.Add("PayPrice3", ProcessPayPrice3);
m_SOPXmlProcessors.Add("PayPrice4", ProcessPayPrice4);
#endregion
#region TaskInventoryXmlProcessors initialization
m_TaskInventoryXmlProcessors.Add("AssetID", ProcessTIAssetID);
m_TaskInventoryXmlProcessors.Add("BasePermissions", ProcessTIBasePermissions);
m_TaskInventoryXmlProcessors.Add("CreationDate", ProcessTICreationDate);
m_TaskInventoryXmlProcessors.Add("CreatorID", ProcessTICreatorID);
m_TaskInventoryXmlProcessors.Add("CreatorData", ProcessTICreatorData);
m_TaskInventoryXmlProcessors.Add("Description", ProcessTIDescription);
m_TaskInventoryXmlProcessors.Add("EveryonePermissions", ProcessTIEveryonePermissions);
m_TaskInventoryXmlProcessors.Add("Flags", ProcessTIFlags);
m_TaskInventoryXmlProcessors.Add("GroupID", ProcessTIGroupID);
m_TaskInventoryXmlProcessors.Add("GroupPermissions", ProcessTIGroupPermissions);
m_TaskInventoryXmlProcessors.Add("InvType", ProcessTIInvType);
m_TaskInventoryXmlProcessors.Add("ItemID", ProcessTIItemID);
m_TaskInventoryXmlProcessors.Add("OldItemID", ProcessTIOldItemID);
m_TaskInventoryXmlProcessors.Add("LastOwnerID", ProcessTILastOwnerID);
m_TaskInventoryXmlProcessors.Add("Name", ProcessTIName);
m_TaskInventoryXmlProcessors.Add("NextPermissions", ProcessTINextPermissions);
m_TaskInventoryXmlProcessors.Add("OwnerID", ProcessTIOwnerID);
m_TaskInventoryXmlProcessors.Add("CurrentPermissions", ProcessTICurrentPermissions);
m_TaskInventoryXmlProcessors.Add("ParentID", ProcessTIParentID);
m_TaskInventoryXmlProcessors.Add("ParentPartID", ProcessTIParentPartID);
m_TaskInventoryXmlProcessors.Add("PermsGranter", ProcessTIPermsGranter);
m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask);
m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType);
m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged);
#endregion
#region ShapeXmlProcessors initialization
m_ShapeXmlProcessors.Add("ProfileCurve", ProcessShpProfileCurve);
m_ShapeXmlProcessors.Add("TextureEntry", ProcessShpTextureEntry);
m_ShapeXmlProcessors.Add("ExtraParams", ProcessShpExtraParams);
m_ShapeXmlProcessors.Add("PathBegin", ProcessShpPathBegin);
m_ShapeXmlProcessors.Add("PathCurve", ProcessShpPathCurve);
m_ShapeXmlProcessors.Add("PathEnd", ProcessShpPathEnd);
m_ShapeXmlProcessors.Add("PathRadiusOffset", ProcessShpPathRadiusOffset);
m_ShapeXmlProcessors.Add("PathRevolutions", ProcessShpPathRevolutions);
m_ShapeXmlProcessors.Add("PathScaleX", ProcessShpPathScaleX);
m_ShapeXmlProcessors.Add("PathScaleY", ProcessShpPathScaleY);
m_ShapeXmlProcessors.Add("PathShearX", ProcessShpPathShearX);
m_ShapeXmlProcessors.Add("PathShearY", ProcessShpPathShearY);
m_ShapeXmlProcessors.Add("PathSkew", ProcessShpPathSkew);
m_ShapeXmlProcessors.Add("PathTaperX", ProcessShpPathTaperX);
m_ShapeXmlProcessors.Add("PathTaperY", ProcessShpPathTaperY);
m_ShapeXmlProcessors.Add("PathTwist", ProcessShpPathTwist);
m_ShapeXmlProcessors.Add("PathTwistBegin", ProcessShpPathTwistBegin);
m_ShapeXmlProcessors.Add("PCode", ProcessShpPCode);
m_ShapeXmlProcessors.Add("ProfileBegin", ProcessShpProfileBegin);
m_ShapeXmlProcessors.Add("ProfileEnd", ProcessShpProfileEnd);
m_ShapeXmlProcessors.Add("ProfileHollow", ProcessShpProfileHollow);
m_ShapeXmlProcessors.Add("Scale", ProcessShpScale);
m_ShapeXmlProcessors.Add("State", ProcessShpState);
m_ShapeXmlProcessors.Add("ProfileShape", ProcessShpProfileShape);
m_ShapeXmlProcessors.Add("HollowShape", ProcessShpHollowShape);
m_ShapeXmlProcessors.Add("SculptTexture", ProcessShpSculptTexture);
m_ShapeXmlProcessors.Add("SculptType", ProcessShpSculptType);
m_ShapeXmlProcessors.Add("SculptData", ProcessShpSculptData);
m_ShapeXmlProcessors.Add("FlexiSoftness", ProcessShpFlexiSoftness);
m_ShapeXmlProcessors.Add("FlexiTension", ProcessShpFlexiTension);
m_ShapeXmlProcessors.Add("FlexiDrag", ProcessShpFlexiDrag);
m_ShapeXmlProcessors.Add("FlexiGravity", ProcessShpFlexiGravity);
m_ShapeXmlProcessors.Add("FlexiWind", ProcessShpFlexiWind);
m_ShapeXmlProcessors.Add("FlexiForceX", ProcessShpFlexiForceX);
m_ShapeXmlProcessors.Add("FlexiForceY", ProcessShpFlexiForceY);
m_ShapeXmlProcessors.Add("FlexiForceZ", ProcessShpFlexiForceZ);
m_ShapeXmlProcessors.Add("LightColorR", ProcessShpLightColorR);
m_ShapeXmlProcessors.Add("LightColorG", ProcessShpLightColorG);
m_ShapeXmlProcessors.Add("LightColorB", ProcessShpLightColorB);
m_ShapeXmlProcessors.Add("LightColorA", ProcessShpLightColorA);
m_ShapeXmlProcessors.Add("LightRadius", ProcessShpLightRadius);
m_ShapeXmlProcessors.Add("LightCutoff", ProcessShpLightCutoff);
m_ShapeXmlProcessors.Add("LightFalloff", ProcessShpLightFalloff);
m_ShapeXmlProcessors.Add("LightIntensity", ProcessShpLightIntensity);
m_ShapeXmlProcessors.Add("FlexiEntry", ProcessShpFlexiEntry);
m_ShapeXmlProcessors.Add("LightEntry", ProcessShpLightEntry);
m_ShapeXmlProcessors.Add("SculptEntry", ProcessShpSculptEntry);
m_ShapeXmlProcessors.Add("Media", ProcessShpMedia);
#endregion
}
public static void AddSerializer(string Name, ISOPSerializerModule processor)
{
if (!m_SOPXmlProcessors.ContainsKey(Name))
{
m_SOPXmlProcessors.Add(Name, processor.Deserialization);
m_genericSerializers.Add(Name, processor.Serialization);
}
else
MainConsole.Instance.Warn("[SCENEOBJECTSERIALIZER]: Tried to add an additional SOP processor for " + Name);
}
public static void RemoveSerializer(string Name)
{
if (m_SOPXmlProcessors.ContainsKey(Name))
{
m_SOPXmlProcessors.Remove(Name);
m_genericSerializers.Remove(Name);
}
else
MainConsole.Instance.Warn("[SCENEOBJECTSERIALIZER]: Tried to remove a SOP processor for " + Name +
" that did not exist");
}
////////// Write /////////
public static void SOGToXml2(XmlTextWriter writer, SceneObjectGroup sog, Dictionary<string, object> options)
{
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
SOPToXml2(writer, sog.RootPart, options);
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
sog.ForEachPart(delegate(SceneObjectPart sop)
{
if (sop.UUID != sog.RootPart.UUID)
SOPToXml2(writer, sop, options);
});
writer.WriteEndElement();
writer.WriteEndElement();
}
public static void SOPToXml2(XmlTextWriter writer, SceneObjectPart sop, Dictionary<string, object> options)
{
writer.WriteStartElement("SceneObjectPart");
writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
writer.WriteElementString("AllowedDrop", sop.AllowedDrop.ToString().ToLower());
WriteUUID(writer, "CreatorID", sop.CreatorID, options);
if (!string.IsNullOrEmpty(sop.CreatorData))
writer.WriteElementString("CreatorData", sop.CreatorData);
else if (options.ContainsKey("profile"))
{
IUserManagement m_UserManagement = sop.ParentEntity.Scene.RequestModuleInterface<IUserManagement>();
string name = m_UserManagement.GetUserName(sop.CreatorID);
writer.WriteElementString("CreatorData", (string) options["profile"] + "/" + sop.CreatorID + ";" + name);
}
writer.WriteElementString("InventorySerial", sop.InventorySerial.ToString());
WriteTaskInventory(writer, sop.TaskInventory, options, sop.ParentEntity.Scene);
WriteUUID(writer, "UUID", sop.UUID, options);
writer.WriteElementString("LocalId", sop.LocalId.ToString());
writer.WriteElementString("Name", sop.Name);
writer.WriteElementString("Material", sop.Material.ToString());
writer.WriteElementString("PassTouch", sop.PassTouch.ToString());
writer.WriteElementString("PassCollisions", sop.PassCollisions.ToString());
writer.WriteElementString("ScriptAccessPin", sop.ScriptAccessPin.ToString());
WriteVector(writer, "GroupPosition", sop.GroupPosition);
WriteVector(writer, "OffsetPosition", sop.OffsetPosition);
WriteQuaternion(writer, "RotationOffset", sop.RotationOffset);
WriteVector(writer, "Velocity", sop.Velocity);
WriteVector(writer, "AngularVelocity", sop.AngularVelocity);
WriteVector(writer, "Acceleration", sop.Acceleration);
writer.WriteElementString("Description", sop.Description);
writer.WriteStartElement("Color");
writer.WriteElementString("R", sop.Color.R.ToString(Utils.EnUsCulture));
writer.WriteElementString("G", sop.Color.G.ToString(Utils.EnUsCulture));
writer.WriteElementString("B", sop.Color.B.ToString(Utils.EnUsCulture));
writer.WriteElementString("A", sop.Color.G.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
writer.WriteElementString("Text", sop.Text);
writer.WriteElementString("SitName", sop.SitName);
writer.WriteElementString("TouchName", sop.TouchName);
writer.WriteElementString("LinkNum", sop.LinkNum.ToString());
writer.WriteElementString("ClickAction", sop.ClickAction.ToString());
WriteShape(writer, sop.Shape, options);
WriteVector(writer, "Scale", sop.Scale);
writer.WriteElementString("UpdateFlag", ((byte) 0).ToString());
WriteQuaternion(writer, "SitTargetOrientation", sop.SitTargetOrientation);
WriteVector(writer, "SitTargetPosition", sop.SitTargetPosition);
WriteVector(writer, "SitTargetPositionLL", sop.SitTargetPositionLL);
WriteQuaternion(writer, "SitTargetOrientationLL", sop.SitTargetOrientationLL);
writer.WriteElementString("ParentID", sop.ParentID.ToString());
writer.WriteElementString("CreationDate", sop.CreationDate.ToString());
writer.WriteElementString("Category", sop.Category.ToString());
writer.WriteElementString("SalePrice", sop.SalePrice.ToString());
writer.WriteElementString("ObjectSaleType", sop.ObjectSaleType.ToString());
writer.WriteElementString("OwnershipCost", sop.OwnershipCost.ToString());
WriteUUID(writer, "GroupID", sop.GroupID, options);
WriteUUID(writer, "OwnerID", sop.OwnerID, options);
WriteUUID(writer, "LastOwnerID", sop.LastOwnerID, options);
writer.WriteElementString("BaseMask", sop.BaseMask.ToString());
writer.WriteElementString("OwnerMask", sop.OwnerMask.ToString());
writer.WriteElementString("GroupMask", sop.GroupMask.ToString());
writer.WriteElementString("EveryoneMask", sop.EveryoneMask.ToString());
writer.WriteElementString("NextOwnerMask", sop.NextOwnerMask.ToString());
writer.WriteElementString("Flags", sop.Flags.ToString());
WriteUUID(writer, "CollisionSound", sop.CollisionSound, options);
writer.WriteElementString("CollisionSoundVolume", sop.CollisionSoundVolume.ToString());
if (sop.MediaUrl != null)
writer.WriteElementString("MediaUrl", sop.MediaUrl);
WriteBytes(writer, "TextureAnimation", sop.TextureAnimation);
WriteBytes(writer, "ParticleSystem", sop.ParticleSystem);
writer.WriteElementString("PayPrice0", sop.PayPrice[0].ToString());
writer.WriteElementString("PayPrice1", sop.PayPrice[1].ToString());
writer.WriteElementString("PayPrice2", sop.PayPrice[2].ToString());
writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString());
writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString());
//Write the generic elements last
foreach (KeyValuePair<string, Serialization> kvp in m_genericSerializers)
{
writer.WriteElementString(kvp.Key, kvp.Value(sop));
}
writer.WriteEndElement();
}
private static void WriteUUID(XmlTextWriter writer, string name, UUID id, Dictionary<string, object> options)
{
writer.WriteStartElement(name);
writer.WriteElementString(options.ContainsKey("old-guids") ? "Guid" : "UUID", id.ToString());
writer.WriteEndElement();
}
private static void WriteVector(XmlTextWriter writer, string name, Vector3 vec)
{
writer.WriteStartElement(name);
writer.WriteElementString("X", vec.X.ToString(Utils.EnUsCulture));
writer.WriteElementString("Y", vec.Y.ToString(Utils.EnUsCulture));
writer.WriteElementString("Z", vec.Z.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
}
private static void WriteQuaternion(XmlTextWriter writer, string name, Quaternion quat)
{
writer.WriteStartElement(name);
writer.WriteElementString("X", quat.X.ToString(Utils.EnUsCulture));
writer.WriteElementString("Y", quat.Y.ToString(Utils.EnUsCulture));
writer.WriteElementString("Z", quat.Z.ToString(Utils.EnUsCulture));
writer.WriteElementString("W", quat.W.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
}
private static void WriteBytes(XmlTextWriter writer, string name, byte[] data)
{
writer.WriteStartElement(name);
byte[] d;
if (data != null)
d = data;
else
d = Utils.EmptyBytes;
writer.WriteBase64(d, 0, d.Length);
writer.WriteEndElement(); // name
}
private static void WriteTaskInventory(XmlTextWriter writer, TaskInventoryDictionary tinv,
Dictionary<string, object> options, IScene scene)
{
if (tinv.Count > 0) // otherwise skip this
{
writer.WriteStartElement("TaskInventory");
foreach (TaskInventoryItem item in tinv.Values)
{
writer.WriteStartElement("TaskInventoryItem");
WriteUUID(writer, "AssetID", item.AssetID, options);
writer.WriteElementString("BasePermissions", item.BasePermissions.ToString());
writer.WriteElementString("CreationDate", item.CreationDate.ToString());
WriteUUID(writer, "CreatorID", item.CreatorID, options);
if (!string.IsNullOrEmpty(item.CreatorData))
writer.WriteElementString("CreatorData", item.CreatorData);
else if (options.ContainsKey("profile"))
{
IUserManagement m_UserManagement = scene.RequestModuleInterface<IUserManagement>();
string name = m_UserManagement.GetUserName(item.CreatorID);
writer.WriteElementString("CreatorData",
(string) options["profile"] + "/" + item.CreatorID + ";" + name);
}
writer.WriteElementString("Description", item.Description);
writer.WriteElementString("EveryonePermissions", item.EveryonePermissions.ToString());
writer.WriteElementString("Flags", item.Flags.ToString());
WriteUUID(writer, "GroupID", item.GroupID, options);
writer.WriteElementString("GroupPermissions", item.GroupPermissions.ToString());
writer.WriteElementString("InvType", item.InvType.ToString());
WriteUUID(writer, "ItemID", item.ItemID, options);
WriteUUID(writer, "OldItemID", item.OldItemID, options);
WriteUUID(writer, "LastOwnerID", item.LastOwnerID, options);
writer.WriteElementString("Name", item.Name);
writer.WriteElementString("NextPermissions", item.NextPermissions.ToString());
WriteUUID(writer, "OwnerID", item.OwnerID, options);
writer.WriteElementString("CurrentPermissions", item.CurrentPermissions.ToString());
WriteUUID(writer, "ParentID", item.ParentID, options);
WriteUUID(writer, "ParentPartID", item.ParentPartID, options);
WriteUUID(writer, "PermsGranter", item.PermsGranter, options);
writer.WriteElementString("PermsMask", item.PermsMask.ToString());
writer.WriteElementString("Type", item.Type.ToString());
writer.WriteElementString("OwnerChanged", item.OwnerChanged.ToString().ToLower());
writer.WriteEndElement(); // TaskInventoryItem
}
writer.WriteEndElement(); // TaskInventory
}
}
private static void WriteShape(XmlTextWriter writer, PrimitiveBaseShape shp, Dictionary<string, object> options)
{
if (shp != null)
{
writer.WriteStartElement("Shape");
writer.WriteElementString("ProfileCurve", shp.ProfileCurve.ToString());
writer.WriteStartElement("TextureEntry");
byte[] te;
if (shp.TextureEntry != null)
te = shp.TextureEntry;
else
te = Utils.EmptyBytes;
writer.WriteBase64(te, 0, te.Length);
writer.WriteEndElement(); // TextureEntry
writer.WriteStartElement("ExtraParams");
byte[] ep;
if (shp.ExtraParams != null)
ep = shp.ExtraParams;
else
ep = Utils.EmptyBytes;
writer.WriteBase64(ep, 0, ep.Length);
writer.WriteEndElement(); // ExtraParams
writer.WriteElementString("PathBegin", shp.PathBegin.ToString());
writer.WriteElementString("PathCurve", shp.PathCurve.ToString());
writer.WriteElementString("PathEnd", shp.PathEnd.ToString());
writer.WriteElementString("PathRadiusOffset", shp.PathRadiusOffset.ToString());
writer.WriteElementString("PathRevolutions", shp.PathRevolutions.ToString());
writer.WriteElementString("PathScaleX", shp.PathScaleX.ToString());
writer.WriteElementString("PathScaleY", shp.PathScaleY.ToString());
writer.WriteElementString("PathShearX", shp.PathShearX.ToString());
writer.WriteElementString("PathShearY", shp.PathShearY.ToString());
writer.WriteElementString("PathSkew", shp.PathSkew.ToString());
writer.WriteElementString("PathTaperX", shp.PathTaperX.ToString());
writer.WriteElementString("PathTaperY", shp.PathTaperY.ToString());
writer.WriteElementString("PathTwist", shp.PathTwist.ToString());
writer.WriteElementString("PathTwistBegin", shp.PathTwistBegin.ToString());
writer.WriteElementString("PCode", shp.PCode.ToString());
writer.WriteElementString("ProfileBegin", shp.ProfileBegin.ToString());
writer.WriteElementString("ProfileEnd", shp.ProfileEnd.ToString());
writer.WriteElementString("ProfileHollow", shp.ProfileHollow.ToString());
writer.WriteElementString("State", shp.State.ToString());
writer.WriteElementString("ProfileShape", shp.ProfileShape.ToString());
writer.WriteElementString("HollowShape", shp.HollowShape.ToString());
WriteUUID(writer, "SculptTexture", shp.SculptTexture, options);
writer.WriteElementString("SculptType", shp.SculptType.ToString());
writer.WriteStartElement("SculptData");
byte[] sd;
//if (shp.SculptData != null)
sd = shp.ExtraParams;
//else
// sd = Utils.EmptyBytes;
if (sd != null) writer.WriteBase64(sd, 0, sd.Length);
writer.WriteEndElement(); // SculptData
writer.WriteElementString("FlexiSoftness", shp.FlexiSoftness.ToString());
writer.WriteElementString("FlexiTension", shp.FlexiTension.ToString());
writer.WriteElementString("FlexiDrag", shp.FlexiDrag.ToString());
writer.WriteElementString("FlexiGravity", shp.FlexiGravity.ToString());
writer.WriteElementString("FlexiWind", shp.FlexiWind.ToString());
writer.WriteElementString("FlexiForceX", shp.FlexiForceX.ToString());
writer.WriteElementString("FlexiForceY", shp.FlexiForceY.ToString());
writer.WriteElementString("FlexiForceZ", shp.FlexiForceZ.ToString());
writer.WriteElementString("LightColorR", shp.LightColorR.ToString());
writer.WriteElementString("LightColorG", shp.LightColorG.ToString());
writer.WriteElementString("LightColorB", shp.LightColorB.ToString());
writer.WriteElementString("LightColorA", shp.LightColorA.ToString());
writer.WriteElementString("LightRadius", shp.LightRadius.ToString());
writer.WriteElementString("LightCutoff", shp.LightCutoff.ToString());
writer.WriteElementString("LightFalloff", shp.LightFalloff.ToString());
writer.WriteElementString("LightIntensity", shp.LightIntensity.ToString());
writer.WriteElementString("FlexiEntry", shp.FlexiEntry.ToString().ToLower());
writer.WriteElementString("LightEntry", shp.LightEntry.ToString().ToLower());
writer.WriteElementString("SculptEntry", shp.SculptEntry.ToString().ToLower());
if (shp.Media != null)
writer.WriteElementString("Media", shp.Media.ToXml());
writer.WriteEndElement(); // Shape
}
}
//////// Read /////////
public static bool Xml2ToSOG(XmlTextReader reader, SceneObjectGroup sog)
{
reader.Read();
reader.ReadStartElement("SceneObjectGroup");
SceneObjectPart root = Xml2ToSOP(reader, sog.Scene);
if (root != null)
sog.SetRootPart(root);
else
{
return false;
}
if (sog.UUID == UUID.Zero)
sog.UUID = sog.RootPart.UUID;
reader.Read(); // OtherParts
while (!reader.EOF)
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.Name == "SceneObjectPart")
{
SceneObjectPart child = Xml2ToSOP(reader, sog.Scene);
if (child != null)
sog.AddChild(child, child.LinkNum);
}
else
{
//Logger.Log("Found unexpected prim XML element " + reader.Name, Helpers.LogLevel.Debug);
reader.Read();
}
break;
case XmlNodeType.EndElement:
default:
reader.Read();
break;
}
}
return true;
}
public static SceneObjectPart Xml2ToSOP(XmlTextReader reader, IRegistryCore scene)
{
SceneObjectPart obj = new SceneObjectPart(scene);
reader.ReadStartElement("SceneObjectPart");
string nodeName = string.Empty;
while (reader.Name != "SceneObjectPart")
{
nodeName = reader.Name;
SOPXmlProcessor p = null;
if (m_SOPXmlProcessors.TryGetValue(reader.Name, out p))
{
//MainConsole.Instance.DebugFormat("[XXX] Processing: {0}", reader.Name);
try
{
p(obj, reader);
}
catch (Exception e)
{
MainConsole.Instance.DebugFormat("[SceneObjectSerializer]: exception while parsing {0}: {1}", nodeName, e);
if (reader.NodeType == XmlNodeType.EndElement)
reader.Read();
}
}
else
{
// MainConsole.Instance.DebugFormat("[SceneObjectSerializer]: caught unknown element {0}", nodeName);
reader.ReadOuterXml(); // ignore
}
}
reader.ReadEndElement(); // SceneObjectPart
//MainConsole.Instance.DebugFormat("[XXX]: parsed SOP {0} - {1}", obj.Name, obj.UUID);
return obj;
}
private static UUID ReadUUID(XmlTextReader reader, string name)
{
UUID id;
string idStr;
reader.ReadStartElement(name);
idStr = reader.ReadElementString(reader.Name == "Guid" ? "Guid" : "UUID");
UUID.TryParse(idStr, out id);
reader.ReadEndElement();
return id;
}
private static Vector3 ReadVector(XmlTextReader reader, string name)
{
Vector3 vec;
reader.ReadStartElement(name);
vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
reader.ReadEndElement();
return vec;
}
private static Quaternion ReadQuaternion(XmlTextReader reader, string name)
{
Quaternion quat = new Quaternion();
reader.ReadStartElement(name);
while (reader.NodeType != XmlNodeType.EndElement)
{
switch (reader.Name.ToLower())
{
case "x":
quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
break;
case "y":
quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
break;
case "z":
quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
break;
case "w":
quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
break;
}
}
reader.ReadEndElement();
return quat;
}
private static TaskInventoryDictionary ReadTaskInventory(XmlTextReader reader, string name)
{
TaskInventoryDictionary tinv = new TaskInventoryDictionary();
reader.ReadStartElement(name, String.Empty);
if (reader.IsEmptyElement)
{
reader.Read();
return tinv;
}
while (reader.Name == "TaskInventoryItem")
{
reader.ReadStartElement("TaskInventoryItem", String.Empty); // TaskInventory
TaskInventoryItem item = new TaskInventoryItem();
while (reader.NodeType != XmlNodeType.EndElement)
{
TaskInventoryXmlProcessor p = null;
try
{
if (m_TaskInventoryXmlProcessors.TryGetValue(reader.Name, out p))
p(item, reader);
else
{
//MainConsole.Instance.DebugFormat("[SceneObjectSerializer]: caught unknown element in TaskInventory {0}, {1}", reader.Name, reader.Value);
reader.ReadOuterXml();
}
}
catch (Exception e)
{
MainConsole.Instance.DebugFormat("[SceneObjectSerializer]: exception while parsing Inventory Items {0}: {1}",
reader.Name, e);
}
}
reader.ReadEndElement(); // TaskInventoryItem
tinv.Add(item.ItemID, item);
}
if (reader.NodeType == XmlNodeType.EndElement)
reader.ReadEndElement(); // TaskInventory
return tinv;
}
private static PrimitiveBaseShape ReadShape(XmlTextReader reader, string name)
{
PrimitiveBaseShape shape = new PrimitiveBaseShape();
if (reader.IsEmptyElement)
{
reader.Read();
return shape;
}
reader.ReadStartElement(name, String.Empty); // Shape
string nodeName = string.Empty;
while (reader.NodeType != XmlNodeType.EndElement)
{
nodeName = reader.Name;
//MainConsole.Instance.DebugFormat("[XXX] Processing: {0}", reader.Name);
ShapeXmlProcessor p = null;
if (m_ShapeXmlProcessors.TryGetValue(reader.Name, out p))
{
try
{
p(shape, reader);
}
catch (Exception e)
{
MainConsole.Instance.DebugFormat("[SceneObjectSerializer]: exception while parsing Shape {0}: {1}", nodeName, e);
if (reader.NodeType == XmlNodeType.EndElement)
reader.Read();
}
}
else
{
// MainConsole.Instance.DebugFormat("[SceneObjectSerializer]: caught unknown element in Shape {0}", reader.Name);
reader.ReadOuterXml();
}
}
reader.ReadEndElement(); // Shape
return shape;
}
#region SOPXmlProcessors
private static void ProcessAllowedDrop(SceneObjectPart obj, XmlTextReader reader)
{
obj.AllowedDrop = reader.ReadElementContentAsBoolean("AllowedDrop", String.Empty);
}
private static void ProcessCreatorID(SceneObjectPart obj, XmlTextReader reader)
{
obj.CreatorID = ReadUUID(reader, "CreatorID");
}
private static void ProcessCreatorData(SceneObjectPart obj, XmlTextReader reader)
{
obj.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty);
}
private static void ProcessInventorySerial(SceneObjectPart obj, XmlTextReader reader)
{
obj.InventorySerial = uint.Parse(reader.ReadElementContentAsString("InventorySerial", String.Empty));
}
private static void ProcessTaskInventory(SceneObjectPart obj, XmlTextReader reader)
{
obj.TaskInventory = ReadTaskInventory(reader, "TaskInventory");
}
private static void ProcessUUID(SceneObjectPart obj, XmlTextReader reader)
{
obj.UUID = ReadUUID(reader, "UUID");
}
private static void ProcessLocalId(SceneObjectPart obj, XmlTextReader reader)
{
obj.LocalId = (uint) reader.ReadElementContentAsLong("LocalId", String.Empty);
}
private static void ProcessName(SceneObjectPart obj, XmlTextReader reader)
{
obj.Name = reader.ReadElementString("Name");
}
private static void ProcessMaterial(SceneObjectPart obj, XmlTextReader reader)
{
obj.Material = (byte) reader.ReadElementContentAsInt("Material", String.Empty);
}
private static void ProcessPassCollisions(SceneObjectPart obj, XmlTextReader reader)
{
obj.PassCollisions = reader.ReadElementContentAsInt("PassCollisions", String.Empty);
}
private static void ProcessPassTouch(SceneObjectPart obj, XmlTextReader reader)
{
obj.PassTouch = reader.ReadElementContentAsInt("PassTouch", String.Empty);
}
private static void ProcessScriptAccessPin(SceneObjectPart obj, XmlTextReader reader)
{
obj.ScriptAccessPin = reader.ReadElementContentAsInt("ScriptAccessPin", String.Empty);
}
private static void ProcessGroupPosition(SceneObjectPart obj, XmlTextReader reader)
{
obj.FixGroupPosition(ReadVector(reader, "GroupPosition"), false);
}
private static void ProcessOffsetPosition(SceneObjectPart obj, XmlTextReader reader)
{
obj.FixOffsetPosition(ReadVector(reader, "OffsetPosition"), true);
}
private static void ProcessRotationOffset(SceneObjectPart obj, XmlTextReader reader)
{
obj.RotationOffset = ReadQuaternion(reader, "RotationOffset");
}
private static void ProcessVelocity(SceneObjectPart obj, XmlTextReader reader)
{
obj.Velocity = ReadVector(reader, "Velocity");
}
private static void ProcessAngularVelocity(SceneObjectPart obj, XmlTextReader reader)
{
obj.AngularVelocity = ReadVector(reader, "AngularVelocity");
}
private static void ProcessAcceleration(SceneObjectPart obj, XmlTextReader reader)
{
obj.Acceleration = ReadVector(reader, "Acceleration");
}
private static void ProcessDescription(SceneObjectPart obj, XmlTextReader reader)
{
obj.Description = reader.ReadElementString("Description");
}
private static void ProcessColor(SceneObjectPart obj, XmlTextReader reader)
{
reader.ReadStartElement("Color");
if (reader.Name == "R")
{
float r = reader.ReadElementContentAsFloat("R", String.Empty);
float g = reader.ReadElementContentAsFloat("G", String.Empty);
float b = reader.ReadElementContentAsFloat("B", String.Empty);
float a = reader.ReadElementContentAsFloat("A", String.Empty);
obj.Color = Color.FromArgb((int) a, (int) r, (int) g, (int) b);
reader.ReadEndElement();
}
}
private static void ProcessText(SceneObjectPart obj, XmlTextReader reader)
{
obj.Text = reader.ReadElementString("Text", String.Empty);
}
private static void ProcessSitName(SceneObjectPart obj, XmlTextReader reader)
{
obj.SitName = reader.ReadElementString("SitName", String.Empty);
}
private static void ProcessTouchName(SceneObjectPart obj, XmlTextReader reader)
{
obj.TouchName = reader.ReadElementString("TouchName", String.Empty);
}
private static void ProcessLinkNum(SceneObjectPart obj, XmlTextReader reader)
{
obj.LinkNum = reader.ReadElementContentAsInt("LinkNum", String.Empty);
}
private static void ProcessClickAction(SceneObjectPart obj, XmlTextReader reader)
{
obj.ClickAction = (byte) reader.ReadElementContentAsInt("ClickAction", String.Empty);
}
private static void ProcessShape(SceneObjectPart obj, XmlTextReader reader)
{
obj.Shape = ReadShape(reader, "Shape");
}
private static void ProcessScale(SceneObjectPart obj, XmlTextReader reader)
{
obj.Scale = ReadVector(reader, "Scale");
}
private static void ProcessUpdateFlag(SceneObjectPart obj, XmlTextReader reader)
{
reader.Read();
//InternalUpdateFlags flags = (InternalUpdateFlags)(byte)reader.ReadElementContentAsInt("UpdateFlag", String.Empty);
}
private static void ProcessSitTargetOrientation(SceneObjectPart obj, XmlTextReader reader)
{
obj.SitTargetOrientation = ReadQuaternion(reader, "SitTargetOrientation");
}
private static void ProcessSitTargetPosition(SceneObjectPart obj, XmlTextReader reader)
{
obj.SitTargetPosition = ReadVector(reader, "SitTargetPosition");
}
private static void ProcessSitTargetPositionLL(SceneObjectPart obj, XmlTextReader reader)
{
obj.SitTargetPositionLL = ReadVector(reader, "SitTargetPositionLL");
}
private static void ProcessSitTargetOrientationLL(SceneObjectPart obj, XmlTextReader reader)
{
obj.SitTargetOrientationLL = ReadQuaternion(reader, "SitTargetOrientationLL");
}
private static void ProcessParentID(SceneObjectPart obj, XmlTextReader reader)
{
string str = reader.ReadElementContentAsString("ParentID", String.Empty);
obj.ParentID = Convert.ToUInt32(str);
}
private static void ProcessCreationDate(SceneObjectPart obj, XmlTextReader reader)
{
obj.CreationDate = reader.ReadElementContentAsInt("CreationDate", String.Empty);
}
private static void ProcessCategory(SceneObjectPart obj, XmlTextReader reader)
{
obj.Category = uint.Parse(reader.ReadElementContentAsString("Category", String.Empty));
}
private static void ProcessSalePrice(SceneObjectPart obj, XmlTextReader reader)
{
obj.SalePrice = reader.ReadElementContentAsInt("SalePrice", String.Empty);
}
private static void ProcessObjectSaleType(SceneObjectPart obj, XmlTextReader reader)
{
obj.ObjectSaleType = (byte) reader.ReadElementContentAsInt("ObjectSaleType", String.Empty);
}
private static void ProcessOwnershipCost(SceneObjectPart obj, XmlTextReader reader)
{
obj.OwnershipCost = reader.ReadElementContentAsInt("OwnershipCost", String.Empty);
}
private static void ProcessGroupID(SceneObjectPart obj, XmlTextReader reader)
{
obj.GroupID = ReadUUID(reader, "GroupID");
}
private static void ProcessOwnerID(SceneObjectPart obj, XmlTextReader reader)
{
obj.OwnerID = ReadUUID(reader, "OwnerID");
}
private static void ProcessLastOwnerID(SceneObjectPart obj, XmlTextReader reader)
{
obj.LastOwnerID = ReadUUID(reader, "LastOwnerID");
}
private static void ProcessBaseMask(SceneObjectPart obj, XmlTextReader reader)
{
obj.BaseMask = uint.Parse(reader.ReadElementContentAsString("BaseMask", String.Empty));
}
private static void ProcessOwnerMask(SceneObjectPart obj, XmlTextReader reader)
{
obj.OwnerMask = uint.Parse(reader.ReadElementContentAsString("OwnerMask", String.Empty));
}
private static void ProcessGroupMask(SceneObjectPart obj, XmlTextReader reader)
{
obj.GroupMask = uint.Parse(reader.ReadElementContentAsString("GroupMask", String.Empty));
}
private static void ProcessEveryoneMask(SceneObjectPart obj, XmlTextReader reader)
{
obj.EveryoneMask = uint.Parse(reader.ReadElementContentAsString("EveryoneMask", String.Empty));
}
private static void ProcessNextOwnerMask(SceneObjectPart obj, XmlTextReader reader)
{
obj.NextOwnerMask = uint.Parse(reader.ReadElementContentAsString("NextOwnerMask", String.Empty));
}
private static void ProcessFlags(SceneObjectPart obj, XmlTextReader reader)
{
string value = reader.ReadElementContentAsString("Flags", String.Empty);
// !!!!! to deal with flags without commas
if (value.Contains(" ") && !value.Contains(","))
value = value.Replace(" ", ", ");
obj.Flags = (PrimFlags) Enum.Parse(typeof (PrimFlags), value);
}
private static void ProcessCollisionSound(SceneObjectPart obj, XmlTextReader reader)
{
obj.CollisionSound = ReadUUID(reader, "CollisionSound");
}
private static void ProcessCollisionSoundVolume(SceneObjectPart obj, XmlTextReader reader)
{
obj.CollisionSoundVolume =
float.Parse(reader.ReadElementContentAsString("CollisionSoundVolume", String.Empty));
}
private static void ProcessMediaUrl(SceneObjectPart obj, XmlTextReader reader)
{
obj.MediaUrl = reader.ReadElementContentAsString("MediaUrl", String.Empty);
}
private static void ProcessTextureAnimation(SceneObjectPart obj, XmlTextReader reader)
{
obj.TextureAnimation =
Convert.FromBase64String(reader.ReadElementContentAsString("TextureAnimation", String.Empty));
}
private static void ProcessParticleSystem(SceneObjectPart obj, XmlTextReader reader)
{
obj.ParticleSystem =
Convert.FromBase64String(reader.ReadElementContentAsString("ParticleSystem", String.Empty));
}
private static void ProcessPayPrice0(SceneObjectPart obj, XmlTextReader reader)
{
obj.PayPrice[0] = int.Parse(reader.ReadElementContentAsString("PayPrice0", String.Empty));
}
private static void ProcessPayPrice1(SceneObjectPart obj, XmlTextReader reader)
{
obj.PayPrice[1] = int.Parse(reader.ReadElementContentAsString("PayPrice1", String.Empty));
}
private static void ProcessPayPrice2(SceneObjectPart obj, XmlTextReader reader)
{
obj.PayPrice[2] = int.Parse(reader.ReadElementContentAsString("PayPrice2", String.Empty));
}
private static void ProcessPayPrice3(SceneObjectPart obj, XmlTextReader reader)
{
obj.PayPrice[3] = int.Parse(reader.ReadElementContentAsString("PayPrice3", String.Empty));
}
private static void ProcessPayPrice4(SceneObjectPart obj, XmlTextReader reader)
{
obj.PayPrice[4] = int.Parse(reader.ReadElementContentAsString("PayPrice4", String.Empty));
}
#endregion
#region TaskInventoryXmlProcessors
private static void ProcessTIAssetID(TaskInventoryItem item, XmlTextReader reader)
{
item.AssetID = ReadUUID(reader, "AssetID");
}
private static void ProcessTIBasePermissions(TaskInventoryItem item, XmlTextReader reader)
{
item.BasePermissions = uint.Parse(reader.ReadElementContentAsString("BasePermissions", String.Empty));
}
private static void ProcessTICreationDate(TaskInventoryItem item, XmlTextReader reader)
{
item.CreationDate = uint.Parse(reader.ReadElementContentAsString("CreationDate", String.Empty));
}
private static void ProcessTICreatorID(TaskInventoryItem item, XmlTextReader reader)
{
item.CreatorID = ReadUUID(reader, "CreatorID");
}
private static void ProcessTICreatorData(TaskInventoryItem item, XmlTextReader reader)
{
item.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty);
}
private static void ProcessTIDescription(TaskInventoryItem item, XmlTextReader reader)
{
item.Description = reader.ReadElementContentAsString("Description", String.Empty);
}
private static void ProcessTIEveryonePermissions(TaskInventoryItem item, XmlTextReader reader)
{
item.EveryonePermissions = uint.Parse(reader.ReadElementContentAsString("EveryonePermissions", String.Empty));
}
private static void ProcessTIFlags(TaskInventoryItem item, XmlTextReader reader)
{
item.Flags = uint.Parse(reader.ReadElementContentAsString("Flags", String.Empty));
}
private static void ProcessTIGroupID(TaskInventoryItem item, XmlTextReader reader)
{
item.GroupID = ReadUUID(reader, "GroupID");
}
private static void ProcessTIGroupPermissions(TaskInventoryItem item, XmlTextReader reader)
{
item.GroupPermissions = uint.Parse(reader.ReadElementContentAsString("GroupPermissions", String.Empty));
}
private static void ProcessTIInvType(TaskInventoryItem item, XmlTextReader reader)
{
item.InvType = reader.ReadElementContentAsInt("InvType", String.Empty);
}
private static void ProcessTIItemID(TaskInventoryItem item, XmlTextReader reader)
{
item.ItemID = ReadUUID(reader, "ItemID");
}
private static void ProcessTIOldItemID(TaskInventoryItem item, XmlTextReader reader)
{
//Disable this, if we are rezzing from inventory, we want to get a new ItemID for next time
//item.OldItemID = ReadUUID (reader, "OldItemID");
ReadUUID(reader, "OldItemID");
}
private static void ProcessTILastOwnerID(TaskInventoryItem item, XmlTextReader reader)
{
item.LastOwnerID = ReadUUID(reader, "LastOwnerID");
}
private static void ProcessTIName(TaskInventoryItem item, XmlTextReader reader)
{
item.Name = reader.ReadElementContentAsString("Name", String.Empty);
}
private static void ProcessTINextPermissions(TaskInventoryItem item, XmlTextReader reader)
{
item.NextPermissions = uint.Parse(reader.ReadElementContentAsString("NextPermissions", String.Empty));
}
private static void ProcessTIOwnerID(TaskInventoryItem item, XmlTextReader reader)
{
item.OwnerID = ReadUUID(reader, "OwnerID");
}
private static void ProcessTICurrentPermissions(TaskInventoryItem item, XmlTextReader reader)
{
item.CurrentPermissions = uint.Parse(reader.ReadElementContentAsString("CurrentPermissions", String.Empty));
}
private static void ProcessTIParentID(TaskInventoryItem item, XmlTextReader reader)
{
item.ParentID = ReadUUID(reader, "ParentID");
}
private static void ProcessTIParentPartID(TaskInventoryItem item, XmlTextReader reader)
{
item.ParentPartID = ReadUUID(reader, "ParentPartID");
}
private static void ProcessTIPermsGranter(TaskInventoryItem item, XmlTextReader reader)
{
item.PermsGranter = ReadUUID(reader, "PermsGranter");
}
private static void ProcessTIPermsMask(TaskInventoryItem item, XmlTextReader reader)
{
item.PermsMask = reader.ReadElementContentAsInt("PermsMask", String.Empty);
}
private static void ProcessTIType(TaskInventoryItem item, XmlTextReader reader)
{
item.Type = reader.ReadElementContentAsInt("Type", String.Empty);
}
private static void ProcessTIOwnerChanged(TaskInventoryItem item, XmlTextReader reader)
{
item.OwnerChanged = reader.ReadElementContentAsBoolean("OwnerChanged", String.Empty);
}
#endregion
#region ShapeXmlProcessors
private static void ProcessShpProfileCurve(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.ProfileCurve = (byte) reader.ReadElementContentAsInt("ProfileCurve", String.Empty);
}
private static void ProcessShpTextureEntry(PrimitiveBaseShape shp, XmlTextReader reader)
{
byte[] teData = Convert.FromBase64String(reader.ReadElementString("TextureEntry"));
shp.Textures = new Primitive.TextureEntry(teData, 0, teData.Length);
}
private static void ProcessShpExtraParams(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.ExtraParams = Convert.FromBase64String(reader.ReadElementString("ExtraParams"));
}
private static void ProcessShpPathBegin(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathBegin = (ushort) reader.ReadElementContentAsInt("PathBegin", String.Empty);
}
private static void ProcessShpPathCurve(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathCurve = (byte) reader.ReadElementContentAsInt("PathCurve", String.Empty);
}
private static void ProcessShpPathEnd(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathEnd = (ushort) reader.ReadElementContentAsInt("PathEnd", String.Empty);
}
private static void ProcessShpPathRadiusOffset(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathRadiusOffset = (sbyte) reader.ReadElementContentAsInt("PathRadiusOffset", String.Empty);
}
private static void ProcessShpPathRevolutions(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathRevolutions = (byte) reader.ReadElementContentAsInt("PathRevolutions", String.Empty);
}
private static void ProcessShpPathScaleX(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathScaleX = (byte) reader.ReadElementContentAsInt("PathScaleX", String.Empty);
}
private static void ProcessShpPathScaleY(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathScaleY = (byte) reader.ReadElementContentAsInt("PathScaleY", String.Empty);
}
private static void ProcessShpPathShearX(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathShearX = (byte) reader.ReadElementContentAsInt("PathShearX", String.Empty);
}
private static void ProcessShpPathShearY(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathShearY = (byte) reader.ReadElementContentAsInt("PathShearY", String.Empty);
}
private static void ProcessShpPathSkew(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathSkew = (sbyte) reader.ReadElementContentAsInt("PathSkew", String.Empty);
}
private static void ProcessShpPathTaperX(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathTaperX = (sbyte) reader.ReadElementContentAsInt("PathTaperX", String.Empty);
}
private static void ProcessShpPathTaperY(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathTaperY = (sbyte) reader.ReadElementContentAsInt("PathTaperY", String.Empty);
}
private static void ProcessShpPathTwist(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathTwist = (sbyte) reader.ReadElementContentAsInt("PathTwist", String.Empty);
}
private static void ProcessShpPathTwistBegin(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PathTwistBegin = (sbyte) reader.ReadElementContentAsInt("PathTwistBegin", String.Empty);
}
private static void ProcessShpPCode(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.PCode = (byte) reader.ReadElementContentAsInt("PCode", String.Empty);
}
private static void ProcessShpProfileBegin(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.ProfileBegin = (ushort) reader.ReadElementContentAsInt("ProfileBegin", String.Empty);
}
private static void ProcessShpProfileEnd(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.ProfileEnd = (ushort) reader.ReadElementContentAsInt("ProfileEnd", String.Empty);
}
private static void ProcessShpProfileHollow(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.ProfileHollow = (ushort) reader.ReadElementContentAsInt("ProfileHollow", String.Empty);
}
private static void ProcessShpScale(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.Scale = ReadVector(reader, "Scale");
}
private static void ProcessShpState(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.State = (byte) reader.ReadElementContentAsInt("State", String.Empty);
}
private static void ProcessShpProfileShape(PrimitiveBaseShape shp, XmlTextReader reader)
{
string value = reader.ReadElementContentAsString("ProfileShape", String.Empty);
// !!!!! to deal with flags without commas
if (value.Contains(" ") && !value.Contains(","))
value = value.Replace(" ", ", ");
shp.ProfileShape = (ProfileShape) Enum.Parse(typeof (ProfileShape), value);
}
private static void ProcessShpHollowShape(PrimitiveBaseShape shp, XmlTextReader reader)
{
string value = reader.ReadElementContentAsString("HollowShape", String.Empty);
// !!!!! to deal with flags without commas
if (value.Contains(" ") && !value.Contains(","))
value = value.Replace(" ", ", ");
shp.HollowShape = (HollowShape) Enum.Parse(typeof (HollowShape), value);
}
private static void ProcessShpSculptTexture(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.SculptTexture = ReadUUID(reader, "SculptTexture");
}
private static void ProcessShpSculptType(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.SculptType = (byte) reader.ReadElementContentAsInt("SculptType", String.Empty);
}
private static void ProcessShpSculptData(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.SculptData = Convert.FromBase64String(reader.ReadElementString("SculptData"));
}
private static void ProcessShpFlexiSoftness(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiSoftness = reader.ReadElementContentAsInt("FlexiSoftness", String.Empty);
}
private static void ProcessShpFlexiTension(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiTension = reader.ReadElementContentAsFloat("FlexiTension", String.Empty);
}
private static void ProcessShpFlexiDrag(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiDrag = reader.ReadElementContentAsFloat("FlexiDrag", String.Empty);
}
private static void ProcessShpFlexiGravity(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiGravity = reader.ReadElementContentAsFloat("FlexiGravity", String.Empty);
}
private static void ProcessShpFlexiWind(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiWind = reader.ReadElementContentAsFloat("FlexiWind", String.Empty);
}
private static void ProcessShpFlexiForceX(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiForceX = reader.ReadElementContentAsFloat("FlexiForceX", String.Empty);
}
private static void ProcessShpFlexiForceY(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiForceY = reader.ReadElementContentAsFloat("FlexiForceY", String.Empty);
}
private static void ProcessShpFlexiForceZ(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiForceZ = reader.ReadElementContentAsFloat("FlexiForceZ", String.Empty);
}
private static void ProcessShpLightColorR(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightColorR = reader.ReadElementContentAsFloat("LightColorR", String.Empty);
}
private static void ProcessShpLightColorG(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightColorG = reader.ReadElementContentAsFloat("LightColorG", String.Empty);
}
private static void ProcessShpLightColorB(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightColorB = reader.ReadElementContentAsFloat("LightColorB", String.Empty);
}
private static void ProcessShpLightColorA(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightColorA = reader.ReadElementContentAsFloat("LightColorA", String.Empty);
}
private static void ProcessShpLightRadius(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightRadius = reader.ReadElementContentAsFloat("LightRadius", String.Empty);
}
private static void ProcessShpLightCutoff(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightCutoff = reader.ReadElementContentAsFloat("LightCutoff", String.Empty);
}
private static void ProcessShpLightFalloff(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightFalloff = reader.ReadElementContentAsFloat("LightFalloff", String.Empty);
}
private static void ProcessShpLightIntensity(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightIntensity = reader.ReadElementContentAsFloat("LightIntensity", String.Empty);
}
private static void ProcessShpFlexiEntry(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.FlexiEntry = reader.ReadElementContentAsBoolean("FlexiEntry", String.Empty);
}
private static void ProcessShpLightEntry(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.LightEntry = reader.ReadElementContentAsBoolean("LightEntry", String.Empty);
}
private static void ProcessShpSculptEntry(PrimitiveBaseShape shp, XmlTextReader reader)
{
shp.SculptEntry = reader.ReadElementContentAsBoolean("SculptEntry", String.Empty);
}
private static void ProcessShpMedia(PrimitiveBaseShape shp, XmlTextReader reader)
{
string value = reader.ReadElementContentAsString("Media", String.Empty);
shp.Media = PrimitiveBaseShape.MediaList.FromXml(value);
}
#endregion
#region Nested type: Serialization
private delegate string Serialization(SceneObjectPart part);
#endregion
#region Nested type: ShapeXmlProcessor
private delegate void ShapeXmlProcessor(PrimitiveBaseShape shape, XmlTextReader reader);
#endregion
#region Nested type: TaskInventoryXmlProcessor
private delegate void TaskInventoryXmlProcessor(TaskInventoryItem item, XmlTextReader reader);
#endregion
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using Aurora.Simulation.Base;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Aurora.Framework;
using Aurora.Framework.Capabilities;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services.MessagingService
{
public class AgentProcessing : IService, IAgentProcessing
{
#region Declares
protected int MaxVariableRegionSight = 512;
protected bool VariableRegionSight;
protected bool m_enabled = true;
protected IRegistryCore m_registry;
#endregion
#region IService Members
public virtual void Initialize(IConfigSource config, IRegistryCore registry)
{
m_registry = registry;
IConfig agentConfig = config.Configs["AgentProcessing"];
if (agentConfig != null)
{
m_enabled = agentConfig.GetString("Module", "AgentProcessing") == "AgentProcessing";
VariableRegionSight = agentConfig.GetBoolean("UseVariableRegionSightDistance", VariableRegionSight);
MaxVariableRegionSight = agentConfig.GetInt("MaxDistanceVariableRegionSightDistance",
MaxVariableRegionSight);
}
if (m_enabled)
m_registry.RegisterModuleInterface<IAgentProcessing>(this);
}
public virtual void Start(IConfigSource config, IRegistryCore registry)
{
}
public virtual void FinishedStartup()
{
//Also look for incoming messages to display
if (m_enabled)
m_registry.RequestModuleInterface<IAsyncMessageRecievedService>().OnMessageReceived += OnMessageReceived;
}
#endregion
#region Message Received
protected virtual OSDMap OnMessageReceived(OSDMap message)
{
if (!message.ContainsKey("Method"))
return null;
UUID AgentID = message["AgentID"].AsUUID();
ulong requestingRegion = message["RequestingRegion"].AsULong();
ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
if (capsService == null)
{
//MainConsole.Instance.Info("[AgentProcessing]: Failed OnMessageReceived ICapsService is null");
return new OSDMap();
}
IClientCapsService clientCaps = capsService.GetClientCapsService(AgentID);
IRegionClientCapsService regionCaps = null;
if (clientCaps != null)
regionCaps = clientCaps.GetCapsService(requestingRegion);
if (message["Method"] == "LogoutRegionAgents")
{
LogOutAllAgentsForRegion(requestingRegion);
}
else if (message["Method"] == "RegionIsOnline")
//This gets fired when the scene is fully finished starting up
{
//Log out all the agents first, then add any child agents that should be in this region
LogOutAllAgentsForRegion(requestingRegion);
IGridService GridService = m_registry.RequestModuleInterface<IGridService>();
if (GridService != null)
{
int x, y;
Util.UlongToInts(requestingRegion, out x, out y);
GridRegion requestingGridRegion = GridService.GetRegionByPosition(UUID.Zero, x, y);
if (requestingGridRegion != null)
EnableChildAgentsForRegion(requestingGridRegion);
}
}
else if (message["Method"] == "DisableSimulator")
{
//KILL IT!
if (regionCaps == null || clientCaps == null)
return null;
IEventQueueService eventQueue = m_registry.RequestModuleInterface<IEventQueueService>();
eventQueue.DisableSimulator(regionCaps.AgentID, regionCaps.RegionHandle);
//regionCaps.Close();
//clientCaps.RemoveCAPS(requestingRegion);
regionCaps.Disabled = true;
}
else if (message["Method"] == "ArrivedAtDestination")
{
if (regionCaps == null || clientCaps == null)
return null;
//Recieved a callback
if (clientCaps.InTeleport) //Only set this if we are in a teleport,
// otherwise (such as on login), this won't check after the first tp!
clientCaps.CallbackHasCome = true;
regionCaps.Disabled = false;
//The agent is getting here for the first time (eg. login)
OSDMap body = ((OSDMap) message["Message"]);
//Parse the OSDMap
int DrawDistance = body["DrawDistance"].AsInteger();
AgentCircuitData circuitData = new AgentCircuitData();
circuitData.UnpackAgentCircuitData((OSDMap) body["Circuit"]);
//Now do the creation
EnableChildAgents(AgentID, requestingRegion, DrawDistance, circuitData);
}
else if (message["Method"] == "CancelTeleport")
{
if (regionCaps == null || clientCaps == null)
return null;
//Only the region the client is root in can do this
IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle)
{
//The user has requested to cancel the teleport, stop them.
clientCaps.RequestToCancelTeleport = true;
regionCaps.Disabled = false;
}
}
else if (message["Method"] == "AgentLoggedOut")
{
//ONLY if the agent is root do we even consider it
if (regionCaps != null)
{
if (regionCaps.RootAgent)
{
LogoutAgent(regionCaps, false); //The root is killing itself
}
}
}
else if (message["Method"] == "SendChildAgentUpdate")
{
if (regionCaps == null || clientCaps == null)
return null;
IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle) //Has to be root
{
OSDMap body = ((OSDMap) message["Message"]);
AgentPosition pos = new AgentPosition();
pos.Unpack((OSDMap) body["AgentPos"]);
SendChildAgentUpdate(pos, regionCaps);
regionCaps.Disabled = false;
}
}
else if (message["Method"] == "TeleportAgent")
{
if (regionCaps == null || clientCaps == null)
return null;
IRegionClientCapsService rootCaps = clientCaps.GetRootCapsService();
if (rootCaps != null && rootCaps.RegionHandle == regionCaps.RegionHandle)
{
OSDMap body = ((OSDMap) message["Message"]);
GridRegion destination = new GridRegion();
destination.FromOSD((OSDMap) body["Region"]);
uint TeleportFlags = body["TeleportFlags"].AsUInteger();
int DrawDistance = body["DrawDistance"].AsInteger();
AgentCircuitData Circuit = new AgentCircuitData();
Circuit.UnpackAgentCircuitData((OSDMap) body["Circuit"]);
AgentData AgentData = new AgentData();
AgentData.Unpack((OSDMap) body["AgentData"]);
regionCaps.Disabled = false;
OSDMap result = new OSDMap();
string reason = "";
result["Success"] = TeleportAgent(ref destination, TeleportFlags, DrawDistance,
Circuit, AgentData, AgentID, requestingRegion, out reason);
result["Reason"] = reason;
//Remove the region flags, not the regions problem
destination.Flags = 0;
result["Destination"] = destination.ToOSD(); //Send back the new destination
return result;
}
}
else if (message["Method"] == "CrossAgent")
{
if (regionCaps == null || clientCaps == null)
return null;
if (clientCaps.GetRootCapsService().RegionHandle == regionCaps.RegionHandle)
{
//This is a simulator message that tells us to cross the agent
OSDMap body = ((OSDMap) message["Message"]);
Vector3 pos = body["Pos"].AsVector3();
Vector3 Vel = body["Vel"].AsVector3();
GridRegion Region = new GridRegion();
Region.FromOSD((OSDMap) body["Region"]);
AgentCircuitData Circuit = new AgentCircuitData();
Circuit.UnpackAgentCircuitData((OSDMap) body["Circuit"]);
AgentData AgentData = new AgentData();
AgentData.Unpack((OSDMap) body["AgentData"]);
regionCaps.Disabled = false;
OSDMap result = new OSDMap();
string reason = "";
result["Success"] = CrossAgent(Region, pos, Vel, Circuit, AgentData,
AgentID, requestingRegion, out reason);
result["Reason"] = reason;
return result;
}
else if (clientCaps.InTeleport)
{
OSDMap result = new OSDMap();
result["Success"] = false;
result["Note"] = false;
return result;
}
else
{
OSDMap result = new OSDMap();
result["Success"] = false;
result["Note"] = false;
return result;
}
}
return null;
}
#region Logout Agent
public virtual void LogoutAgent(IRegionClientCapsService regionCaps, bool kickRootAgent)
{
//Close all neighbor agents as well, the root is closing itself, so don't call them
ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>();
if (SimulationService != null)
{
IGridService GridService = m_registry.RequestModuleInterface<IGridService>();
if (GridService != null)
{
#if (!ISWIN)
foreach (IRegionClientCapsService regionClient in regionCaps.ClientCaps.GetCapsServices())
{
if (regionClient.RegionHandle != regionCaps.RegionHandle && regionClient.Region != null)
{
SimulationService.CloseAgent(regionClient.Region, regionCaps.AgentID);
}
}
#else
foreach (IRegionClientCapsService regionClient in regionCaps.ClientCaps.GetCapsServices().Where(regionClient => regionClient.RegionHandle != regionCaps.RegionHandle && regionClient.Region != null))
{
SimulationService.CloseAgent(regionClient.Region, regionCaps.AgentID);
}
#endif
}
}
if (kickRootAgent && regionCaps.Region != null) //Kick the root agent then
SimulationService.CloseAgent(regionCaps.Region, regionCaps.AgentID);
//Close all caps
regionCaps.ClientCaps.Close();
IAgentInfoService agentInfoService = m_registry.RequestModuleInterface<IAgentInfoService>();
if (agentInfoService != null)
agentInfoService.SetLoggedIn(regionCaps.AgentID.ToString(), false, true, UUID.Zero);
ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
if (capsService != null)
capsService.RemoveCAPS(regionCaps.AgentID);
}
public virtual void LogOutAllAgentsForRegion(ulong requestingRegion)
{
IRegionCapsService fullregionCaps =
m_registry.RequestModuleInterface<ICapsService>().GetCapsForRegion(requestingRegion);
if (fullregionCaps != null)
{
IEventQueueService eqs = m_registry.RequestModuleInterface<IEventQueueService>();
if (eqs != null)
{
foreach (IRegionClientCapsService regionClientCaps in fullregionCaps.GetClients())
{
//We can send this here, because we ONLY send this when the region is going down for a loong time
eqs.DisableSimulator(regionClientCaps.AgentID, regionClientCaps.RegionHandle);
}
}
//Now kill the region in the caps Service, DO THIS FIRST, otherwise you get an infinite loop later in the IClientCapsService when it tries to remove itself from the IRegionCapsService
m_registry.RequestModuleInterface<ICapsService>().RemoveCapsForRegion(requestingRegion);
//Close all regions and remove them from the region
fullregionCaps.Close();
}
}
#endregion
#region EnableChildAgents
public virtual bool EnableChildAgentsForRegion(GridRegion requestingRegion)
{
int count = 0;
bool informed = true;
List<GridRegion> neighbors = GetNeighbors(requestingRegion, 0);
foreach (GridRegion neighbor in neighbors)
{
//MainConsole.Instance.WarnFormat("--> Going to send child agent to {0}, new agent {1}", neighbour.RegionName, newAgent);
IRegionCapsService regionCaps =
m_registry.RequestModuleInterface<ICapsService>().GetCapsForRegion(neighbor.RegionHandle);
if (regionCaps == null) //If there isn't a region caps, there isn't an agent in this sim
continue;
List<UUID> usersInformed = new List<UUID>();
foreach (IRegionClientCapsService regionClientCaps in regionCaps.GetClients())
{
if (usersInformed.Contains(regionClientCaps.AgentID) || !regionClientCaps.RootAgent)
//Only inform agents once
continue;
AgentCircuitData regionCircuitData = regionClientCaps.CircuitData.Copy();
regionCircuitData.child = true; //Fix child agent status
regionCircuitData.roothandle = requestingRegion.RegionHandle;
regionCircuitData.reallyischild = true;
string reason; //Tell the region about it
bool useCallbacks = false;
if (!InformClientOfNeighbor(regionClientCaps.AgentID, regionClientCaps.RegionHandle,
regionCircuitData, ref requestingRegion, (uint) TeleportFlags.Default,
null, out reason, out useCallbacks))
informed = false;
else
usersInformed.Add(regionClientCaps.AgentID);
}
count++;
}
return informed;
}
public virtual void EnableChildAgents(UUID AgentID, ulong requestingRegion, int DrawDistance,
AgentCircuitData circuit)
{
Util.FireAndForget(delegate
{
int count = 0;
int x, y;
Util.UlongToInts(requestingRegion, out x, out y);
GridRegion ourRegion =
m_registry.RequestModuleInterface<IGridService>().GetRegionByPosition(
UUID.Zero, x, y);
if (ourRegion == null)
{
MainConsole.Instance.Info(
"[AgentProcessing]: Failed to inform neighbors about new agent, could not find our region.");
return;
}
List<GridRegion> neighbors = GetNeighbors(ourRegion, DrawDistance);
ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
IClientCapsService clientCaps = capsService.GetClientCapsService(AgentID);
clientCaps.GetRootCapsService().CircuitData.DrawDistance = DrawDistance;
//Fix the root agents dd
foreach (GridRegion neighbor in neighbors)
{
if (neighbor.RegionHandle != requestingRegion &&
clientCaps.GetCapsService(neighbor.RegionHandle) == null)
{
string reason;
AgentCircuitData regionCircuitData =
clientCaps.GetRootCapsService().CircuitData.Copy();
GridRegion nCopy = neighbor;
regionCircuitData.child = true; //Fix child agent status
regionCircuitData.roothandle = requestingRegion;
regionCircuitData.reallyischild = true;
regionCircuitData.DrawDistance = DrawDistance;
bool useCallbacks = false;
InformClientOfNeighbor(AgentID, requestingRegion, regionCircuitData,
ref nCopy,
(uint) TeleportFlags.Default, null, out reason,
out useCallbacks);
}
count++;
}
});
}
public virtual void EnableChildAgentsForPosition(IRegionClientCapsService caps, Vector3 position)
{
Util.FireAndForget(delegate
{
int count = 0;
IGridService gridService = m_registry.RequestModuleInterface<IGridService>();
int xMin = (caps.Region.RegionLocX) + (int)(position.X) - ((gridService != null ? gridService.GetRegionViewSize() : 1) * caps.Region.RegionSizeX);
int xMax = (caps.Region.RegionLocX) + (int) (position.X) + 256;
int yMin = (caps.Region.RegionLocY) + (int)(position.Y) - ((gridService != null ? gridService.GetRegionViewSize() : 1) * caps.Region.RegionSizeY);
int yMax = (caps.Region.RegionLocY) + (int) (position.Y) + 256;
//Ask the grid service about the range
List<GridRegion> neighbors =
m_registry.RequestModuleInterface<IGridService>().GetRegionRange(UUID.Zero,
xMin, xMax,
yMin, yMax);
ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
IClientCapsService clientCaps = capsService.GetClientCapsService(caps.AgentID);
foreach (GridRegion neighbor in neighbors)
{
if (neighbor.RegionHandle != caps.RegionHandle &&
clientCaps.GetCapsService(neighbor.RegionHandle) == null)
{
string reason;
AgentCircuitData regionCircuitData = caps.CircuitData.Copy();
GridRegion nCopy = neighbor;
regionCircuitData.child = true; //Fix child agent status
regionCircuitData.roothandle = caps.RegionHandle;
regionCircuitData.reallyischild = true;
bool useCallbacks = false;
InformClientOfNeighbor(caps.AgentID, caps.RegionHandle, regionCircuitData,
ref nCopy,
(uint) TeleportFlags.Default, null, out reason,
out useCallbacks);
}
count++;
}
});
}
#endregion
#region Inform Client Of Neighbor
/// <summary>
/// Async component for informing client of which neighbors exist
/// </summary>
/// <remarks>
/// This needs to run asynchronously, as a network timeout may block the thread for a long while
/// </remarks>
/// <param name = "remoteClient"></param>
/// <param name = "a"></param>
/// <param name = "regionHandle"></param>
/// <param name = "endPoint"></param>
public virtual bool InformClientOfNeighbor(UUID AgentID, ulong requestingRegion, AgentCircuitData circuitData,
ref GridRegion neighbor,
uint TeleportFlags, AgentData agentData, out string reason,
out bool useCallbacks)
{
useCallbacks = true;
if (neighbor == null || neighbor.RegionHandle == 0)
{
reason = "Could not find neighbor to inform";
return false;
}
/*if ((neighbor.Flags & (int)Aurora.Framework.RegionFlags.RegionOnline) == 0 &&
(neighbor.Flags & (int)(Aurora.Framework.RegionFlags.Foreign | Aurora.Framework.RegionFlags.Hyperlink)) == 0)
{
reason = "The region you are attempting to teleport to is offline";
return false;
}*/
MainConsole.Instance.Info("[AgentProcessing]: Starting to inform client about neighbor " + neighbor.RegionName);
//Notes on this method
// 1) the SimulationService.CreateAgent MUST have a fixed CapsUrl for the region, so we have to create (if needed)
// a new Caps handler for it.
// 2) Then we can call the methods (EnableSimulator and EstatablishAgentComm) to tell the client the new Urls
// 3) This allows us to make the Caps on the grid server without telling any other regions about what the
// Urls are.
ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>();
if (SimulationService != null)
{
ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
IClientCapsService clientCaps = capsService.GetClientCapsService(AgentID);
IRegionClientCapsService oldRegionService = clientCaps.GetCapsService(neighbor.RegionHandle);
//If its disabled, it should be removed, so kill it!
if (oldRegionService != null && oldRegionService.Disabled)
{
clientCaps.RemoveCAPS(neighbor.RegionHandle);
oldRegionService = null;
}
bool newAgent = oldRegionService == null;
IRegionClientCapsService otherRegionService = clientCaps.GetOrCreateCapsService(neighbor.RegionHandle,
CapsUtil.GetCapsSeedPath
(CapsUtil.
GetRandomCapsObjectPath
()),
circuitData, 0);
if (!newAgent)
{
//Note: if the agent is already there, send an agent update then
bool result = true;
if (agentData != null)
{
agentData.IsCrossing = false;
result = SimulationService.UpdateAgent(neighbor, agentData);
}
if (result)
oldRegionService.Disabled = false;
reason = "";
return result;
}
ICommunicationService commsService = m_registry.RequestModuleInterface<ICommunicationService>();
if (commsService != null)
commsService.GetUrlsForUser(neighbor, circuitData.AgentID);
//Make sure that we make userURLs if we need to
circuitData.CapsPath = CapsUtil.GetCapsPathFromCapsSeed(otherRegionService.CapsUrl); //For OpenSim
circuitData.firstname = clientCaps.AccountInfo.FirstName;
circuitData.lastname = clientCaps.AccountInfo.LastName;
int requestedPort = 0;
if (circuitData.child)
circuitData.reallyischild = true;
bool regionAccepted = CreateAgent(neighbor, otherRegionService, ref circuitData, SimulationService, ref requestedPort, out reason);
if (regionAccepted)
{
IPAddress ipAddress = neighbor.ExternalEndPoint.Address;
string otherRegionsCapsURL;
//If the region accepted us, we should get a CAPS url back as the reason, if not, its not updated or not an Aurora region, so don't touch it.
if (reason != "")
{
OSDMap responseMap = (OSDMap) OSDParser.DeserializeJson(reason);
OSDMap SimSeedCaps = (OSDMap) responseMap["CapsUrls"];
if (responseMap.ContainsKey("OurIPForClient"))
{
string ip = responseMap["OurIPForClient"].AsString();
ipAddress = IPAddress.Parse(ip);
}
otherRegionService.AddCAPS(SimSeedCaps);
otherRegionsCapsURL = otherRegionService.CapsUrl;
}
else
{
//We are assuming an OpenSim region now!
#region OpenSim teleport compatibility!
useCallbacks = false; //OpenSim can't send us back a message, don't try it!
otherRegionsCapsURL = otherRegionService.Region.ServerURI +
CapsUtil.GetCapsSeedPath(circuitData.CapsPath);
otherRegionService.CapsUrl = otherRegionsCapsURL;
#endregion
}
if (ipAddress == null)
ipAddress = neighbor.ExternalEndPoint.Address;
if (requestedPort == 0)
requestedPort = neighbor.ExternalEndPoint.Port;
otherRegionService = clientCaps.GetCapsService(neighbor.RegionHandle);
otherRegionService.LoopbackRegionIP = ipAddress;
otherRegionService.CircuitData.RegionUDPPort = requestedPort;
circuitData.RegionUDPPort = requestedPort; //Fix the port
IEventQueueService EQService = m_registry.RequestModuleInterface<IEventQueueService>();
EQService.EnableSimulator(neighbor.RegionHandle,
ipAddress.GetAddressBytes(),
requestedPort, AgentID,
neighbor.RegionSizeX, neighbor.RegionSizeY, requestingRegion);
// EnableSimulator makes the client send a UseCircuitCode message to the destination,
// which triggers a bunch of things there.
// So let's wait
Thread.Sleep(300);
EQService.EstablishAgentCommunication(AgentID, neighbor.RegionHandle,
ipAddress.GetAddressBytes(),
requestedPort, otherRegionsCapsURL, neighbor.RegionSizeX,
neighbor.RegionSizeY,
requestingRegion);
if (!useCallbacks)
Thread.Sleep(3000); //Give it a bit of time, only for OpenSim...
MainConsole.Instance.Info("[AgentProcessing]: Completed inform client about neighbor " + neighbor.RegionName);
}
else
{
clientCaps.RemoveCAPS(neighbor.RegionHandle);
MainConsole.Instance.Error("[AgentProcessing]: Failed to inform client about neighbor " + neighbor.RegionName +
", reason: " + reason);
return false;
}
return true;
}
reason = "SimulationService does not exist";
MainConsole.Instance.Error("[AgentProcessing]: Failed to inform client about neighbor " + neighbor.RegionName +
", reason: " + reason + "!");
return false;
}
#endregion
#region Teleporting
private int CloseNeighborCall;
public virtual bool TeleportAgent(ref GridRegion destination, uint TeleportFlags, int DrawDistance,
AgentCircuitData circuit, AgentData agentData, UUID AgentID,
ulong requestingRegion,
out string reason)
{
IClientCapsService clientCaps =
m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID);
IRegionClientCapsService regionCaps = clientCaps.GetCapsService(requestingRegion);
if (regionCaps == null || !regionCaps.RootAgent)
{
reason = "";
ResetFromTransit(AgentID);
return false;
}
bool result = false;
try
{
bool callWasCanceled = false;
ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>();
if (SimulationService != null)
{
//Set the user in transit so that we block duplicate tps and reset any cancelations
if (!SetUserInTransit(AgentID))
{
reason = "Already in a teleport";
return false;
}
bool useCallbacks = false;
//Note: we have to pull the new grid region info as the one from the region cannot be trusted
GridRegion oldRegion = destination;
IGridService GridService = m_registry.RequestModuleInterface<IGridService>();
if (GridService != null)
{
destination = GridService.GetRegionByUUID(UUID.Zero, destination.RegionID);
if (destination == null) //If its not in this grid
destination = oldRegion;
//Inform the client of the neighbor if needed
circuit.child = false; //Force child status to the correct type
circuit.roothandle = destination.RegionHandle;
if (!InformClientOfNeighbor(AgentID, requestingRegion, circuit, ref destination, TeleportFlags,
agentData, out reason, out useCallbacks))
{
ResetFromTransit(AgentID);
return false;
}
}
else
{
reason = "Could not find the grid service";
ResetFromTransit(AgentID);
return false;
}
IEventQueueService EQService = m_registry.RequestModuleInterface<IEventQueueService>();
IRegionClientCapsService otherRegion = clientCaps.GetCapsService(destination.RegionHandle);
EQService.TeleportFinishEvent(destination.RegionHandle, destination.Access,
otherRegion.LoopbackRegionIP,
otherRegion.CircuitData.RegionUDPPort,
otherRegion.CapsUrl,
4, AgentID, TeleportFlags,
destination.RegionSizeX, destination.RegionSizeY,
requestingRegion);
// TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
// trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
// that the client contacted the destination before we send the attachments and close things here.
result = !useCallbacks || WaitForCallback(AgentID, out callWasCanceled);
if (!result)
{
//It says it failed, lets call the sim and check
AgentData data = null;
AgentCircuitData circuitData;
result = SimulationService.RetrieveAgent(destination, AgentID, false, out data, out circuitData);
}
if (!result)
{
if (!callWasCanceled)
{
MainConsole.Instance.Warn("[AgentProcessing]: Callback never came for teleporting agent " +
AgentID + ". Resetting.");
}
//Close the agent at the place we just created if it isn't a neighbor
// 7/22 -- Kill the agent no matter what, it obviously is having issues getting there
//if (IsOutsideView (regionCaps.RegionX, destination.RegionLocX, regionCaps.Region.RegionSizeX, destination.RegionSizeX,
// regionCaps.RegionY, destination.RegionLocY, regionCaps.Region.RegionSizeY, destination.RegionSizeY))
{
SimulationService.CloseAgent(destination, AgentID);
clientCaps.RemoveCAPS(destination.RegionHandle);
}
reason = !callWasCanceled ? "The teleport timed out" : "Cancelled";
}
else
{
//Fix the root agent status
otherRegion.RootAgent = true;
regionCaps.RootAgent = false;
// Next, let's close the child agent connections that are too far away.
//if (useCallbacks || oldRegion != destination)//Only close it if we are using callbacks (Aurora region)
//Why? OpenSim regions need closed too, even if the protocol is kinda stupid
CloseNeighborAgents(regionCaps.Region, destination, AgentID);
reason = "";
}
}
else
reason = "No SimulationService found!";
}
catch (Exception ex)
{
MainConsole.Instance.WarnFormat("[AgentProcessing]: Exception occured during agent teleport, {0}", ex);
reason = "Exception occured.";
}
//All done
ResetFromTransit(AgentID);
return result;
}
public virtual void CloseNeighborAgents(GridRegion oldRegion, GridRegion destination, UUID AgentID)
{
CloseNeighborCall++;
int CloseNeighborCallNum = CloseNeighborCall;
Util.FireAndForget(delegate
{
//Sleep for 15 seconds to give the agents a chance to cross and get everything right
Thread.Sleep(15000);
if (CloseNeighborCall != CloseNeighborCallNum)
return; //Another was enqueued, kill this one
//Now do a sanity check on the avatar
IClientCapsService clientCaps =
m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(
AgentID);
if (clientCaps == null)
return;
IRegionClientCapsService rootRegionCaps = clientCaps.GetRootCapsService();
if (rootRegionCaps == null)
return;
IRegionClientCapsService ourRegionCaps =
clientCaps.GetCapsService(destination.RegionHandle);
if (ourRegionCaps == null)
return;
//If they handles arn't the same, the agent moved, and we can't be sure that we should close these agents
if (rootRegionCaps.RegionHandle != ourRegionCaps.RegionHandle &&
!clientCaps.InTeleport)
return;
IGridService service = m_registry.RequestModuleInterface<IGridService>();
if (service != null)
{
List<GridRegion> NeighborsOfOldRegion = service.GetNeighbors(oldRegion);
List<GridRegion> NeighborsOfDestinationRegion =
service.GetNeighbors(destination);
List<GridRegion> byebyeRegions = new List<GridRegion>(NeighborsOfOldRegion)
{oldRegion};
//Add the old region, because it might need closed too
byebyeRegions.RemoveAll(delegate(GridRegion r)
{
if (r.RegionID == destination.RegionID)
return true;
else if (
NeighborsOfDestinationRegion.Contains
(r))
return true;
return false;
});
if (byebyeRegions.Count > 0)
{
MainConsole.Instance.Info("[AgentProcessing]: Closing " + byebyeRegions.Count +
" child agents around " + oldRegion.RegionName);
SendCloseChildAgent(AgentID, byebyeRegions);
}
}
});
}
public virtual void SendCloseChildAgent(UUID agentID, IEnumerable<GridRegion> regionsToClose)
{
IClientCapsService clientCaps =
m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(agentID);
//Close all agents that we've been given regions for
foreach (GridRegion region in regionsToClose)
{
MainConsole.Instance.Info("[AgentProcessing]: Closing child agent in " + region.RegionName);
IRegionClientCapsService regionClientCaps = clientCaps.GetCapsService(region.RegionHandle);
if (regionClientCaps != null)
{
m_registry.RequestModuleInterface<ISimulationService>().CloseAgent(region, agentID);
clientCaps.RemoveCAPS(region.RegionHandle);
}
}
}
protected void ResetFromTransit(UUID AgentID)
{
IClientCapsService clientCaps =
m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID);
if (clientCaps != null)
{
clientCaps.InTeleport = false;
clientCaps.RequestToCancelTeleport = false;
clientCaps.CallbackHasCome = false;
}
}
protected bool SetUserInTransit(UUID AgentID)
{
IClientCapsService clientCaps =
m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID);
if (clientCaps.InTeleport)
{
MainConsole.Instance.Warn("[AgentProcessing]: Got a request to teleport during another teleport for agent " + AgentID +
"!");
return false; //What??? Stop here and don't go forward
}
clientCaps.InTeleport = true;
clientCaps.RequestToCancelTeleport = false;
clientCaps.CallbackHasCome = false;
return true;
}
#region Callbacks
protected bool WaitForCallback(UUID AgentID, out bool callWasCanceled)
{
IClientCapsService clientCaps =
m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID);
int count = 1000;
while (!clientCaps.CallbackHasCome && count > 0)
{
//MainConsole.Instance.Debug(" >>> Waiting... " + count);
if (clientCaps.RequestToCancelTeleport)
{
//If the call was canceled, we need to break here
// now and tell the code that called us about it
callWasCanceled = true;
return true;
}
Thread.Sleep(10);
count--;
}
//If we made it through the whole loop, we havn't been canceled,
// as we either have timed out or made it, so no checks are needed
callWasCanceled = false;
return clientCaps.CallbackHasCome;
}
protected bool WaitForCallback(UUID AgentID)
{
IClientCapsService clientCaps =
m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID);
int count = 100;
while (!clientCaps.CallbackHasCome && count > 0)
{
//MainConsole.Instance.Debug(" >>> Waiting... " + count);
Thread.Sleep(100);
count--;
}
return clientCaps.CallbackHasCome;
}
#endregion
#endregion
#region View Size
/// <summary>
/// Check if the new position is outside of the range for the old position
/// </summary>
/// <param name = "x">old X pos (in meters)</param>
/// <param name = "newRegionX">new X pos (in meters)</param>
/// <param name = "y">old Y pos (in meters)</param>
/// <param name = "newRegionY">new Y pos (in meters)</param>
/// <returns></returns>
public virtual bool IsOutsideView(int oldRegionX, int newRegionX, int oldRegionSizeX, int newRegionSizeX,
int oldRegionY, int newRegionY, int oldRegionSizeY, int newRegionSizeY)
{
if (!CheckViewSize(oldRegionX, newRegionX, oldRegionSizeX, newRegionSizeX))
return true;
if (!CheckViewSize(oldRegionY, newRegionY, oldRegionSizeY, newRegionSizeY))
return true;
return false;
}
private bool CheckViewSize(int oldr, int newr, int oldSize, int newSize)
{
if (oldr - newr < 0)
{
if (
!(Math.Abs(oldr - newr + newSize) <=
m_registry.RequestModuleInterface<IGridService>().GetRegionViewSize()))
return false;
}
else
{
if (
!(Math.Abs(newr - oldr + oldSize) <=
m_registry.RequestModuleInterface<IGridService>().GetRegionViewSize()))
return false;
}
return true;
}
public virtual List<GridRegion> GetNeighbors(GridRegion region, int userDrawDistance)
{
List<GridRegion> neighbors = new List<GridRegion>();
if (VariableRegionSight && userDrawDistance != 0)
{
//Enforce the max draw distance
if (userDrawDistance > MaxVariableRegionSight)
userDrawDistance = MaxVariableRegionSight;
//Query how many regions fit in this size
int xMin = (region.RegionLocX) - (userDrawDistance);
int xMax = (region.RegionLocX) + (userDrawDistance);
int yMin = (region.RegionLocY) - (userDrawDistance);
int yMax = (region.RegionLocY) + (userDrawDistance);
//Ask the grid service about the range
neighbors = m_registry.RequestModuleInterface<IGridService>().GetRegionRange(region.ScopeID,
xMin, xMax, yMin, yMax);
}
else
neighbors = m_registry.RequestModuleInterface<IGridService>().GetNeighbors(region);
return neighbors;
}
#endregion
#region Crossing
public virtual bool CrossAgent(GridRegion crossingRegion, Vector3 pos,
Vector3 velocity, AgentCircuitData circuit, AgentData cAgent, UUID AgentID,
ulong requestingRegion, out string reason)
{
try
{
IClientCapsService clientCaps =
m_registry.RequestModuleInterface<ICapsService>().GetClientCapsService(AgentID);
IRegionClientCapsService requestingRegionCaps = clientCaps.GetCapsService(requestingRegion);
ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>();
if (SimulationService != null)
{
//Note: we have to pull the new grid region info as the one from the region cannot be trusted
IGridService GridService = m_registry.RequestModuleInterface<IGridService>();
if (GridService != null)
{
//Set the user in transit so that we block duplicate tps and reset any cancelations
if (!SetUserInTransit(AgentID))
{
reason = "Already in a teleport";
return false;
}
bool result = false;
//We need to get it from the grid service again so that we can get the simulation service urls correctly
// as regions don't get that info
crossingRegion = GridService.GetRegionByUUID(UUID.Zero, crossingRegion.RegionID);
cAgent.IsCrossing = true;
if (!SimulationService.UpdateAgent(crossingRegion, cAgent))
{
MainConsole.Instance.Warn("[AgentProcessing]: Failed to cross agent " + AgentID +
" because region did not accept it. Resetting.");
reason = "Failed to update an agent";
}
else
{
IEventQueueService EQService = m_registry.RequestModuleInterface<IEventQueueService>();
//Add this for the viewer, but not for the sim, seems to make the viewer happier
int XOffset = crossingRegion.RegionLocX - requestingRegionCaps.RegionX;
pos.X += XOffset;
int YOffset = crossingRegion.RegionLocY - requestingRegionCaps.RegionY;
pos.Y += YOffset;
IRegionClientCapsService otherRegion = clientCaps.GetCapsService(crossingRegion.RegionHandle);
//Tell the client about the transfer
EQService.CrossRegion(crossingRegion.RegionHandle, pos, velocity,
otherRegion.LoopbackRegionIP,
otherRegion.CircuitData.RegionUDPPort,
otherRegion.CapsUrl,
AgentID,
circuit.SessionID,
crossingRegion.RegionSizeX,
crossingRegion.RegionSizeY,
requestingRegion);
result = WaitForCallback(AgentID);
if (!result)
{
MainConsole.Instance.Warn("[AgentProcessing]: Callback never came in crossing agent " + circuit.AgentID +
". Resetting.");
reason = "Crossing timed out";
}
else
{
// Next, let's close the child agent connections that are too far away.
//Fix the root agent status
otherRegion.RootAgent = true;
requestingRegionCaps.RootAgent = false;
CloseNeighborAgents(requestingRegionCaps.Region, crossingRegion, AgentID);
reason = "";
}
}
//All done
ResetFromTransit(AgentID);
return result;
}
else
reason = "Could not find the GridService";
}
else
reason = "Could not find the SimulationService";
}
catch (Exception ex)
{
MainConsole.Instance.WarnFormat("[AgentProcessing]: Failed to cross an agent into a new region. {0}", ex);
}
ResetFromTransit(AgentID);
reason = "Exception occured";
return false;
}
#endregion
#region Agent Update
public virtual void SendChildAgentUpdate(AgentPosition agentpos, IRegionClientCapsService regionCaps)
{
Util.FireAndForget(delegate { SendChildAgentUpdateAsync(agentpos, regionCaps); });
}
public virtual void SendChildAgentUpdateAsync(AgentPosition agentpos, IRegionClientCapsService regionCaps)
{
//We need to send this update out to all the child agents this region has
IGridService service = m_registry.RequestModuleInterface<IGridService>();
if (service != null)
{
ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>();
if (SimulationService != null)
{
//Set the last location in the database
IAgentInfoService agentInfoService = m_registry.RequestModuleInterface<IAgentInfoService>();
if (agentInfoService != null)
{
//Find the lookAt vector
Vector3 lookAt = new Vector3(agentpos.AtAxis.X, agentpos.AtAxis.Y, 0);
if (lookAt != Vector3.Zero)
lookAt = Util.GetNormalizedVector(lookAt);
//Update the database
agentInfoService.SetLastPosition(regionCaps.AgentID.ToString(), regionCaps.Region.RegionID,
agentpos.Position, lookAt);
}
//Also update the service itself
regionCaps.LastPosition = agentpos.Position;
if (agentpos.UserGoingOffline)
return; //It just needed a last pos update
//Tell all neighbor regions about the new position as well
List<GridRegion> ourNeighbors = GetRegions(regionCaps.ClientCaps);
#if (!ISWIN)
foreach (GridRegion region in ourNeighbors)
{
if (!SimulationService.UpdateAgent(region, agentpos))
{
MainConsole.Instance.Info("[AgentProcessing]: Failed to inform " + region.RegionName + " about updating agent. ");
}
}
#else
foreach (GridRegion region in ourNeighbors.Where(region => !SimulationService.UpdateAgent(region, agentpos)))
{
MainConsole.Instance.Info("[AgentProcessing]: Failed to inform " + region.RegionName +
" about updating agent. ");
}
#endif
EnableChildAgentsForPosition(regionCaps, agentpos.Position);
}
}
}
private List<GridRegion> GetRegions(IClientCapsService iClientCapsService)
{
#if(!ISWIN)
List<GridRegion> regions = new List<GridRegion>();
foreach(IRegionClientCapsService rcc in iClientCapsService.GetCapsServices())
regions.Add(rcc.Region);
return regions;
#else
return iClientCapsService.GetCapsServices().Select(rccs => rccs.Region).ToList();
#endif
}
#endregion
#region Login initial agent
public virtual bool LoginAgent(GridRegion region, ref AgentCircuitData aCircuit, out string reason)
{
bool success = false;
reason = "Could not find the simulation service";
ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
ISimulationService SimulationService = m_registry.RequestModuleInterface<ISimulationService>();
if (SimulationService != null)
{
// The client is in the region, we need to make sure it gets the right Caps
// If CreateAgent is successful, it passes back a OSDMap of params that the client
// wants to inform us about, and it includes the Caps SEED url for the region
IRegionClientCapsService regionClientCaps = null;
IClientCapsService clientCaps = null;
if (capsService != null)
{
//Remove any previous users
string ServerCapsBase = CapsUtil.GetRandomCapsObjectPath();
capsService.CreateCAPS(aCircuit.AgentID, CapsUtil.GetCapsSeedPath(ServerCapsBase),
region.RegionHandle, true, aCircuit);
clientCaps = capsService.GetClientCapsService(aCircuit.AgentID);
regionClientCaps = clientCaps.GetCapsService(region.RegionHandle);
}
ICommunicationService commsService = m_registry.RequestModuleInterface<ICommunicationService>();
if (commsService != null)
commsService.GetUrlsForUser(region, aCircuit.AgentID);
//Make sure that we make userURLs if we need to
int requestedUDPPort = 0;
// As we are creating the agent, we must also initialize the CapsService for the agent
success = CreateAgent(region, regionClientCaps, ref aCircuit, SimulationService, ref requestedUDPPort, out reason);
if (requestedUDPPort == 0)
requestedUDPPort = region.ExternalEndPoint.Port;
aCircuit.RegionUDPPort = requestedUDPPort;
if (!success) // If it failed, do not set up any CapsService for the client
{
if (reason != "")
{
try
{
OSDMap reasonMap = OSDParser.DeserializeJson(reason) as OSDMap;
if (reasonMap != null && reasonMap.ContainsKey("Reason"))
reason = reasonMap["Reason"].AsString();
}
catch
{
//If its already not JSON, it'll throw an exception, catch it
}
}
//Delete the Caps!
IAgentProcessing agentProcessor = m_registry.RequestModuleInterface<IAgentProcessing>();
if (agentProcessor != null && capsService != null)
agentProcessor.LogoutAgent(regionClientCaps, true);
else if (capsService != null)
capsService.RemoveCAPS(aCircuit.AgentID);
return success;
}
IPAddress ipAddress = regionClientCaps.Region.ExternalEndPoint.Address;
if (capsService != null && reason != "")
{
try
{
OSDMap responseMap = (OSDMap) OSDParser.DeserializeJson(reason);
OSDMap SimSeedCaps = (OSDMap) responseMap["CapsUrls"];
if (responseMap.ContainsKey("OurIPForClient"))
{
string ip = responseMap["OurIPForClient"].AsString();
ipAddress = IPAddress.Parse(ip);
}
region.ExternalEndPoint.Address = ipAddress;
//Fix this so that it gets sent to the client that way
regionClientCaps.AddCAPS(SimSeedCaps);
regionClientCaps = clientCaps.GetCapsService(region.RegionHandle);
regionClientCaps.LoopbackRegionIP = ipAddress;
regionClientCaps.CircuitData.RegionUDPPort = requestedUDPPort;
regionClientCaps.RootAgent = true;
}
catch
{
//Delete the Caps!
IAgentProcessing agentProcessor = m_registry.RequestModuleInterface<IAgentProcessing>();
if (agentProcessor != null && capsService != null)
agentProcessor.LogoutAgent(regionClientCaps, true);
else if (capsService != null)
capsService.RemoveCAPS(aCircuit.AgentID);
success = false;
}
}
}
return success;
}
private bool CreateAgent(GridRegion region, IRegionClientCapsService regionCaps, ref AgentCircuitData aCircuit,
ISimulationService SimulationService, ref int requestedUDPPort, out string reason)
{
CachedUserInfo info = new CachedUserInfo();
IAgentConnector con = Aurora.DataManager.DataManager.RequestPlugin<IAgentConnector>();
if (con != null)
info.AgentInfo = con.GetAgent(aCircuit.AgentID);
info.UserAccount = regionCaps.ClientCaps.AccountInfo;
IGroupsServiceConnector groupsConn = Aurora.DataManager.DataManager.RequestPlugin<IGroupsServiceConnector>();
if (groupsConn != null)
{
info.ActiveGroup = groupsConn.GetGroupMembershipData(aCircuit.AgentID, UUID.Zero, aCircuit.AgentID);
info.GroupMemberships = groupsConn.GetAgentGroupMemberships(aCircuit.AgentID, aCircuit.AgentID);
}
aCircuit.OtherInformation["CachedUserInfo"] = info.ToOSD();
return SimulationService.CreateAgent(region, ref aCircuit, aCircuit.teleportFlags, null,
out requestedUDPPort, out reason);
}
#endregion
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace System.Net.Security
{
public enum EncryptionPolicy
{
// Prohibit null ciphers (current system defaults)
RequireEncryption = 0,
// Add null ciphers to current system defaults
AllowNoEncryption,
// Request null ciphers only
NoEncryption
}
// A user delegate used to verify remote SSL certificate.
public delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors);
// A user delegate used to select local SSL certificate.
public delegate X509Certificate LocalCertificateSelectionCallback(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers);
// Internal versions of the above delegates.
internal delegate bool RemoteCertValidationCallback(string host, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors);
internal delegate X509Certificate LocalCertSelectionCallback(string targetHost, X509CertificateCollection localCertificates, X509Certificate2 remoteCertificate, string[] acceptableIssuers);
public class SslStream : AuthenticatedStream
{
private SslState _sslState;
private RemoteCertificateValidationCallback _userCertificateValidationCallback;
private LocalCertificateSelectionCallback _userCertificateSelectionCallback;
private object _remoteCertificateOrBytes;
public SslStream(Stream innerStream)
: this(innerStream, false, null, null)
{
}
public SslStream(Stream innerStream, bool leaveInnerStreamOpen)
: this(innerStream, leaveInnerStreamOpen, null, null, EncryptionPolicy.RequireEncryption)
{
}
public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback)
: this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, null, EncryptionPolicy.RequireEncryption)
{
}
public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback,
LocalCertificateSelectionCallback userCertificateSelectionCallback)
: this(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback, userCertificateSelectionCallback, EncryptionPolicy.RequireEncryption)
{
}
public SslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback,
LocalCertificateSelectionCallback userCertificateSelectionCallback, EncryptionPolicy encryptionPolicy)
: base(innerStream, leaveInnerStreamOpen)
{
if (encryptionPolicy != EncryptionPolicy.RequireEncryption && encryptionPolicy != EncryptionPolicy.AllowNoEncryption && encryptionPolicy != EncryptionPolicy.NoEncryption)
{
throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), "encryptionPolicy");
}
_userCertificateValidationCallback = userCertificateValidationCallback;
_userCertificateSelectionCallback = userCertificateSelectionCallback;
RemoteCertValidationCallback _userCertValidationCallbackWrapper = new RemoteCertValidationCallback(UserCertValidationCallbackWrapper);
LocalCertSelectionCallback _userCertSelectionCallbackWrapper = userCertificateSelectionCallback == null ? null : new LocalCertSelectionCallback(UserCertSelectionCallbackWrapper);
_sslState = new SslState(innerStream, _userCertValidationCallbackWrapper, _userCertSelectionCallbackWrapper, encryptionPolicy);
}
private bool UserCertValidationCallbackWrapper(string hostName, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
_remoteCertificateOrBytes = certificate == null ? null : certificate.RawData;
if (_userCertificateValidationCallback == null)
{
if (!_sslState.RemoteCertRequired)
{
sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateNotAvailable;
}
return (sslPolicyErrors == SslPolicyErrors.None);
}
else
{
return _userCertificateValidationCallback(this, certificate, chain, sslPolicyErrors);
}
}
private X509Certificate UserCertSelectionCallbackWrapper(string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
{
return _userCertificateSelectionCallback(this, targetHost, localCertificates, remoteCertificate, acceptableIssuers);
}
//
// Client side auth.
//
internal virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient(targetHost, new X509CertificateCollection(), SecurityProtocol.DefaultSecurityProtocols, false,
asyncCallback, asyncState);
}
internal virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates,
SslProtocols enabledSslProtocols, bool checkCertificateRevocation,
AsyncCallback asyncCallback, object asyncState)
{
_sslState.ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true, checkCertificateRevocation);
LazyAsyncResult result = new LazyAsyncResult(_sslState, asyncState, asyncCallback);
_sslState.ProcessAuthentication(result);
return result;
}
internal virtual void EndAuthenticateAsClient(IAsyncResult asyncResult)
{
_sslState.EndProcessAuthentication(asyncResult);
}
//
// Server side auth.
//
internal virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsServer(serverCertificate, false, SecurityProtocol.DefaultSecurityProtocols, false,
asyncCallback,
asyncState);
}
internal virtual IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired,
SslProtocols enabledSslProtocols, bool checkCertificateRevocation,
AsyncCallback asyncCallback,
object asyncState)
{
_sslState.ValidateCreateContext(true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired, checkCertificateRevocation);
LazyAsyncResult result = new LazyAsyncResult(_sslState, asyncState, asyncCallback);
_sslState.ProcessAuthentication(result);
return result;
}
internal virtual void EndAuthenticateAsServer(IAsyncResult asyncResult)
{
_sslState.EndProcessAuthentication(asyncResult);
}
public TransportContext TransportContext
{
get
{
return new SslStreamContext(this);
}
}
internal ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
return _sslState.GetChannelBinding(kind);
}
#region Task-based async public methods
public virtual Task AuthenticateAsClientAsync(string targetHost)
{
return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, targetHost, null);
}
public virtual Task AuthenticateAsClientAsync(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
{
SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols);
return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, callback, state), EndAuthenticateAsClient, null);
}
public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate)
{
return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, serverCertificate, null);
}
public virtual Task AuthenticateAsServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
{
SecurityProtocol.ThrowOnNotAllowed(enabledSslProtocols);
return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, callback, state), EndAuthenticateAsServer, null);
}
#endregion
public override bool IsAuthenticated
{
get
{
return _sslState.IsAuthenticated;
}
}
public override bool IsMutuallyAuthenticated
{
get
{
return _sslState.IsMutuallyAuthenticated;
}
}
public override bool IsEncrypted
{
get
{
return IsAuthenticated;
}
}
public override bool IsSigned
{
get
{
return IsAuthenticated;
}
}
public override bool IsServer
{
get
{
return _sslState.IsServer;
}
}
public virtual SslProtocols SslProtocol
{
get
{
return _sslState.SslProtocol;
}
}
public virtual bool CheckCertRevocationStatus
{
get
{
return _sslState.CheckCertRevocationStatus;
}
}
public virtual X509Certificate LocalCertificate
{
get
{
return _sslState.LocalCertificate;
}
}
public virtual X509Certificate RemoteCertificate
{
get
{
_sslState.CheckThrow(true);
object chkCertificateOrBytes = _remoteCertificateOrBytes;
if (chkCertificateOrBytes != null && chkCertificateOrBytes.GetType() == typeof(byte[]))
{
return (X509Certificate)(_remoteCertificateOrBytes = new X509Certificate((byte[])chkCertificateOrBytes));
}
else
{
return chkCertificateOrBytes as X509Certificate;
}
}
}
public virtual CipherAlgorithmType CipherAlgorithm
{
get
{
return _sslState.CipherAlgorithm;
}
}
public virtual int CipherStrength
{
get
{
return _sslState.CipherStrength;
}
}
public virtual HashAlgorithmType HashAlgorithm
{
get
{
return _sslState.HashAlgorithm;
}
}
public virtual int HashStrength
{
get
{
return _sslState.HashStrength;
}
}
public virtual ExchangeAlgorithmType KeyExchangeAlgorithm
{
get
{
return _sslState.KeyExchangeAlgorithm;
}
}
public virtual int KeyExchangeStrength
{
get
{
return _sslState.KeyExchangeStrength;
}
}
//
// Stream contract implementation.
//
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanRead
{
get
{
return _sslState.IsAuthenticated && InnerStream.CanRead;
}
}
public override bool CanTimeout
{
get
{
return InnerStream.CanTimeout;
}
}
public override bool CanWrite
{
get
{
return _sslState.IsAuthenticated && InnerStream.CanWrite;
}
}
public override int ReadTimeout
{
get
{
return InnerStream.ReadTimeout;
}
set
{
InnerStream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return InnerStream.WriteTimeout;
}
set
{
InnerStream.WriteTimeout = value;
}
}
public override long Length
{
get
{
return InnerStream.Length;
}
}
public override long Position
{
get
{
return InnerStream.Position;
}
set
{
throw new NotSupportedException(SR.net_noseek);
}
}
public override void SetLength(long value)
{
InnerStream.SetLength(value);
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.net_noseek);
}
public override void Flush()
{
_sslState.Flush();
}
protected override void Dispose(bool disposing)
{
try
{
_sslState.Close();
}
finally
{
base.Dispose(disposing);
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return _sslState.SecureStream.Read(buffer, offset, count);
}
public void Write(byte[] buffer)
{
_sslState.SecureStream.Write(buffer, 0, buffer.Length);
}
public override void Write(byte[] buffer, int offset, int count)
{
_sslState.SecureStream.Write(buffer, offset, count);
}
}
}
| |
namespace SharpLua
{
using System;
using System.IO;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
#if WindowsCE
using IReflect = System.Type;
#endif
/*
* Passes objects from the CLR to Lua and vice-versa
*
* Author: Fabio Mascarenhas
* Version: 1.0
*/
public class ObjectTranslator
{
internal CheckType typeChecker;
// object # to object (FIXME - it should be possible to get object address as an object #)
public readonly Dictionary<int, object> objects = new Dictionary<int, object>();
// object to object #
public readonly Dictionary<object, int> objectsBackMap = new Dictionary<object, int>();
private MetaFunctions metaFunctions;
private SharpLua.Lua.lua_CFunction registerTableFunction, unregisterTableFunction, getMethodSigFunction,
getConstructorSigFunction, importTypeFunction, loadAssemblyFunction, ctypeFunction, enumFromIntFunction;
internal EventHandlerContainer pendingEvents = new EventHandlerContainer();
#if WindowsCE
/// <summary>
/// List of assemblies to search when searching for a type by name
/// </summary>
/// <remarks>
/// Under the full framework, we simply use AppDomain.CurrentDomain.GetAssemblies().
/// The Compact Framework, however, does not provide this method, nor any other means to
/// get a list of all assemblies loaded into the current AppDomain.
/// Therefore, under the Compact Framework, integrators must populate this property in order for
/// various operations to perform usefully.
/// </remarks>
public static List<Assembly> SearchAssemblies = new List<Assembly>();
#endif
public ObjectTranslator(LuaInterface __ignored__, SharpLua.Lua.LuaState luaState)
{
typeChecker = new CheckType(this);
metaFunctions = new MetaFunctions(this);
importTypeFunction = new SharpLua.Lua.lua_CFunction(this.importType);
loadAssemblyFunction = new SharpLua.Lua.lua_CFunction(this.loadAssembly);
registerTableFunction = new SharpLua.Lua.lua_CFunction(this.registerTable);
unregisterTableFunction = new SharpLua.Lua.lua_CFunction(this.unregisterTable);
getMethodSigFunction = new SharpLua.Lua.lua_CFunction(this.getMethodSignature);
getConstructorSigFunction = new SharpLua.Lua.lua_CFunction(this.getConstructorSignature);
ctypeFunction = new SharpLua.Lua.lua_CFunction(this.ctype);
enumFromIntFunction = new SharpLua.Lua.lua_CFunction(this.enumFromInt);
createLuaObjectList(luaState);
createIndexingMetaFunction(luaState);
createBaseClassMetatable(luaState);
createClassMetatable(luaState);
createFunctionMetatable(luaState);
setGlobalFunctions(luaState);
}
/*
* Sets up the list of objects in the Lua side
*/
private void createLuaObjectList(SharpLua.Lua.LuaState luaState)
{
LuaDLL.lua_pushstring(luaState, "luaNet_objects");
LuaDLL.lua_newtable(luaState);
LuaDLL.lua_newtable(luaState);
LuaDLL.lua_pushstring(luaState, "__mode");
LuaDLL.lua_pushstring(luaState, "v");
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_setmetatable(luaState, -2);
LuaDLL.lua_settable(luaState, (int)LuaIndexes.LUA_REGISTRYINDEX);
}
/*
* Registers the indexing function of CLR objects
* passed to Lua
*/
private void createIndexingMetaFunction(SharpLua.Lua.LuaState luaState)
{
LuaDLL.lua_pushstring(luaState, "luaNet_indexfunction");
LuaDLL.luaL_dostring(luaState, MetaFunctions.luaIndexFunction); // steffenj: lua_dostring renamed to luaL_dostring
//LuaDLL.lua_pushstdcallcfunction(luaState,indexFunction);
LuaDLL.lua_rawset(luaState, (int)LuaIndexes.LUA_REGISTRYINDEX);
}
/*
* Creates the metatable for superclasses (the base
* field of registered tables)
*/
private void createBaseClassMetatable(SharpLua.Lua.LuaState luaState)
{
LuaDLL.luaL_newmetatable(luaState, "luaNet_searchbase");
LuaDLL.lua_pushstring(luaState, "__gc");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.gcFunction);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__tostring");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.toStringFunction);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__index");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.baseIndexFunction);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__newindex");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.newindexFunction);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_settop(luaState, -2);
}
/*
* Creates the metatable for type references
*/
private void createClassMetatable(SharpLua.Lua.LuaState luaState)
{
LuaDLL.luaL_newmetatable(luaState, "luaNet_class");
LuaDLL.lua_pushstring(luaState, "__gc");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.gcFunction);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__tostring");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.toStringFunction);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__index");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.classIndexFunction);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__newindex");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.classNewindexFunction);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__call");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.callConstructorFunction);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_settop(luaState, -2);
}
/*
* Registers the global functions used by LuaInterface
*/
private void setGlobalFunctions(SharpLua.Lua.LuaState luaState)
{
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.indexFunction);
LuaDLL.lua_setglobal(luaState, "get_object_member");
LuaDLL.lua_pushstdcallcfunction(luaState, importTypeFunction);
LuaDLL.lua_setglobal(luaState, "import_type");
LuaDLL.lua_pushstdcallcfunction(luaState, loadAssemblyFunction);
LuaDLL.lua_setglobal(luaState, "load_assembly");
LuaDLL.lua_pushstdcallcfunction(luaState, registerTableFunction);
LuaDLL.lua_setglobal(luaState, "make_object");
LuaDLL.lua_pushstdcallcfunction(luaState, unregisterTableFunction);
LuaDLL.lua_setglobal(luaState, "free_object");
LuaDLL.lua_pushstdcallcfunction(luaState, getMethodSigFunction);
LuaDLL.lua_setglobal(luaState, "get_method_bysig");
LuaDLL.lua_pushstdcallcfunction(luaState, getConstructorSigFunction);
LuaDLL.lua_setglobal(luaState, "get_constructor_bysig");
LuaDLL.lua_pushstdcallcfunction(luaState, ctypeFunction);
LuaDLL.lua_setglobal(luaState, "ctype");
LuaDLL.lua_pushstdcallcfunction(luaState, enumFromIntFunction);
LuaDLL.lua_setglobal(luaState, "enum");
}
/*
* Creates the metatable for delegates
*/
private void createFunctionMetatable(SharpLua.Lua.LuaState luaState)
{
LuaDLL.luaL_newmetatable(luaState, "luaNet_function");
LuaDLL.lua_pushstring(luaState, "__gc");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.gcFunction);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__call");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.execDelegateFunction);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_settop(luaState, -2);
}
/*
* Passes errors (argument e) to the Lua interpreter
*/
internal void throwError(SharpLua.Lua.LuaState luaState, object e)
{
// if e is a LuaErrorException, it's wrapping the real object to be thrown (usually a string)
LuaErrorException luaerror_ex = e as LuaErrorException;
if (luaerror_ex != null)
e = luaerror_ex.LuaErrorObject;
// If the argument is a mere string, we are free to add extra info to it (as opposed to some private C# exception object or somesuch, which we just pass up)
if (e is string)
{
// We use this to remove anything pushed by luaL_where
int oldTop = LuaDLL.lua_gettop(luaState);
// Stack frame #1 is our C# wrapper, so not very interesting to the user
// Stack frame #2 must be the lua code that called us, so that's what we want to use
LuaDLL.luaL_where(luaState, 2);
object[] curlev = popValues(luaState, oldTop);
// Debug.WriteLine(curlev);
if (curlev.Length > 0)
e = curlev[0].ToString() + e;
}
push(luaState, e);
LuaDLL.lua_error(luaState);
}
/*
* Implementation of load_assembly. Throws an error
* if the assembly is not found.
*/
private int loadAssembly(SharpLua.Lua.LuaState luaState)
{
try
{
string assemblyName = LuaDLL.lua_tostring(luaState, 1);
Assembly assembly = null;
try
{
assembly = Assembly.Load(assemblyName);
}
catch (BadImageFormatException)
{
// The assemblyName was invalid. It is most likely a path.
}
if (assembly == null)
{
#if WindowsCE
assembly = Assembly.LoadFrom(assemblyName);
#else
assembly = Assembly.Load(AssemblyName.GetAssemblyName(assemblyName));
#endif
}
}
catch (Exception e)
{
throwError(luaState, e);
}
return 0;
}
internal Type FindType(string className) { return FindType(className, null); }
internal Type FindType(string className, Type desiredType)
{
Type t = Type.GetType(className, false);
if (t != null) return t;
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Type klass = assembly.GetType(className, false);
if (klass != null)
{
if (desiredType == null || desiredType.IsAssignableFrom(klass))
return klass;
}
}
return null;
}
/*
* Implementation of import_type. Returns nil if the
* type is not found.
*/
private int importType(SharpLua.Lua.LuaState luaState)
{
string className = LuaDLL.lua_tostring(luaState, 1);
Type klass = FindType(className);
if (klass != null)
pushType(luaState, klass);
else
LuaDLL.lua_pushnil(luaState);
return 1;
}
/*
* Implementation of make_object. Registers a table (first
* argument in the stack) as an object subclassing the
* type passed as second argument in the stack.
*/
private int registerTable(SharpLua.Lua.LuaState luaState)
{
#if WindowsCE
throwError(luaState, "cannot make_object() under Windows CE");
#else
if (LuaDLL.lua_type(luaState, 1) == LuaTypes.LUA_TTABLE)
{
LuaTable luaTable = getTable(luaState, 1);
string superclassName = LuaDLL.lua_tostring(luaState, 2);
if (superclassName != null)
{
Type klass = FindType(superclassName);
if (klass != null)
{
// Creates and pushes the object in the stack, setting
// it as the metatable of the first argument
object obj = CodeGeneration.Instance.GetClassInstance(klass, luaTable);
pushObject(luaState, obj, "luaNet_metatable");
LuaDLL.lua_newtable(luaState);
LuaDLL.lua_pushstring(luaState, "__index");
LuaDLL.lua_pushvalue(luaState, -3);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__newindex");
LuaDLL.lua_pushvalue(luaState, -3);
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_setmetatable(luaState, 1);
// Pushes the object again, this time as the base field
// of the table and with the luaNet_searchbase metatable
LuaDLL.lua_pushstring(luaState, "base");
int index = addObject(obj);
pushNewObject(luaState, obj, index, "luaNet_searchbase");
LuaDLL.lua_rawset(luaState, 1);
}
else
throwError(luaState, "register_table: can not find superclass '" + superclassName + "'");
}
else
throwError(luaState, "register_table: superclass name can not be null");
}
else throwError(luaState, "register_table: first arg is not a table");
#endif
return 0;
}
/*
* Implementation of free_object. Clears the metatable and the
* base field, freeing the created object for garbage-collection
*/
private int unregisterTable(SharpLua.Lua.LuaState luaState)
{
try
{
if (LuaDLL.lua_getmetatable(luaState, 1) != 0)
{
LuaDLL.lua_pushstring(luaState, "__index");
LuaDLL.lua_gettable(luaState, -2);
object obj = getRawNetObject(luaState, -1);
if (obj == null) throwError(luaState, "unregister_table: arg is not valid table");
FieldInfo luaTableField = obj.GetType().GetField("__luaInterface_luaTable");
if (luaTableField == null) throwError(luaState, "unregister_table: arg is not valid table");
luaTableField.SetValue(obj, null);
LuaDLL.lua_pushnil(luaState);
LuaDLL.lua_setmetatable(luaState, 1);
LuaDLL.lua_pushstring(luaState, "base");
LuaDLL.lua_pushnil(luaState);
LuaDLL.lua_settable(luaState, 1);
}
else throwError(luaState, "unregister_table: arg is not valid table");
}
catch (Exception e)
{
throwError(luaState, e.Message);
}
return 0;
}
/*
* Implementation of get_method_bysig. Returns nil
* if no matching method is not found.
*/
private int getMethodSignature(SharpLua.Lua.LuaState luaState)
{
IReflect klass; object target;
int udata = LuaDLL.luanet_checkudata(luaState, 1, "luaNet_class");
if (udata != -1)
{
klass = (IReflect)objects[udata];
target = null;
}
else
{
target = getRawNetObject(luaState, 1);
if (target == null)
{
throwError(luaState, "get_method_bysig: first arg is not type or object reference");
LuaDLL.lua_pushnil(luaState);
return 1;
}
klass = target.GetType();
}
string methodName = LuaDLL.lua_tostring(luaState, 2);
Type[] signature = new Type[LuaDLL.lua_gettop(luaState) - 2];
for (int i = 0; i < signature.Length; i++)
signature[i] = FindType(LuaDLL.lua_tostring(luaState, i + 3));
try
{
//CP: Added ignore case
MethodInfo method = klass.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static |
BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase, null, signature, null);
pushFunction(luaState, new SharpLua.Lua.lua_CFunction((new LuaMethodWrapper(this, target, klass, method)).call));
}
catch (Exception e)
{
throwError(luaState, e);
LuaDLL.lua_pushnil(luaState);
}
return 1;
}
/*
* Implementation of get_constructor_bysig. Returns nil
* if no matching constructor is found.
*/
private int getConstructorSignature(SharpLua.Lua.LuaState luaState)
{
IReflect klass = null;
int udata = LuaDLL.luanet_checkudata(luaState, 1, "luaNet_class");
if (udata != -1)
{
klass = (IReflect)objects[udata];
}
if (klass == null)
{
throwError(luaState, "get_constructor_bysig: first arg is invalid type reference");
}
Type[] signature = new Type[LuaDLL.lua_gettop(luaState) - 1];
for (int i = 0; i < signature.Length; i++)
signature[i] = FindType(LuaDLL.lua_tostring(luaState, i + 2));
try
{
ConstructorInfo constructor = klass.UnderlyingSystemType.GetConstructor(signature);
pushFunction(luaState, new SharpLua.Lua.lua_CFunction((new LuaMethodWrapper(this, null, klass, constructor)).call));
}
catch (Exception e)
{
throwError(luaState, e);
LuaDLL.lua_pushnil(luaState);
}
return 1;
}
private Type typeOf(SharpLua.Lua.LuaState luaState, int idx)
{
int udata = LuaDLL.luanet_checkudata(luaState, 1, "luaNet_class");
if (udata == -1)
{
return null;
}
else
{
ProxyType pt = (ProxyType)objects[udata];
return pt.UnderlyingSystemType;
}
}
public int pushError(SharpLua.Lua.LuaState luaState, string msg)
{
LuaDLL.lua_pushnil(luaState);
LuaDLL.lua_pushstring(luaState, msg);
return 2;
}
private int ctype(SharpLua.Lua.LuaState luaState)
{
Type t = typeOf(luaState, 1);
if (t == null)
{
return pushError(luaState, "not a CLR class");
}
pushObject(luaState, t, "luaNet_metatable");
return 1;
}
private int enumFromInt(SharpLua.Lua.LuaState luaState)
{
Type t = typeOf(luaState, 1);
if (t == null || !t.IsEnum)
{
return pushError(luaState, "not an enum");
}
object res = null;
LuaTypes lt = LuaDLL.lua_type(luaState, 2);
if (lt == LuaTypes.LUA_TNUMBER)
{
int ival = (int)LuaDLL.lua_tonumber(luaState, 2);
res = Enum.ToObject(t, ival);
}
else
if (lt == LuaTypes.LUA_TSTRING)
{
string sflags = LuaDLL.lua_tostring(luaState, 2);
string err = null;
try
{
res = Enum.Parse(t, sflags, false);
}
catch (ArgumentException e)
{
err = e.Message;
}
if (err != null)
{
return pushError(luaState, err);
}
}
else
{
return pushError(luaState, "second argument must be a integer or a string");
}
pushObject(luaState, res, "luaNet_metatable");
return 1;
}
/*
* Pushes a type reference into the stack
*/
internal void pushType(SharpLua.Lua.LuaState luaState, Type t)
{
pushObject(luaState, new ProxyType(t), "luaNet_class");
}
/*
* Pushes a delegate into the stack
*/
internal void pushFunction(SharpLua.Lua.LuaState luaState, SharpLua.Lua.lua_CFunction func)
{
//Console.WriteLine("function push");
if (true)
// 11/16/12 - Fix function pushing (Dirk Weltz metatable problem)
// SharpLua.InterfacingTests still works
// This allows metatables to have CLR defined functions
Lua.lua_pushcfunction(luaState, func);
else
pushObject(luaState, func, "luaNet_function");
}
/*
* Pushes a CLR object into the Lua stack as an userdata
* with the provided metatable
*/
internal void pushObject(SharpLua.Lua.LuaState luaState, object o, string metatable)
{
int index = -1;
// Pushes nil
if (o == null)
{
LuaDLL.lua_pushnil(luaState);
return;
}
// Object already in the list of Lua objects? Push the stored reference.
bool found = objectsBackMap.TryGetValue(o, out index);
if (found)
{
LuaDLL.luaL_getmetatable(luaState, "luaNet_objects");
LuaDLL.lua_rawgeti(luaState, -1, index);
// Note: starting with lua5.1 the garbage collector may remove weak reference items (such as our luaNet_objects values) when the initial GC sweep
// occurs, but the actual call of the __gc finalizer for that object may not happen until a little while later. During that window we might call
// this routine and find the element missing from luaNet_objects, but collectObject() has not yet been called. In that case, we go ahead and call collect
// object here
// did we find a non nil object in our table? if not, we need to call collect object
LuaTypes type = LuaDLL.lua_type(luaState, -1);
if (type != LuaTypes.LUA_TNIL)
{
LuaDLL.lua_remove(luaState, -2); // drop the metatable - we're going to leave our object on the stack
return;
}
// MetaFunctions.dumpStack(this, luaState);
LuaDLL.lua_remove(luaState, -1); // remove the nil object value
LuaDLL.lua_remove(luaState, -1); // remove the metatable
collectObject(o, index); // Remove from both our tables and fall out to get a new ID
}
index = addObject(o);
pushNewObject(luaState, o, index, metatable);
}
/*
* Pushes a new object into the Lua stack with the provided
* metatable
*/
private void pushNewObject(SharpLua.Lua.LuaState luaState, object o, int index, string metatable)
{
if (metatable == "luaNet_metatable")
{
// Gets or creates the metatable for the object's type
LuaDLL.luaL_getmetatable(luaState, o.GetType().AssemblyQualifiedName);
if (LuaDLL.lua_isnil(luaState, -1))
{
LuaDLL.lua_settop(luaState, -2);
LuaDLL.luaL_newmetatable(luaState, o.GetType().AssemblyQualifiedName);
LuaDLL.lua_pushstring(luaState, "cache");
LuaDLL.lua_newtable(luaState);
LuaDLL.lua_rawset(luaState, -3);
LuaDLL.lua_pushlightuserdata(luaState, LuaDLL.luanet_gettag());
LuaDLL.lua_pushnumber(luaState, 1);
LuaDLL.lua_rawset(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__index");
LuaDLL.lua_pushstring(luaState, "luaNet_indexfunction");
LuaDLL.lua_rawget(luaState, (int)LuaIndexes.LUA_REGISTRYINDEX);
LuaDLL.lua_rawset(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__gc");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.gcFunction);
LuaDLL.lua_rawset(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__tostring");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.toStringFunction);
LuaDLL.lua_rawset(luaState, -3);
LuaDLL.lua_pushstring(luaState, "__newindex");
LuaDLL.lua_pushstdcallcfunction(luaState, metaFunctions.newindexFunction);
LuaDLL.lua_rawset(luaState, -3);
}
}
else
{
LuaDLL.luaL_getmetatable(luaState, metatable);
}
// Stores the object index in the Lua list and pushes the
// index into the Lua stack
LuaDLL.luaL_getmetatable(luaState, "luaNet_objects");
LuaDLL.luanet_newudata(luaState, index);
LuaDLL.lua_pushvalue(luaState, -3);
LuaDLL.lua_remove(luaState, -4);
LuaDLL.lua_setmetatable(luaState, -2);
LuaDLL.lua_pushvalue(luaState, -1);
LuaDLL.lua_rawseti(luaState, -3, index);
LuaDLL.lua_remove(luaState, -2);
}
/*
* Gets an object from the Lua stack with the desired type, if it matches, otherwise
* returns null.
*/
internal object getAsType(SharpLua.Lua.LuaState luaState, int stackPos, Type paramType)
{
ExtractValue extractor = typeChecker.checkType(luaState, stackPos, paramType);
if (extractor != null) return extractor(luaState, stackPos);
return null;
}
/// <summary>
/// Given the Lua int ID for an object remove it from our maps
/// </summary>
/// <param name="udata"></param>
internal void collectObject(int udata)
{
object o;
bool found = objects.TryGetValue(udata, out o);
// The other variant of collectObject might have gotten here first, in that case we will silently ignore the missing entry
if (found)
{
// Debug.WriteLine("Removing " + o.ToString() + " @ " + udata);
objects.Remove(udata);
objectsBackMap.Remove(o);
}
}
/// <summary>
/// Given an object reference, remove it from our maps
/// </summary>
/// <param name="udata"></param>
void collectObject(object o, int udata)
{
// Debug.WriteLine("Removing " + o.ToString() + " @ " + udata);
objects.Remove(udata);
objectsBackMap.Remove(o);
}
/// <summary>
/// We want to ensure that objects always have a unique ID
/// </summary>
int nextObj = 0;
int addObject(object obj)
{
// New object: inserts it in the list
int index = nextObj++;
// Debug.WriteLine("Adding " + obj.ToString() + " @ " + index);
objects[index] = obj;
objectsBackMap[obj] = index;
return index;
}
/*
* Gets an object from the Lua stack according to its Lua type.
*/
public object getObject(SharpLua.Lua.LuaState luaState, int index)
{
LuaTypes type = LuaDLL.lua_type(luaState, index);
switch (type)
{
case LuaTypes.LUA_TNUMBER:
{
return LuaDLL.lua_tonumber(luaState, index);
}
case LuaTypes.LUA_TSTRING:
{
return LuaDLL.lua_tostring(luaState, index);
}
case LuaTypes.LUA_TBOOLEAN:
{
return LuaDLL.lua_toboolean(luaState, index);
}
case LuaTypes.LUA_TTABLE:
{
return getTable(luaState, index);
}
case LuaTypes.LUA_TFUNCTION:
{
return getFunction(luaState, index);
}
case LuaTypes.LUA_TUSERDATA:
{
int udata = LuaDLL.luanet_tonetobject(luaState, index);
if (udata != -1)
return objects[udata];
else
return getUserData(luaState, index);
}
default:
return null;
}
}
/*
* Gets the table in the index positon of the Lua stack.
*/
internal LuaTable getTable(SharpLua.Lua.LuaState luaState, int index)
{
LuaDLL.lua_pushvalue(luaState, index);
return new LuaTable(LuaDLL.lua_ref(luaState, 1), luaState.Interface);
}
/*
* Gets the userdata in the index positon of the Lua stack.
*/
internal LuaUserData getUserData(SharpLua.Lua.LuaState luaState, int index)
{
LuaDLL.lua_pushvalue(luaState, index);
return new LuaUserData(LuaDLL.lua_ref(luaState, 1), luaState.Interface);
}
/*
* Gets the function in the index positon of the Lua stack.
*/
internal LuaFunction getFunction(SharpLua.Lua.LuaState luaState, int index)
{
LuaDLL.lua_pushvalue(luaState, index);
return new LuaFunction(LuaDLL.lua_ref(luaState, 1), luaState.Interface);
}
/*
* Gets the CLR object in the index positon of the Lua stack. Returns
* delegates as Lua functions.
*/
internal object getNetObject(SharpLua.Lua.LuaState luaState, int index)
{
int idx = LuaDLL.luanet_tonetobject(luaState, index);
if (idx != -1)
return objects[idx];
else
return null;
}
/// <summary>
/// Assuming that, for the stack of the Lua instance identified by luaState, 'index' refers to a table,
/// </summary>
/// <param name="luaState"></param>
/// <param name="index"></param>
/// <returns></returns>
internal object createNetObject(SharpLua.Lua.LuaState luaState, int index, Type t)
{
throw new NotImplementedException();
}
/*
* Gets the CLR object in the index positon of the Lua stack. Returns
* delegates as is.
*/
internal object getRawNetObject(SharpLua.Lua.LuaState luaState, int index)
{
int udata = LuaDLL.luanet_rawnetobj(luaState, index);
if (udata != -1)
{
return objects[udata];
}
return null;
}
/*
* Pushes the entire array into the Lua stack and returns the number
* of elements pushed.
*/
internal int returnValues(SharpLua.Lua.LuaState luaState, object[] returnValues)
{
if (LuaDLL.lua_checkstack(luaState, returnValues.Length + 5))
{
for (int i = 0; i < returnValues.Length; i++)
{
push(luaState, returnValues[i]);
}
return returnValues.Length;
}
else
return 0;
}
/*
* Gets the values from the provided index to
* the top of the stack and returns them in an array.
*/
internal object[] popValues(SharpLua.Lua.LuaState luaState, int oldTop)
{
int newTop = LuaDLL.lua_gettop(luaState);
if (oldTop == newTop)
{
return null;
}
else
{
ArrayList returnValues = new ArrayList();
for (int i = oldTop + 1; i <= newTop; i++)
{
returnValues.Add(getObject(luaState, i));
}
LuaDLL.lua_settop(luaState, oldTop);
return returnValues.ToArray();
}
}
/*
* Gets the values from the provided index to
* the top of the stack and returns them in an array, casting
* them to the provided types.
*/
internal object[] popValues(SharpLua.Lua.LuaState luaState, int oldTop, Type[] popTypes)
{
int newTop = LuaDLL.lua_gettop(luaState);
if (oldTop == newTop)
{
return null;
}
else
{
int iTypes;
ArrayList returnValues = new ArrayList();
if (popTypes[0] == typeof(void))
iTypes = 1;
else
iTypes = 0;
for (int i = oldTop + 1; i <= newTop; i++)
{
returnValues.Add(getAsType(luaState, i, popTypes[iTypes]));
iTypes++;
}
LuaDLL.lua_settop(luaState, oldTop);
return returnValues.ToArray();
}
}
// kevinh - the following line doesn't work for remoting proxies - they always return a match for 'is'
// else if(o is ILuaGeneratedType)
static bool IsILua(object o)
{
#if !WindowsCE
if (o is ILuaGeneratedType)
{
// Make sure we are _really_ ILuaGenerated
Type typ = o.GetType();
return (typ.GetInterface("ILuaGeneratedType") != null);
}
else
#endif
return false;
}
/*
* Pushes the object into the Lua stack according to its type.
*/
internal void push(SharpLua.Lua.LuaState luaState, object o)
{
if (o == null)
{
LuaDLL.lua_pushnil(luaState);
}
else if (o is sbyte || o is byte || o is short || o is ushort ||
o is int || o is uint || o is long || o is float ||
o is ulong || o is decimal || o is double)
{
double d = Convert.ToDouble(o);
LuaDLL.lua_pushnumber(luaState, d);
}
else if (o is char)
{
double d = (char)o;
LuaDLL.lua_pushnumber(luaState, d);
}
else if (o is string)
{
string str = (string)o;
LuaDLL.lua_pushstring(luaState, str);
}
else if (o is bool)
{
bool b = (bool)o;
LuaDLL.lua_pushboolean(luaState, b);
}
#if !WindowsCE
else if (IsILua(o))
{
(((ILuaGeneratedType)o).__luaInterface_getLuaTable()).push(luaState);
}
#endif
else if (o is LuaTable)
{
((LuaTable)o).push(luaState);
}
else if (o is SharpLua.Lua.lua_CFunction)
{
pushFunction(luaState, (SharpLua.Lua.lua_CFunction)o);
}
else if (o is LuaFunction)
{
((LuaFunction)o).push(luaState);
}
else
{
pushObject(luaState, o, "luaNet_metatable");
}
}
/*
* Checks if the method matches the arguments in the Lua stack, getting
* the arguments if it does.
*/
internal bool matchParameters(SharpLua.Lua.LuaState luaState, MethodBase method, ref MethodCache methodCache)
{
return metaFunctions.matchParameters(luaState, method, ref methodCache);
}
internal Array tableToArray(object luaParamValue, Type paramArrayType)
{
return metaFunctions.TableToArray(luaParamValue, paramArrayType);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces
{
public interface ILSL_Api
{
LSL_List GetPrimitiveParamsEx(LSL_Key prim, LSL_List rules);
LSL_Integer llAbs(int i);
LSL_Float llAcos(double val);
void llAddToLandBanList(string avatar, double hours);
void llAddToLandPassList(string avatar, double hours);
void llAdjustSoundVolume(double volume);
void llAllowInventoryDrop(int add);
LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b);
void llApplyImpulse(LSL_Vector force, int local);
void llApplyRotationalImpulse(LSL_Vector force, int local);
LSL_Float llAsin(double val);
LSL_Float llAtan2(double x, double y);
void llAttachToAvatar(int attachment);
LSL_Key llAvatarOnLinkSitTarget(int linknum);
LSL_Key llAvatarOnSitTarget();
LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up);
LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle);
LSL_Integer llBase64ToInteger(string str);
LSL_String llBase64ToString(string str);
void llBreakAllLinks();
void llBreakLink(int linknum);
LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options);
LSL_Integer llCeil(double f);
void llClearCameraParams();
LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face);
LSL_Integer llClearPrimMedia(LSL_Integer face);
void llCloseRemoteDataChannel(string channel);
LSL_Float llCloud(LSL_Vector offset);
void llCollisionFilter(string name, string id, int accept);
void llCollisionSound(string impact_sound, double impact_volume);
void llCollisionSprite(string impact_sprite);
LSL_Float llCos(double f);
void llCreateLink(string target, int parent);
LSL_List llCSV2List(string src);
LSL_List llDeleteSubList(LSL_List src, int start, int end);
LSL_String llDeleteSubString(string src, int start, int end);
void llDetachFromAvatar();
LSL_Vector llDetectedGrab(int number);
LSL_Integer llDetectedGroup(int number);
LSL_Key llDetectedKey(int number);
LSL_Integer llDetectedLinkNumber(int number);
LSL_String llDetectedName(int number);
LSL_Key llDetectedOwner(int number);
LSL_Vector llDetectedPos(int number);
LSL_Rotation llDetectedRot(int number);
LSL_Vector llDetectedTouchBinormal(int index);
LSL_Integer llDetectedTouchFace(int index);
LSL_Vector llDetectedTouchNormal(int index);
LSL_Vector llDetectedTouchPos(int index);
LSL_Vector llDetectedTouchST(int index);
LSL_Vector llDetectedTouchUV(int index);
LSL_Integer llDetectedType(int number);
LSL_Vector llDetectedVel(int number);
void llDialog(string avatar, string message, LSL_List buttons, int chat_channel);
void llDie();
LSL_String llDumpList2String(LSL_List src, string seperator);
LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir);
void llEjectFromLand(string pest);
void llEmail(string address, string subject, string message);
LSL_String llEscapeURL(string url);
LSL_Rotation llEuler2Rot(LSL_Vector v);
LSL_Float llFabs(double f);
LSL_Integer llFloor(double f);
void llForceMouselook(int mouselook);
LSL_Float llFrand(double mag);
LSL_Key llGenerateKey();
LSL_Vector llGetAccel();
LSL_Integer llGetAgentInfo(string id);
LSL_String llGetAgentLanguage(string id);
LSL_List llGetAgentList(LSL_Integer scope, LSL_List options);
LSL_Vector llGetAgentSize(string id);
LSL_Float llGetAlpha(int face);
LSL_Float llGetAndResetTime();
LSL_String llGetAnimation(string id);
LSL_List llGetAnimationList(string id);
LSL_Integer llGetAttached();
LSL_List llGetBoundingBox(string obj);
LSL_Vector llGetCameraPos();
LSL_Rotation llGetCameraRot();
LSL_Vector llGetCenterOfMass();
LSL_Vector llGetColor(int face);
LSL_String llGetCreator();
LSL_String llGetDate();
LSL_String llGetDisplayName(string id);
LSL_Float llGetEnergy();
LSL_Vector llGetForce();
LSL_Integer llGetFreeMemory();
LSL_Integer llGetFreeURLs();
LSL_Vector llGetGeometricCenter();
LSL_Float llGetGMTclock();
LSL_String llGetHTTPHeader(LSL_Key request_id, string header);
LSL_Key llGetInventoryCreator(string item);
LSL_Key llGetInventoryKey(string name);
LSL_String llGetInventoryName(int type, int number);
LSL_Integer llGetInventoryNumber(int type);
LSL_Integer llGetInventoryPermMask(string item, int mask);
LSL_Integer llGetInventoryType(string name);
LSL_Key llGetKey();
LSL_Key llGetLandOwnerAt(LSL_Vector pos);
LSL_Key llGetLinkKey(int linknum);
LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules);
LSL_String llGetLinkName(int linknum);
LSL_Integer llGetLinkNumber();
LSL_Integer llGetLinkNumberOfSides(int link);
LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules);
LSL_Integer llGetListEntryType(LSL_List src, int index);
LSL_Integer llGetListLength(LSL_List src);
LSL_Vector llGetLocalPos();
LSL_Rotation llGetLocalRot();
LSL_Float llGetMass();
LSL_Integer llGetMemoryLimit();
void llGetNextEmail(string address, string subject);
LSL_String llGetNotecardLine(string name, int line);
LSL_Key llGetNumberOfNotecardLines(string name);
LSL_Integer llGetNumberOfPrims();
LSL_Integer llGetNumberOfSides();
LSL_String llGetObjectDesc();
LSL_List llGetObjectDetails(string id, LSL_List args);
LSL_Float llGetObjectMass(string id);
LSL_String llGetObjectName();
LSL_Integer llGetObjectPermMask(int mask);
LSL_Integer llGetObjectPrimCount(string object_id);
LSL_Vector llGetOmega();
LSL_Key llGetOwner();
LSL_Key llGetOwnerKey(string id);
LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param);
LSL_Integer llGetParcelFlags(LSL_Vector pos);
LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide);
LSL_String llGetParcelMusicURL();
LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide);
LSL_List llGetParcelPrimOwners(LSL_Vector pos);
LSL_Integer llGetPermissions();
LSL_Key llGetPermissionsKey();
LSL_Vector llGetPos();
LSL_List llGetPrimitiveParams(LSL_List rules);
LSL_List llGetPrimMediaParams(int face, LSL_List rules);
LSL_Integer llGetRegionAgentCount();
LSL_Vector llGetRegionCorner();
LSL_Integer llGetRegionFlags();
LSL_Float llGetRegionFPS();
LSL_String llGetRegionName();
LSL_Float llGetRegionTimeDilation();
LSL_Vector llGetRootPosition();
LSL_Rotation llGetRootRotation();
LSL_Rotation llGetRot();
LSL_Vector llGetScale();
LSL_String llGetScriptName();
LSL_Integer llGetScriptState(string name);
LSL_String llGetSimulatorHostname();
LSL_Integer llGetSPMaxMemory();
LSL_Integer llGetStartParameter();
LSL_Integer llGetStatus(int status);
LSL_String llGetSubString(string src, int start, int end);
LSL_Vector llGetSunDirection();
LSL_String llGetTexture(int face);
LSL_Vector llGetTextureOffset(int face);
LSL_Float llGetTextureRot(int side);
LSL_Vector llGetTextureScale(int side);
LSL_Float llGetTime();
LSL_Float llGetTimeOfDay();
LSL_String llGetTimestamp();
LSL_Vector llGetTorque();
LSL_Integer llGetUnixTime();
LSL_Integer llGetUsedMemory();
LSL_String llGetUsername(string id);
LSL_Vector llGetVel();
LSL_Float llGetWallclock();
void llGiveInventory(string destination, string inventory);
void llGiveInventoryList(string destination, string category, LSL_List inventory);
void llGiveMoney(string destination, int amount);
void llGodLikeRezObject(string inventory, LSL_Vector pos);
LSL_Float llGround(LSL_Vector offset);
LSL_Vector llGroundContour(LSL_Vector offset);
LSL_Vector llGroundNormal(LSL_Vector offset);
void llGroundRepel(double height, int water, double tau);
LSL_Vector llGroundSlope(LSL_Vector offset);
LSL_String llHTTPRequest(string url, LSL_List parameters, string body);
void llHTTPResponse(LSL_Key id, int status, string body);
LSL_String llInsertString(string dst, int position, string src);
void llInstantMessage(string user, string message);
LSL_String llIntegerToBase64(int number);
LSL_String llKey2Name(string id);
void llLinkParticleSystem(int linknum, LSL_List rules);
void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot);
LSL_String llList2CSV(LSL_List src);
LSL_Float llList2Float(LSL_List src, int index);
LSL_Integer llList2Integer(LSL_List src, int index);
LSL_Key llList2Key(LSL_List src, int index);
LSL_List llList2List(LSL_List src, int start, int end);
LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride);
LSL_Rotation llList2Rot(LSL_List src, int index);
LSL_String llList2String(LSL_List src, int index);
LSL_Vector llList2Vector(LSL_List src, int index);
LSL_Integer llListen(int channelID, string name, string ID, string msg);
void llListenControl(int number, int active);
void llListenRemove(int number);
LSL_Integer llListFindList(LSL_List src, LSL_List test);
LSL_List llListInsertList(LSL_List dest, LSL_List src, int start);
LSL_List llListRandomize(LSL_List src, int stride);
LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end);
LSL_List llListSort(LSL_List src, int stride, int ascending);
LSL_Float llListStatistics(int operation, LSL_List src);
void llLoadURL(string avatar_id, string message, string url);
LSL_Float llLog(double val);
LSL_Float llLog10(double val);
void llLookAt(LSL_Vector target, double strength, double damping);
void llLoopSound(string sound, double volume);
void llLoopSoundMaster(string sound, double volume);
void llLoopSoundSlave(string sound, double volume);
void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset);
void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
LSL_Integer llManageEstateAccess(int action, string avatar);
void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at);
LSL_String llMD5String(string src, int nonce);
void llMessageLinked(int linknum, int num, string str, string id);
void llMinEventDelay(double delay);
void llModifyLand(int action, int brush);
LSL_Integer llModPow(int a, int b, int c);
void llMoveToTarget(LSL_Vector target, double tau);
void llOffsetTexture(double u, double v, int face);
void llOpenRemoteDataChannel();
LSL_Integer llOverMyLand(string id);
void llOwnerSay(string msg);
void llParcelMediaCommandList(LSL_List commandList);
LSL_List llParcelMediaQuery(LSL_List aList);
LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers);
LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers);
void llParticleSystem(LSL_List rules);
void llPassCollisions(int pass);
void llPassTouches(int pass);
void llPlaySound(string sound, double volume);
void llPlaySoundSlave(string sound, double volume);
void llPointAt(LSL_Vector pos);
LSL_Float llPow(double fbase, double fexponent);
void llPreloadSound(string sound);
void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local);
void llRefreshPrimURL();
void llRegionSay(int channelID, string text);
void llRegionSayTo(string target, int channelID, string text);
void llReleaseCamera(string avatar);
void llReleaseControls();
void llReleaseURL(string url);
void llRemoteDataReply(string channel, string message_id, string sdata, int idata);
void llRemoteDataSetRegion();
void llRemoteLoadScript(string target, string name, int running, int start_param);
void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param);
void llRemoveFromLandBanList(string avatar);
void llRemoveFromLandPassList(string avatar);
void llRemoveInventory(string item);
void llRemoveVehicleFlags(int flags);
LSL_Key llRequestAgentData(string id, int data);
LSL_String llRequestDisplayName(string id);
LSL_Key llRequestInventoryData(string name);
void llRequestPermissions(string agent, int perm);
LSL_String llRequestSecureURL();
LSL_Key llRequestSimulatorData(string simulator, int data);
LSL_Key llRequestURL();
LSL_String llRequestUsername(string id);
void llResetLandBanList();
void llResetLandPassList();
void llResetOtherScript(string name);
void llResetScript();
void llResetTime();
void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param);
void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param);
LSL_Float llRot2Angle(LSL_Rotation rot);
LSL_Vector llRot2Axis(LSL_Rotation rot);
LSL_Vector llRot2Euler(LSL_Rotation r);
LSL_Vector llRot2Fwd(LSL_Rotation r);
LSL_Vector llRot2Left(LSL_Rotation r);
LSL_Vector llRot2Up(LSL_Rotation r);
void llRotateTexture(double rotation, int face);
LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end);
void llRotLookAt(LSL_Rotation target, double strength, double damping);
LSL_Integer llRotTarget(LSL_Rotation rot, double error);
void llRotTargetRemove(int number);
LSL_Integer llRound(double f);
LSL_Integer llSameGroup(string agent);
void llSay(int channelID, string text);
void llScaleTexture(double u, double v, int face);
LSL_Integer llScriptDanger(LSL_Vector pos);
void llScriptProfiler(LSL_Integer flag);
LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata);
void llSensor(string name, string id, int type, double range, double arc);
void llSensorRemove();
void llSensorRepeat(string name, string id, int type, double range, double arc, double rate);
void llSetAlpha(double alpha, int face);
void llSetAngularVelocity(LSL_Vector angularVelocity, int local);
void llSetBuoyancy(double buoyancy);
void llSetCameraAtOffset(LSL_Vector offset);
void llSetCameraEyeOffset(LSL_Vector offset);
void llSetCameraParams(LSL_List rules);
void llSetClickAction(int action);
void llSetColor(LSL_Vector color, int face);
void llSetContentType(LSL_Key id, LSL_Integer type);
void llSetDamage(double damage);
void llSetForce(LSL_Vector force, int local);
void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local);
void llSetHoverHeight(double height, int water, double tau);
void llSetInventoryPermMask(string item, int mask, int value);
void llSetKeyframedMotion(LSL_List frames, LSL_List options);
void llSetLinkAlpha(int linknumber, double alpha, int face);
void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at);
void llSetLinkColor(int linknumber, LSL_Vector color, int face);
LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules);
void llSetLinkPrimitiveParams(int linknumber, LSL_List rules);
void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules);
void llSetLinkTexture(int linknumber, string texture, int face);
void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate);
void llSetLocalRot(LSL_Rotation rot);
LSL_Integer llSetMemoryLimit(LSL_Integer limit);
void llSetObjectDesc(string desc);
void llSetObjectName(string name);
void llSetObjectPermMask(int mask, int value);
void llSetParcelMusicURL(string url);
void llSetPayPrice(int price, LSL_List quick_pay_buttons);
void llSetPos(LSL_Vector pos);
void llSetPrimitiveParams(LSL_List rules);
LSL_Integer llSetPrimMediaParams(LSL_Integer face, LSL_List rules);
void llSetPrimURL(string url);
LSL_Integer llSetRegionPos(LSL_Vector pos);
void llSetRemoteScriptAccessPin(int pin);
void llSetRot(LSL_Rotation rot);
void llSetScale(LSL_Vector scale);
void llSetScriptState(string name, int run);
void llSetSitText(string text);
void llSetSoundQueueing(int queue);
void llSetSoundRadius(double radius);
void llSetStatus(int status, int value);
void llSetText(string text, LSL_Vector color, double alpha);
void llSetTexture(string texture, int face);
void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate);
void llSetTimerEvent(double sec);
void llSetTorque(LSL_Vector torque, int local);
void llSetTouchText(string text);
void llSetVehicleFlags(int flags);
void llSetVehicleFloatParam(int param, LSL_Float value);
void llSetVehicleRotationParam(int param, LSL_Rotation rot);
void llSetVehicleType(int type);
void llSetVehicleVectorParam(int param, LSL_Vector vec);
void llSetVelocity(LSL_Vector velocity, int local);
LSL_String llSHA1String(string src);
void llShout(int channelID, string text);
LSL_Float llSin(double f);
void llSitTarget(LSL_Vector offset, LSL_Rotation rot);
void llSleep(double sec);
void llSound(string sound, double volume, int queue, int loop);
void llSoundPreload(string sound);
LSL_Float llSqrt(double f);
void llStartAnimation(string anim);
void llStopAnimation(string anim);
void llStopHover();
void llStopLookAt();
void llStopMoveToTarget();
void llStopPointAt();
void llStopSound();
LSL_Integer llStringLength(string str);
LSL_String llStringToBase64(string str);
LSL_String llStringTrim(string src, int type);
LSL_Integer llSubStringIndex(string source, string pattern);
void llTakeCamera(string avatar);
void llTakeControls(int controls, int accept, int pass_on);
LSL_Float llTan(double f);
LSL_Integer llTarget(LSL_Vector position, double range);
void llTargetOmega(LSL_Vector axis, double spinrate, double gain);
void llTargetRemove(int number);
void llTeleportAgent(string agent, string simname, LSL_Vector pos, LSL_Vector lookAt);
void llTeleportAgentGlobalCoords(string agent, LSL_Vector global, LSL_Vector pos, LSL_Vector lookAt);
void llTeleportAgentHome(string agent);
void llTextBox(string avatar, string message, int chat_channel);
LSL_String llToLower(string source);
LSL_String llToUpper(string source);
LSL_String llTransferLindenDollars(string destination, int amount);
void llTriggerSound(string sound, double volume);
void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west);
LSL_String llUnescapeURL(string url);
void llUnSit(string id);
LSL_Float llVecDist(LSL_Vector a, LSL_Vector b);
LSL_Float llVecMag(LSL_Vector v);
LSL_Vector llVecNorm(LSL_Vector v);
void llVolumeDetect(int detect);
LSL_Float llWater(LSL_Vector offset);
void llWhisper(int channelID, string text);
LSL_Vector llWind(LSL_Vector offset);
LSL_String llXorBase64Strings(string str1, string str2);
LSL_String llXorBase64StringsCorrect(string str1, string str2);
void print(string str);
void SetPrimitiveParamsEx(LSL_Key prim, LSL_List rules, string originFunc);
void state(string newState);
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
using System;
using System.Collections.Generic;
using IronScheme.Editor.CodeModel;
using IronScheme.Editor.ComponentModel;
namespace IronScheme.Editor.Languages
{
static class IronSchemeIdentifiers
{
readonly static List<SchemeId> ids;
public static ICodeElement[] GetR6RSIds(string line, int lci, IToken[] tokens, out string hint)
{
List<ICodeElement> filtered = new List<ICodeElement>();
foreach (IToken t in tokens)
{
if (t.Location.Column <= lci && t.Location.EndColumn >= lci)
{
hint = t.Text;
if (hint == "(" || hint == "[")
{
hint = "";
return ids.ToArray();
}
foreach (SchemeId id in ids)
{
if (id.Name.StartsWith(hint))
{
filtered.Add(id);
}
}
return filtered.ToArray();
}
}
hint = "";
return ids.ToArray();
}
static IronSchemeIdentifiers()
{
ids = new List<SchemeId>();
#region Huge list
string[] allids =
{
"import",
"library",
"expand",
"installed-libraries",
"library-path",
"library-exists?",
"library-locator",
"make-parameter",
"parameterize",
"clr-library-locator",
"lambda",
"and",
"begin",
"case",
"cond",
"define",
"define-syntax",
"identifier-syntax",
"if",
"let",
"let*",
"let*-values",
"let-syntax",
"let-values",
"letrec",
"letrec*",
"letrec-syntax",
"or",
"quasiquote",
"quote",
"set!",
"syntax-rules",
"unquote",
"unquote-splicing",
"<",
"<=",
"=",
">",
">=",
"+",
"-",
"*",
"/",
"abs",
"acos",
"angle",
"append",
"apply",
"asin",
"assert",
"assertion-violation",
"atan",
"boolean=?",
"boolean?",
"car",
"cdr",
"caar",
"cadr",
"cdar",
"cddr",
"caaar",
"caadr",
"cadar",
"caddr",
"cdaar",
"cdadr",
"cddar",
"cdddr",
"caaaar",
"caaadr",
"caadar",
"caaddr",
"cadaar",
"cadadr",
"caddar",
"cadddr",
"cdaaar",
"cdaadr",
"cdadar",
"cdaddr",
"cddaar",
"cddadr",
"cdddar",
"cddddr",
"call-with-current-continuation",
"call/cc",
"call-with-values",
"ceiling",
"char->integer",
"char<=?",
"char<?",
"char=?",
"char>=?",
"char>?",
"char?",
"complex?",
"cons",
"cos",
"denominator",
"div",
"mod",
"div-and-mod",
"div0",
"mod0",
"div0-and-mod0",
"dynamic-wind",
"eq?",
"equal?",
"eqv?",
"error",
"even?",
"exact",
"exact-integer-sqrt",
"exact?",
"exp",
"expt",
"finite?",
"floor",
"for-each",
"gcd",
"imag-part",
"inexact",
"inexact?",
"infinite?",
"integer->char",
"integer-valued?",
"integer?",
"lcm",
"length",
"list",
"list->string",
"list->vector",
"list-ref",
"list-tail",
"list?",
"log",
"magnitude",
"make-polar",
"make-rectangular",
"make-string",
"make-vector",
"map",
"max",
"min",
"nan?",
"negative?",
"not",
"null?",
"number->string",
"number?",
"numerator",
"odd?",
"pair?",
"positive?",
"procedure?",
"rational-valued?",
"rational?",
"rationalize",
"real-part",
"real-valued?",
"real?",
"reverse",
"round",
"sin",
"sqrt",
"string",
"string->list",
"string->number",
"string->symbol",
"string-append",
"string-copy",
"string-for-each",
"string-length",
"string-ref",
"string<=?",
"string<?",
"string=?",
"string>=?",
"string>?",
"string?",
"substring",
"symbol->string",
"symbol=?",
"symbol?",
"tan",
"truncate",
"values",
"vector",
"vector->list",
"vector-fill!",
"vector-for-each",
"vector-length",
"vector-map",
"vector-ref",
"vector-set!",
"vector?",
"zero?",
"...",
"=>",
"_",
"else",
"bitwise-arithmetic-shift",
"bitwise-arithmetic-shift-left",
"bitwise-arithmetic-shift-right",
"bitwise-not",
"bitwise-and",
"bitwise-ior",
"bitwise-xor",
"bitwise-bit-count",
"bitwise-bit-field",
"bitwise-bit-set?",
"bitwise-copy-bit",
"bitwise-copy-bit-field",
"bitwise-first-bit-set",
"bitwise-if",
"bitwise-length",
"bitwise-reverse-bit-field",
"bitwise-rotate-bit-field",
"fixnum?",
"fixnum-width",
"least-fixnum",
"greatest-fixnum",
"fx*",
"fx*/carry",
"fx+",
"fx+/carry",
"fx-",
"fx-/carry",
"fx<=?",
"fx<?",
"fx=?",
"fx>=?",
"fx>?",
"fxand",
"fxarithmetic-shift",
"fxarithmetic-shift-left",
"fxarithmetic-shift-right",
"fxbit-count",
"fxbit-field",
"fxbit-set?",
"fxcopy-bit",
"fxcopy-bit-field",
"fxdiv",
"fxdiv-and-mod",
"fxdiv0",
"fxdiv0-and-mod0",
"fxeven?",
"fxfirst-bit-set",
"fxif",
"fxior",
"fxlength",
"fxmax",
"fxmin",
"fxmod",
"fxmod0",
"fxnegative?",
"fxnot",
"fxodd?",
"fxpositive?",
"fxreverse-bit-field",
"fxrotate-bit-field",
"fxxor",
"fxzero?",
"fixnum->flonum",
"fl*",
"fl+",
"fl-",
"fl/",
"fl<=?",
"fl<?",
"fl=?",
"fl>=?",
"fl>?",
"flabs",
"flacos",
"flasin",
"flatan",
"flceiling",
"flcos",
"fldenominator",
"fldiv",
"fldiv-and-mod",
"fldiv0",
"fldiv0-and-mod0",
"fleven?",
"flexp",
"flexpt",
"flfinite?",
"flfloor",
"flinfinite?",
"flinteger?",
"fllog",
"flmax",
"flmin",
"flmod",
"flmod0",
"flnan?",
"flnegative?",
"flnumerator",
"flodd?",
"flonum?",
"flpositive?",
"flround",
"flsin",
"flsqrt",
"fltan",
"fltruncate",
"flzero?",
"real->flonum",
"make-no-infinities-violation",
"make-no-nans-violation",
"&no-infinities",
"no-infinities-violation?",
"&no-nans",
"no-nans-violation?",
"bytevector->sint-list",
"bytevector->u8-list",
"bytevector->uint-list",
"bytevector-copy",
"bytevector-copy!",
"bytevector-fill!",
"bytevector-ieee-double-native-ref",
"bytevector-ieee-double-native-set!",
"bytevector-ieee-double-ref",
"bytevector-ieee-double-set!",
"bytevector-ieee-single-native-ref",
"bytevector-ieee-single-native-set!",
"bytevector-ieee-single-ref",
"bytevector-ieee-single-set!",
"bytevector-length",
"bytevector-s16-native-ref",
"bytevector-s16-native-set!",
"bytevector-s16-ref",
"bytevector-s16-set!",
"bytevector-s32-native-ref",
"bytevector-s32-native-set!",
"bytevector-s32-ref",
"bytevector-s32-set!",
"bytevector-s64-native-ref",
"bytevector-s64-native-set!",
"bytevector-s64-ref",
"bytevector-s64-set!",
"bytevector-s8-ref",
"bytevector-s8-set!",
"bytevector-sint-ref",
"bytevector-sint-set!",
"bytevector-u16-native-ref",
"bytevector-u16-native-set!",
"bytevector-u16-ref",
"bytevector-u16-set!",
"bytevector-u32-native-ref",
"bytevector-u32-native-set!",
"bytevector-u32-ref",
"bytevector-u32-set!",
"bytevector-u64-native-ref",
"bytevector-u64-native-set!",
"bytevector-u64-ref",
"bytevector-u64-set!",
"bytevector-u8-ref",
"bytevector-u8-set!",
"bytevector-uint-ref",
"bytevector-uint-set!",
"bytevector=?",
"bytevector?",
"endianness",
"native-endianness",
"sint-list->bytevector",
"string->utf16",
"string->utf32",
"string->utf8",
"u8-list->bytevector",
"uint-list->bytevector",
"utf8->string",
"utf16->string",
"utf32->string",
"condition?",
"&assertion",
"assertion-violation?",
"&condition",
"condition",
"condition-accessor",
"condition-irritants",
"condition-message",
"condition-predicate",
"condition-who",
"define-condition-type",
"&error",
"error?",
"&implementation-restriction",
"implementation-restriction-violation?",
"&irritants",
"irritants-condition?",
"&lexical",
"lexical-violation?",
"make-assertion-violation",
"make-error",
"make-implementation-restriction-violation",
"make-irritants-condition",
"make-lexical-violation",
"make-message-condition",
"make-non-continuable-violation",
"make-serious-condition",
"make-syntax-violation",
"make-undefined-violation",
"make-violation",
"make-warning",
"make-who-condition",
"&message",
"message-condition?",
"&non-continuable",
"non-continuable-violation?",
"&serious",
"serious-condition?",
"simple-conditions",
"&syntax",
"syntax-violation",
"syntax-violation-form",
"syntax-violation-subform",
"syntax-violation?",
"&undefined",
"undefined-violation?",
"&violation",
"violation?",
"&warning",
"warning?",
"&who",
"who-condition?",
"case-lambda",
"do",
"unless",
"when",
"define-enumeration",
"enum-set->list",
"enum-set-complement",
"enum-set-constructor",
"enum-set-difference",
"enum-set-indexer",
"enum-set-intersection",
"enum-set-member?",
"enum-set-projection",
"enum-set-subset?",
"enum-set-union",
"enum-set-universe",
"enum-set=?",
"make-enumeration",
"environment",
"eval",
"raise",
"raise-continuable",
"with-exception-handler",
"guard",
"assoc",
"assp",
"assq",
"assv",
"cons*",
"filter",
"find",
"fold-left",
"fold-right",
"for-all",
"exists",
"member",
"memp",
"memq",
"memv",
"partition",
"remq",
"remp",
"remv",
"remove",
"set-car!",
"set-cdr!",
"string-set!",
"string-fill!",
"command-line",
"exit",
"delay",
"exact->inexact",
"force",
"inexact->exact",
"modulo",
"remainder",
"null-environment",
"quotient",
"scheme-report-environment",
"binary-port?",
"buffer-mode",
"buffer-mode?",
"bytevector->string",
"call-with-bytevector-output-port",
"call-with-port",
"call-with-string-output-port",
"close-port",
"eol-style",
"error-handling-mode",
"file-options",
"flush-output-port",
"get-bytevector-all",
"get-bytevector-n",
"get-bytevector-n!",
"get-bytevector-some",
"get-char",
"get-datum",
"get-line",
"get-string-all",
"get-string-n",
"get-string-n!",
"get-u8",
"&i/o",
"&i/o-decoding",
"i/o-decoding-error?",
"&i/o-encoding",
"i/o-encoding-error-char",
"i/o-encoding-error?",
"i/o-error-filename",
"i/o-error-port",
"i/o-error?",
"&i/o-file-already-exists",
"i/o-file-already-exists-error?",
"&i/o-file-does-not-exist",
"i/o-file-does-not-exist-error?",
"&i/o-file-is-read-only",
"i/o-file-is-read-only-error?",
"&i/o-file-protection",
"i/o-file-protection-error?",
"&i/o-filename",
"i/o-filename-error?",
"&i/o-invalid-position",
"i/o-invalid-position-error?",
"&i/o-port",
"i/o-port-error?",
"&i/o-read",
"i/o-read-error?",
"&i/o-write",
"i/o-write-error?",
"lookahead-char",
"lookahead-u8",
"make-bytevector",
"make-custom-binary-input-port",
"make-custom-binary-input/output-port",
"make-custom-binary-output-port",
"make-custom-textual-input-port",
"make-custom-textual-input/output-port",
"make-custom-textual-output-port",
"make-i/o-decoding-error",
"make-i/o-encoding-error",
"make-i/o-error",
"make-i/o-file-already-exists-error",
"make-i/o-file-does-not-exist-error",
"make-i/o-file-is-read-only-error",
"make-i/o-file-protection-error",
"make-i/o-filename-error",
"make-i/o-invalid-position-error",
"make-i/o-port-error",
"make-i/o-read-error",
"make-i/o-write-error",
"latin-1-codec",
"make-transcoder",
"native-eol-style",
"native-transcoder",
"open-bytevector-input-port",
"open-bytevector-output-port",
"open-file-input-port",
"open-file-input/output-port",
"open-file-output-port",
"open-string-input-port",
"open-string-output-port",
"output-port-buffer-mode",
"port-eof?",
"port-has-port-position?",
"port-has-set-port-position!?",
"port-position",
"port-transcoder",
"port?",
"put-bytevector",
"put-char",
"put-datum",
"put-string",
"put-u8",
"set-port-position!",
"standard-error-port",
"standard-input-port",
"standard-output-port",
"string->bytevector",
"textual-port?",
"transcoded-port",
"transcoder-codec",
"transcoder-eol-style",
"transcoder-error-handling-mode",
"utf-16-codec",
"utf-8-codec",
"input-port?",
"output-port?",
"current-input-port",
"current-output-port",
"current-error-port",
"eof-object",
"eof-object?",
"close-input-port",
"close-output-port",
"display",
"newline",
"open-input-file",
"open-output-file",
"peek-char",
"read",
"read-char",
"with-input-from-file",
"with-output-to-file",
"write",
"write-char",
"call-with-input-file",
"call-with-output-file",
"hashtable-clear!",
"hashtable-contains?",
"hashtable-copy",
"hashtable-delete!",
"hashtable-entries",
"hashtable-keys",
"hashtable-mutable?",
"hashtable-ref",
"hashtable-set!",
"hashtable-size",
"hashtable-update!",
"hashtable?",
"make-eq-hashtable",
"make-eqv-hashtable",
"hashtable-hash-function",
"make-hashtable",
"hashtable-equivalence-function",
"equal-hash",
"string-hash",
"string-ci-hash",
"symbol-hash",
"list-sort",
"vector-sort",
"vector-sort!",
"file-exists?",
"delete-file",
"define-record-type",
"fields",
"immutable",
"mutable",
"opaque",
"parent",
"parent-rtd",
"protocol",
"record-constructor-descriptor",
"record-type-descriptor",
"sealed",
"nongenerative",
"record-field-mutable?",
"record-rtd",
"record-type-field-names",
"record-type-generative?",
"record-type-name",
"record-type-opaque?",
"record-type-parent",
"record-type-sealed?",
"record-type-uid",
"record?",
"make-record-constructor-descriptor",
"make-record-type-descriptor",
"record-accessor",
"record-constructor",
"record-mutator",
"record-predicate",
"record-type-descriptor?",
"bound-identifier=?",
"datum->syntax",
"syntax",
"syntax->datum",
"syntax-case",
"unsyntax",
"unsyntax-splicing",
"quasisyntax",
"with-syntax",
"free-identifier=?",
"generate-temporaries",
"identifier?",
"make-variable-transformer",
"char-alphabetic?",
"char-ci<=?",
"char-ci<?",
"char-ci=?",
"char-ci>=?",
"char-ci>?",
"char-downcase",
"char-foldcase",
"char-titlecase",
"char-upcase",
"char-general-category",
"char-lower-case?",
"char-numeric?",
"char-title-case?",
"char-upper-case?",
"char-whitespace?",
"string-ci<=?",
"string-ci<?",
"string-ci=?",
"string-ci>=?",
"string-ci>?",
"string-downcase",
"string-foldcase",
"string-normalize-nfc",
"string-normalize-nfd",
"string-normalize-nfkc",
"string-normalize-nfkd",
"string-titlecase",
"string-upcase",
"load",
"void",
"pretty-print",
"ironscheme-build",
"stacktrace",
"load-r5rs",
"last-pair",
"clr-call",
"clr-static-call",
"clr-cast",
"clr-new",
"clr-foreach",
"make-list",
"read-annotated",
"annotation?",
"annotation-expression",
"annotation-source",
"annotation-stripped",
};
#endregion
Array.Sort(allids);
foreach (string id in allids)
{
Add(id);
}
}
[Image("CodeMethod.png")]
class SchemeId : CodeElement
{
public SchemeId(string name)
{
Name = name;
Tag = name;
}
}
static void Add(string id)
{
ids.Add(new SchemeId(id));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using FluentNHibernate.Testing.Values;
using FluentNHibernate.Utils;
using System.Collections;
using FluentNHibernate.Utils.Reflection;
namespace FluentNHibernate.Testing
{
public static class PersistenceSpecificationExtensions
{
public static PersistenceSpecification<T> CheckProperty<T>(this PersistenceSpecification<T> spec,
Expression<Func<T, object>> expression, object propertyValue)
{
return spec.CheckProperty(expression, propertyValue, (IEqualityComparer)null);
}
public static PersistenceSpecification<T> CheckProperty<T>(this PersistenceSpecification<T> spec,
Expression<Func<T, object>> expression, object propertyValue,
IEqualityComparer propertyComparer)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
return spec.RegisterCheckedProperty(new Property<T, object>(property, propertyValue), propertyComparer);
}
public static PersistenceSpecification<T> CheckProperty<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, Array>> expression,
IEnumerable<TListElement> propertyValue)
{
return spec.CheckProperty(expression, propertyValue, null);
}
public static PersistenceSpecification<T> CheckProperty<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, Array>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
return spec.RegisterCheckedProperty(new List<T, TListElement>(property, propertyValue), elementComparer);
}
public static PersistenceSpecification<T> CheckProperty<T, TProperty>(this PersistenceSpecification<T> spec,
Expression<Func<T, TProperty>> expression,
TProperty propertyValue,
Action<T, TProperty> propertySetter)
{
return spec.CheckProperty(expression, propertyValue, null, propertySetter);
}
public static PersistenceSpecification<T> CheckProperty<T, TProperty>(this PersistenceSpecification<T> spec,
Expression<Func<T, TProperty>> expression,
TProperty propertyValue,
IEqualityComparer propertyComparer,
Action<T, TProperty> propertySetter)
{
Accessor propertyInfoFromExpression = ReflectionHelper.GetAccessor(expression);
var property = new Property<T, TProperty>(propertyInfoFromExpression, propertyValue);
property.ValueSetter = (target, propertyInfo, value) => propertySetter(target, value);
return spec.RegisterCheckedProperty(property, propertyComparer);
}
public static PersistenceSpecification<T> CheckReference<T>(this PersistenceSpecification<T> spec,
Expression<Func<T, object>> expression,
object propertyValue)
{
return spec.CheckReference(expression, propertyValue, (IEqualityComparer)null);
}
public static PersistenceSpecification<T> CheckReference<T>(this PersistenceSpecification<T> spec,
Expression<Func<T, object>> expression,
object propertyValue,
IEqualityComparer propertyComparer)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
return spec.RegisterCheckedProperty(new ReferenceProperty<T, object>(property, propertyValue), propertyComparer);
}
public static PersistenceSpecification<T> CheckReference<T, TReference>(this PersistenceSpecification<T> spec,
Expression<Func<T, object>> expression,
TReference propertyValue,
params Func<TReference, object>[] propertiesToCompare)
{
// Because of the params keyword, the compiler will select this overload
// instead of the one above, even when no funcs are supplied in the method call.
if (propertiesToCompare == null || propertiesToCompare.Length == 0)
return spec.CheckReference(expression, propertyValue, (IEqualityComparer)null);
return spec.CheckReference(expression, propertyValue, new FuncEqualityComparer<TReference>(propertiesToCompare));
}
public static PersistenceSpecification<T> CheckReference<T, TProperty>(this PersistenceSpecification<T> spec,
Expression<Func<T, TProperty>> expression,
TProperty propertyValue,
Action<T, TProperty> propertySetter)
{
return spec.CheckReference(expression, propertyValue, null, propertySetter);
}
public static PersistenceSpecification<T> CheckReference<T, TProperty>(this PersistenceSpecification<T> spec,
Expression<Func<T, TProperty>> expression,
TProperty propertyValue,
IEqualityComparer propertyComparer,
Action<T, TProperty> propertySetter)
{
Accessor propertyInfoFromExpression = ReflectionHelper.GetAccessor(expression);
var property = new ReferenceProperty<T, TProperty>(propertyInfoFromExpression, propertyValue);
property.ValueSetter = (target, propertyInfo, value) => propertySetter(target, value);
return spec.RegisterCheckedProperty(property, propertyComparer);
}
public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue)
{
return spec.CheckList(expression, propertyValue, (IEqualityComparer)null);
}
public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
return spec.RegisterCheckedProperty(new ReferenceList<T, TListElement>(property, propertyValue), elementComparer);
}
public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
params Func<TListElement, object>[] propertiesToCompare)
{
// Because of the params keyword, the compiler can select this overload
// instead of the one above, even when no funcs are supplied in the method call.
if (propertiesToCompare == null || propertiesToCompare.Length == 0)
return spec.CheckList(expression, propertyValue, (IEqualityComparer)null);
return spec.CheckList(expression, propertyValue, new FuncEqualityComparer<TListElement>(propertiesToCompare));
}
public static PersistenceSpecification<T> CheckInverseList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
return spec.RegisterCheckedPropertyWithoutTransactionalSave(new ReferenceList<T, TListElement>(property, propertyValue), elementComparer);
}
public static PersistenceSpecification<T> CheckInverseList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
params Func<TListElement, object>[] propertiesToCompare)
{
// Because of the params keyword, the compiler can select this overload
// instead of the one above, even when no funcs are supplied in the method call.
if (propertiesToCompare == null || propertiesToCompare.Length == 0)
return spec.CheckList(expression, propertyValue, (IEqualityComparer)null);
return spec.CheckInverseList(expression, propertyValue, new FuncEqualityComparer<TListElement>(propertiesToCompare));
}
public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
Action<T, TListElement> listItemSetter)
{
return spec.CheckList(expression, propertyValue, null, listItemSetter);
}
public static PersistenceSpecification<T> CheckInverseList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
Action<T, TListElement> listItemSetter)
{
return spec.CheckInverseList(expression, propertyValue, null, listItemSetter);
}
public static PersistenceSpecification<T> CheckInverseList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer,
Action<T, TListElement> listItemSetter)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
var list = new ReferenceList<T, TListElement>(property, propertyValue);
list.ValueSetter = (target, propertyInfo, value) =>
{
foreach (var item in value)
{
listItemSetter(target, item);
}
};
return spec.RegisterCheckedPropertyWithoutTransactionalSave(list, elementComparer);
}
public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer,
Action<T, TListElement> listItemSetter)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
var list = new ReferenceList<T, TListElement>(property, propertyValue);
list.ValueSetter = (target, propertyInfo, value) =>
{
foreach(var item in value)
{
listItemSetter(target, item);
}
};
return spec.RegisterCheckedProperty(list, elementComparer);
}
public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
Action<T, IEnumerable<TListElement>> listSetter)
{
return spec.CheckList(expression, propertyValue, null, listSetter);
}
public static PersistenceSpecification<T> CheckList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer,
Action<T, IEnumerable<TListElement>> listSetter)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
var list = new ReferenceList<T, TListElement>(property, propertyValue);
list.ValueSetter = (target, propertyInfo, value) => listSetter(target, value);
return spec.RegisterCheckedProperty(list, elementComparer);
}
public static PersistenceSpecification<T> CheckInverseBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue)
{
return spec.CheckInverseBag(expression, propertyValue, (IEqualityComparer)null);
}
public static PersistenceSpecification<T> CheckInverseBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
return spec.RegisterCheckedPropertyWithoutTransactionalSave(new ReferenceBag<T, TListElement>(property, propertyValue), elementComparer);
}
public static PersistenceSpecification<T> CheckInverseBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
params Func<TListElement, object>[] propertiesToCompare)
{
// Because of the params keyword, the compiler can select this overload
// instead of the one above, even when no funcs are supplied in the method call.
if (propertiesToCompare == null || propertiesToCompare.Length == 0)
return spec.CheckInverseBag(expression, propertyValue, (IEqualityComparer)null);
return spec.CheckInverseBag(expression, propertyValue, new FuncEqualityComparer<TListElement>(propertiesToCompare));
}
public static PersistenceSpecification<T> CheckInverseBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
Action<T, TListElement> listItemSetter)
{
return spec.CheckInverseBag(expression, propertyValue, null, listItemSetter);
}
public static PersistenceSpecification<T> CheckInverseBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
Action<T, IEnumerable<TListElement>> listSetter)
{
return spec.CheckInverseBag(expression, propertyValue, null, listSetter);
}
public static PersistenceSpecification<T> CheckInverseBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer,
Action<T, TListElement> listItemSetter)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
var list = new ReferenceBag<T, TListElement>(property, propertyValue);
list.ValueSetter = (target, propertyInfo, value) =>
{
foreach (var item in value)
{
listItemSetter(target, item);
}
};
return spec.RegisterCheckedPropertyWithoutTransactionalSave(list, elementComparer);
}
public static PersistenceSpecification<T> CheckInverseBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer,
Action<T, IEnumerable<TListElement>> listSetter)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
var list = new ReferenceBag<T, TListElement>(property, propertyValue);
list.ValueSetter = (target, propertyInfo, value) => listSetter(target, value);
return spec.RegisterCheckedPropertyWithoutTransactionalSave(list, elementComparer);
}
public static PersistenceSpecification<T> CheckBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue)
{
return spec.CheckBag(expression, propertyValue, (IEqualityComparer)null);
}
public static PersistenceSpecification<T> CheckBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
return spec.RegisterCheckedProperty(new ReferenceBag<T, TListElement>(property, propertyValue), elementComparer);
}
public static PersistenceSpecification<T> CheckBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
params Func<TListElement, object>[] propertiesToCompare)
{
// Because of the params keyword, the compiler can select this overload
// instead of the one above, even when no funcs are supplied in the method call.
if (propertiesToCompare == null || propertiesToCompare.Length == 0)
return spec.CheckBag(expression, propertyValue, (IEqualityComparer)null);
return spec.CheckBag(expression, propertyValue, new FuncEqualityComparer<TListElement>(propertiesToCompare));
}
public static PersistenceSpecification<T> CheckBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
Action<T, TListElement> listItemSetter)
{
return spec.CheckBag(expression, propertyValue, null, listItemSetter);
}
public static PersistenceSpecification<T> CheckBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
Action<T, IEnumerable<TListElement>> listSetter)
{
return spec.CheckBag(expression, propertyValue, null, listSetter);
}
public static PersistenceSpecification<T> CheckBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer,
Action<T, TListElement> listItemSetter)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
var list = new ReferenceBag<T, TListElement>(property, propertyValue);
list.ValueSetter = (target, propertyInfo, value) =>
{
foreach (var item in value)
{
listItemSetter(target, item);
}
};
return spec.RegisterCheckedProperty(list, elementComparer);
}
public static PersistenceSpecification<T> CheckBag<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T,IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer,
Action<T, IEnumerable<TListElement>> listSetter)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
var list = new ReferenceBag<T, TListElement>(property, propertyValue);
list.ValueSetter = (target, propertyInfo, value) => listSetter(target, value);
return spec.RegisterCheckedProperty(list, elementComparer);
}
public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, object>> expression,
IEnumerable<TListElement> propertyValue)
{
return spec.CheckComponentList(expression, propertyValue, null);
}
/// <summary>
/// Checks a list of components for validity.
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
/// <typeparam name="TListElement">Type of list element</typeparam>
/// <param name="spec">Persistence specification</param>
/// <param name="expression">Property</param>
/// <param name="propertyValue">Value to save</param>
/// <param name="elementComparer">Equality comparer</param>
public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, object>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
return spec.RegisterCheckedProperty(new List<T, TListElement>(property, propertyValue), elementComparer);
}
public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
Action<T, TListElement> listItemSetter)
{
return spec.CheckComponentList(expression, propertyValue, null, listItemSetter);
}
public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer,
Action<T, TListElement> listItemSetter)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
var list = new List<T, TListElement>(property, propertyValue);
list.ValueSetter = (target, propertyInfo, value) => {
foreach(var item in value) {
listItemSetter(target, item);
}
};
return spec.RegisterCheckedProperty(list, elementComparer);
}
public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
Action<T, IEnumerable<TListElement>> listSetter)
{
return spec.CheckComponentList(expression, propertyValue, null, listSetter);
}
public static PersistenceSpecification<T> CheckComponentList<T, TListElement>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TListElement>>> expression,
IEnumerable<TListElement> propertyValue,
IEqualityComparer elementComparer,
Action<T, IEnumerable<TListElement>> listSetter)
{
Accessor property = ReflectionHelper.GetAccessor(expression);
var list = new List<T, TListElement>(property, propertyValue);
list.ValueSetter = (target, propertyInfo, value) => listSetter(target, value);
return spec.RegisterCheckedProperty(list, elementComparer);
}
[Obsolete("CheckEnumerable has been replaced with CheckList")]
public static PersistenceSpecification<T> CheckEnumerable<T, TItem>(this PersistenceSpecification<T> spec,
Expression<Func<T, IEnumerable<TItem>>> expression,
Action<T, TItem> addAction,
IEnumerable<TItem> itemsToAdd)
{
return spec.CheckList(expression, itemsToAdd, addAction);
}
private class FuncEqualityComparer<T> : EqualityComparer<T>
{
readonly IEnumerable<Func<T, object>> comparisons;
public FuncEqualityComparer(IEnumerable<Func<T, object>> comparisons)
{
this.comparisons = comparisons;
}
public override bool Equals(T x, T y)
{
return comparisons.All(func => object.Equals(func(x), func(y)));
}
public override int GetHashCode(T obj)
{
throw new NotSupportedException();
}
}
}
}
| |
// <copyright>
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
namespace System.ServiceModel.Channels
{
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.WebSockets;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Security.Principal;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.ServiceModel.Security;
using System.Threading;
using System.Threading.Tasks;
abstract class WebSocketTransportDuplexSessionChannel : TransportDuplexSessionChannel
{
static AsyncCallback streamedWriteCallback = Fx.ThunkCallback(StreamWriteCallback);
WebSocket webSocket = null;
WebSocketTransportSettings webSocketSettings;
TransferMode transferMode;
int maxBufferSize;
WaitCallback waitCallback;
object state;
WebSocketStream webSocketStream;
byte[] internalBuffer;
ConnectionBufferPool bufferPool;
int cleanupStatus = WebSocketHelper.OperationNotStarted;
ITransportFactorySettings transportFactorySettings;
WebSocketCloseDetails webSocketCloseDetails = new WebSocketCloseDetails();
bool shouldDisposeWebSocketAfterClosed = true;
Exception pendingWritingMessageException;
public WebSocketTransportDuplexSessionChannel(HttpChannelListener channelListener, EndpointAddress localAddress, Uri localVia, ConnectionBufferPool bufferPool)
: base(channelListener, channelListener, localAddress, localVia, EndpointAddress.AnonymousAddress, channelListener.MessageVersion.Addressing.AnonymousUri)
{
Fx.Assert(channelListener.WebSocketSettings != null, "channelListener.WebSocketTransportSettings should not be null.");
this.webSocketSettings = channelListener.WebSocketSettings;
this.transferMode = channelListener.TransferMode;
this.maxBufferSize = channelListener.MaxBufferSize;
this.bufferPool = bufferPool;
this.transportFactorySettings = channelListener;
}
public WebSocketTransportDuplexSessionChannel(HttpChannelFactory<IDuplexSessionChannel> channelFactory, EndpointAddress remoteAddresss, Uri via, ConnectionBufferPool bufferPool)
: base(channelFactory, channelFactory, EndpointAddress.AnonymousAddress, channelFactory.MessageVersion.Addressing.AnonymousUri, remoteAddresss, via)
{
Fx.Assert(channelFactory.WebSocketSettings != null, "channelFactory.WebSocketTransportSettings should not be null.");
this.webSocketSettings = channelFactory.WebSocketSettings;
this.transferMode = channelFactory.TransferMode;
this.maxBufferSize = channelFactory.MaxBufferSize;
this.bufferPool = bufferPool;
this.transportFactorySettings = channelFactory;
}
protected WebSocket WebSocket
{
get
{
return this.webSocket;
}
set
{
Fx.Assert(value != null, "value should not be null.");
Fx.Assert(this.webSocket == null, "webSocket should not be set before this set call.");
this.webSocket = value;
}
}
protected WebSocketTransportSettings WebSocketSettings
{
get { return this.webSocketSettings; }
}
protected TransferMode TransferMode
{
get { return this.transferMode; }
}
protected int MaxBufferSize
{
get
{
return this.maxBufferSize;
}
}
protected ITransportFactorySettings TransportFactorySettings
{
get
{
return this.transportFactorySettings;
}
}
protected byte[] InternalBuffer
{
get
{
return this.internalBuffer;
}
set
{
// We allow setting the property to null as long as we don't overwrite an existing non-null 'internalBuffer'. Because otherwise
// we get NullRefs in other places. So if you change/remove the assert below, make sure we still assert for this case.
Fx.Assert(this.internalBuffer == null, "internalBuffer should not be set twice.");
this.internalBuffer = value;
}
}
protected bool ShouldDisposeWebSocketAfterClosed
{
set
{
this.shouldDisposeWebSocketAfterClosed = value;
}
}
protected override void OnAbort()
{
if (TD.WebSocketConnectionAbortedIsEnabled())
{
TD.WebSocketConnectionAborted(
this.EventTraceActivity,
this.WebSocket != null ? this.WebSocket.GetHashCode() : -1);
}
this.Cleanup();
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(IWebSocketCloseDetails))
{
return this.webSocketCloseDetails as T;
}
return base.GetProperty<T>();
}
protected override void CompleteClose(TimeSpan timeout)
{
if (TD.WebSocketCloseSentIsEnabled())
{
TD.WebSocketCloseSent(
this.WebSocket.GetHashCode(),
this.webSocketCloseDetails.OutputCloseStatus.ToString(),
this.RemoteAddress != null ? this.RemoteAddress.ToString() : string.Empty);
}
Task closeTask = this.CloseAsync();
closeTask.Wait(timeout, WebSocketHelper.ThrowCorrectException, WebSocketHelper.CloseOperation);
if (TD.WebSocketConnectionClosedIsEnabled())
{
TD.WebSocketConnectionClosed(this.WebSocket.GetHashCode());
}
}
protected byte[] TakeBuffer()
{
Fx.Assert(this.bufferPool != null, "'bufferPool' MUST NOT be NULL.");
return this.bufferPool.Take();
}
protected override void CloseOutputSessionCore(TimeSpan timeout)
{
if (TD.WebSocketCloseOutputSentIsEnabled())
{
TD.WebSocketCloseOutputSent(
this.WebSocket.GetHashCode(),
this.webSocketCloseDetails.OutputCloseStatus.ToString(),
this.RemoteAddress != null ? this.RemoteAddress.ToString() : string.Empty);
}
Task task = this.CloseOutputAsync(CancellationToken.None);
task.Wait(timeout, WebSocketHelper.ThrowCorrectException, WebSocketHelper.CloseOperation);
}
protected override void OnClose(TimeSpan timeout)
{
try
{
base.OnClose(timeout);
}
finally
{
this.Cleanup();
}
}
protected override void ReturnConnectionIfNecessary(bool abort, TimeSpan timeout)
{
}
protected override AsyncCompletionResult StartWritingBufferedMessage(Message message, ArraySegment<byte> messageData, bool allowOutputBatching, TimeSpan timeout, Threading.WaitCallback callback, object state)
{
Fx.Assert(callback != null, "callback should not be null.");
TimeoutHelper helper = new TimeoutHelper(timeout);
WebSocketMessageType outgoingMessageType = GetWebSocketMessageType(message);
IOThreadCancellationTokenSource cancellationTokenSource = new IOThreadCancellationTokenSource(helper.RemainingTime());
if (TD.WebSocketAsyncWriteStartIsEnabled())
{
TD.WebSocketAsyncWriteStart(
this.WebSocket.GetHashCode(),
messageData.Count,
this.RemoteAddress != null ? this.RemoteAddress.ToString() : string.Empty);
}
Task task = this.WebSocket.SendAsync(messageData, outgoingMessageType, true, cancellationTokenSource.Token);
Fx.Assert(this.pendingWritingMessageException == null, "'pendingWritingMessageException' MUST be NULL at this point.");
task.ContinueWith(t =>
{
try
{
if (TD.WebSocketAsyncWriteStopIsEnabled())
{
TD.WebSocketAsyncWriteStop(this.webSocket.GetHashCode());
}
cancellationTokenSource.Dispose();
WebSocketHelper.ThrowExceptionOnTaskFailure(t, timeout, WebSocketHelper.SendOperation);
}
catch (Exception error)
{
// Intentionally not following the usual pattern to rethrow fatal exceptions.
// Any rethrown exception would just be ----ed, because nobody awaits the
// Task returned from ContinueWith in this case.
FxTrace.Exception.TraceHandledException(error, TraceEventType.Information);
this.pendingWritingMessageException = error;
}
finally
{
callback.Invoke(state);
}
}, CancellationToken.None);
return AsyncCompletionResult.Queued;
}
protected override void FinishWritingMessage()
{
ThrowOnPendingException(ref this.pendingWritingMessageException);
base.FinishWritingMessage();
}
protected override AsyncCompletionResult StartWritingStreamedMessage(Message message, TimeSpan timeout, WaitCallback callback, object state)
{
TimeoutHelper helper = new TimeoutHelper(timeout);
WebSocketMessageType outgoingMessageType = GetWebSocketMessageType(message);
WebSocketStream webSocketStream = new WebSocketStream(this.WebSocket, outgoingMessageType, helper.RemainingTime());
this.waitCallback = callback;
this.state = state;
this.webSocketStream = webSocketStream;
IAsyncResult result = this.MessageEncoder.BeginWriteMessage(message, new TimeoutStream(webSocketStream, ref helper), streamedWriteCallback, this);
if (!result.CompletedSynchronously)
{
return AsyncCompletionResult.Queued;
}
this.MessageEncoder.EndWriteMessage(result);
webSocketStream.WriteEndOfMessageAsync(helper.RemainingTime(), callback, state);
return AsyncCompletionResult.Queued;
}
protected override AsyncCompletionResult BeginCloseOutput(TimeSpan timeout, Threading.WaitCallback callback, object state)
{
Fx.Assert(callback != null, "callback should not be null.");
IOThreadCancellationTokenSource cancellationTokenSource = new IOThreadCancellationTokenSource(timeout);
Task task = this.CloseOutputAsync(cancellationTokenSource.Token);
Fx.Assert(this.pendingWritingMessageException == null, "'pendingWritingMessageException' MUST be NULL at this point.");
task.ContinueWith(t =>
{
try
{
cancellationTokenSource.Dispose();
WebSocketHelper.ThrowExceptionOnTaskFailure(t, timeout, WebSocketHelper.CloseOperation);
}
catch (Exception error)
{
// Intentionally not following the usual pattern to rethrow fatal exceptions.
// Any rethrown exception would just be ----ed, because nobody awaits the
// Task returned from ContinueWith in this case.
FxTrace.Exception.TraceHandledException(error, TraceEventType.Information);
this.pendingWritingMessageException = error;
}
finally
{
callback.Invoke(state);
}
});
return AsyncCompletionResult.Queued;
}
protected override void OnSendCore(Message message, TimeSpan timeout)
{
Fx.Assert(message != null, "message should not be null.");
TimeoutHelper helper = new TimeoutHelper(timeout);
WebSocketMessageType outgoingMessageType = GetWebSocketMessageType(message);
if (this.IsStreamedOutput)
{
WebSocketStream webSocketStream = new WebSocketStream(this.WebSocket, outgoingMessageType, helper.RemainingTime());
TimeoutStream timeoutStream = new TimeoutStream(webSocketStream, ref helper);
this.MessageEncoder.WriteMessage(message, timeoutStream);
webSocketStream.WriteEndOfMessage(helper.RemainingTime());
}
else
{
ArraySegment<byte> messageData = this.EncodeMessage(message);
bool success = false;
try
{
if (TD.WebSocketAsyncWriteStartIsEnabled())
{
TD.WebSocketAsyncWriteStart(
this.WebSocket.GetHashCode(),
messageData.Count,
this.RemoteAddress != null ? this.RemoteAddress.ToString() : string.Empty);
}
Task task = this.WebSocket.SendAsync(messageData, outgoingMessageType, true, CancellationToken.None);
task.Wait(helper.RemainingTime(), WebSocketHelper.ThrowCorrectException, WebSocketHelper.SendOperation);
if (TD.WebSocketAsyncWriteStopIsEnabled())
{
TD.WebSocketAsyncWriteStop(this.webSocket.GetHashCode());
}
success = true;
}
finally
{
try
{
this.BufferManager.ReturnBuffer(messageData.Array);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex) || success)
{
throw;
}
FxTrace.Exception.TraceUnhandledException(ex);
}
}
}
}
protected override ArraySegment<byte> EncodeMessage(Message message)
{
return MessageEncoder.WriteMessage(message, int.MaxValue, this.BufferManager, 0);
}
protected void Cleanup()
{
if (Interlocked.CompareExchange(ref this.cleanupStatus, WebSocketHelper.OperationFinished, WebSocketHelper.OperationNotStarted) == WebSocketHelper.OperationNotStarted)
{
this.OnCleanup();
}
}
protected virtual void OnCleanup()
{
Fx.Assert(this.cleanupStatus == WebSocketHelper.OperationFinished,
"This method should only be called by this.Cleanup(). Make sure that you never call overriden OnCleanup()-methods directly in subclasses");
if (this.shouldDisposeWebSocketAfterClosed && this.webSocket != null)
{
this.webSocket.Dispose();
}
if (this.internalBuffer != null)
{
this.bufferPool.Return(this.internalBuffer);
this.internalBuffer = null;
}
}
private static void ThrowOnPendingException(ref Exception pendingException)
{
Exception exceptionToThrow = pendingException;
if (exceptionToThrow != null)
{
pendingException = null;
throw FxTrace.Exception.AsError(exceptionToThrow);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.WrapExceptionsRule, Justification = "The exceptions thrown here are already wrapped.")]
private Task CloseAsync()
{
try
{
return this.WebSocket.CloseAsync(this.webSocketCloseDetails.OutputCloseStatus, this.webSocketCloseDetails.OutputCloseStatusDescription, CancellationToken.None);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw WebSocketHelper.ConvertAndTraceException(e);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, FxCop.Rule.WrapExceptionsRule, Justification = "The exceptions thrown here are already wrapped.")]
private Task CloseOutputAsync(CancellationToken cancellationToken)
{
try
{
return this.WebSocket.CloseOutputAsync(this.webSocketCloseDetails.OutputCloseStatus, this.webSocketCloseDetails.OutputCloseStatusDescription, cancellationToken);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
throw WebSocketHelper.ConvertAndTraceException(e);
}
}
static WebSocketMessageType GetWebSocketMessageType(Message message)
{
WebSocketMessageType outgoingMessageType = WebSocketDefaults.DefaultWebSocketMessageType;
WebSocketMessageProperty webSocketMessageProperty;
if (message.Properties.TryGetValue<WebSocketMessageProperty>(WebSocketMessageProperty.Name, out webSocketMessageProperty))
{
outgoingMessageType = webSocketMessageProperty.MessageType;
}
return outgoingMessageType;
}
static void StreamWriteCallback(IAsyncResult ar)
{
if (ar.CompletedSynchronously)
{
return;
}
WebSocketTransportDuplexSessionChannel thisPtr = (WebSocketTransportDuplexSessionChannel)ar.AsyncState;
try
{
thisPtr.MessageEncoder.EndWriteMessage(ar);
// We are goverend here by the TimeoutStream, no need to pass a CancellationToken here.
thisPtr.webSocketStream.WriteEndOfMessage(TimeSpan.MaxValue);
thisPtr.waitCallback.Invoke(thisPtr.state);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
thisPtr.AddPendingException(ex);
}
}
protected class WebSocketMessageSource : IMessageSource
{
static readonly Action<object> onAsyncReceiveCancelled = Fx.ThunkCallback<object>(OnAsyncReceiveCancelled);
MessageEncoder encoder;
BufferManager bufferManager;
EndpointAddress localAddress;
Message pendingMessage;
Exception pendingException;
WebSocketContext context;
WebSocket webSocket;
bool closureReceived = false;
bool useStreaming;
int receiveBufferSize;
int maxBufferSize;
long maxReceivedMessageSize;
TaskCompletionSource<object> streamWaitTask;
IDefaultCommunicationTimeouts defaultTimeouts;
RemoteEndpointMessageProperty remoteEndpointMessageProperty;
SecurityMessageProperty handshakeSecurityMessageProperty;
WebSocketCloseDetails closeDetails;
ReadOnlyDictionary<string, object> properties;
TimeSpan asyncReceiveTimeout;
TaskCompletionSource<object> receiveTask;
IOThreadTimer receiveTimer;
int asyncReceiveState;
public WebSocketMessageSource(WebSocketTransportDuplexSessionChannel webSocketTransportDuplexSessionChannel, WebSocket webSocket,
bool useStreaming, IDefaultCommunicationTimeouts defaultTimeouts)
{
this.Initialize(webSocketTransportDuplexSessionChannel, webSocket, useStreaming, defaultTimeouts);
this.StartNextReceiveAsync();
}
public WebSocketMessageSource(WebSocketTransportDuplexSessionChannel webSocketTransportDuplexSessionChannel, WebSocketContext context,
bool isStreamed, RemoteEndpointMessageProperty remoteEndpointMessageProperty, IDefaultCommunicationTimeouts defaultTimeouts, HttpRequestMessage requestMessage)
{
this.Initialize(webSocketTransportDuplexSessionChannel, context.WebSocket, isStreamed, defaultTimeouts);
IPrincipal user = requestMessage == null ? null : requestMessage.GetUserPrincipal();
this.context = new ServiceWebSocketContext(context, user);
this.remoteEndpointMessageProperty = remoteEndpointMessageProperty;
this.properties = requestMessage == null? null : new ReadOnlyDictionary<string, object>(requestMessage.Properties);
this.StartNextReceiveAsync();
}
void Initialize(WebSocketTransportDuplexSessionChannel webSocketTransportDuplexSessionChannel, WebSocket webSocket, bool useStreaming, IDefaultCommunicationTimeouts defaultTimeouts)
{
this.webSocket = webSocket;
this.encoder = webSocketTransportDuplexSessionChannel.MessageEncoder;
this.bufferManager = webSocketTransportDuplexSessionChannel.BufferManager;
this.localAddress = webSocketTransportDuplexSessionChannel.LocalAddress;
this.maxBufferSize = webSocketTransportDuplexSessionChannel.MaxBufferSize;
this.handshakeSecurityMessageProperty = webSocketTransportDuplexSessionChannel.RemoteSecurity;
this.maxReceivedMessageSize = webSocketTransportDuplexSessionChannel.TransportFactorySettings.MaxReceivedMessageSize;
this.receiveBufferSize = Math.Min(WebSocketHelper.GetReceiveBufferSize(this.maxReceivedMessageSize), this.maxBufferSize);
this.useStreaming = useStreaming;
this.defaultTimeouts = defaultTimeouts;
this.closeDetails = webSocketTransportDuplexSessionChannel.webSocketCloseDetails;
this.receiveTimer = new IOThreadTimer(onAsyncReceiveCancelled, this, true);
this.asyncReceiveState = AsyncReceiveState.Finished;
}
internal RemoteEndpointMessageProperty RemoteEndpointMessageProperty
{
get { return this.remoteEndpointMessageProperty; }
}
static void OnAsyncReceiveCancelled(object target)
{
WebSocketMessageSource messageSource = (WebSocketMessageSource)target;
messageSource.AsyncReceiveCancelled();
}
void AsyncReceiveCancelled()
{
if (Interlocked.CompareExchange(ref this.asyncReceiveState, AsyncReceiveState.Cancelled, AsyncReceiveState.Started) == AsyncReceiveState.Started)
{
this.receiveTask.SetResult(null);
}
}
public AsyncReceiveResult BeginReceive(TimeSpan timeout, WaitCallback callback, object state)
{
Fx.Assert(callback != null, "callback should not be null.");
if (this.receiveTask.Task.IsCompleted)
{
return AsyncReceiveResult.Completed;
}
else
{
this.asyncReceiveTimeout = timeout;
this.receiveTimer.Set(timeout);
this.receiveTask.Task.ContinueWith(t =>
{
callback.Invoke(state);
});
return AsyncReceiveResult.Pending;
}
}
public Message EndReceive()
{
if (this.asyncReceiveState == AsyncReceiveState.Cancelled)
{
throw FxTrace.Exception.AsError(WebSocketHelper.GetTimeoutException(null, this.asyncReceiveTimeout, WebSocketHelper.ReceiveOperation));
}
else
{
// IOThreadTimer.Cancel() will return false if we called IOThreadTimer.Set(Timespan.MaxValue) here, so we cannot reply on the return value of Cancel()
// call to see if Cancel() is fired or not. CSDMain 262179 filed for this.
this.receiveTimer.Cancel();
Fx.Assert(this.asyncReceiveState == AsyncReceiveState.Finished, "this.asyncReceiveState is not AsyncReceiveState.Finished: " + this.asyncReceiveState);
Message message = this.GetPendingMessage();
if (message != null)
{
// If we get any exception thrown out before that, the channel will be aborted thus no need to maintain the receive loop here.
this.StartNextReceiveAsync();
}
return message;
}
}
public Message Receive(TimeSpan timeout)
{
bool waitingResult = this.receiveTask.Task.Wait(timeout);
ThrowOnPendingException(ref this.pendingException);
if (!waitingResult)
{
throw FxTrace.Exception.AsError(new TimeoutException(
SR.GetString(SR.WaitForMessageTimedOut, timeout),
ThreadNeutralSemaphore.CreateEnterTimedOutException(timeout)));
}
Message message = this.GetPendingMessage();
if (message != null)
{
this.StartNextReceiveAsync();
}
return message;
}
public void UpdateOpenNotificationMessageProperties(MessageProperties messageProperties)
{
this.AddMessageProperties(messageProperties, WebSocketDefaults.DefaultWebSocketMessageType);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability103",
Justification = "The exceptions are wrapped already.")]
async Task ReadBufferedMessageAsync()
{
byte[] internalBuffer = null;
try
{
internalBuffer = this.bufferManager.TakeBuffer(this.receiveBufferSize);
int receivedByteCount = 0;
bool endOfMessage = false;
WebSocketReceiveResult result = null;
do
{
try
{
if (TD.WebSocketAsyncReadStartIsEnabled())
{
TD.WebSocketAsyncReadStart(this.webSocket.GetHashCode());
}
Task<WebSocketReceiveResult> receiveTask = this.webSocket.ReceiveAsync(
new ArraySegment<byte>(internalBuffer, receivedByteCount, internalBuffer.Length - receivedByteCount),
CancellationToken.None);
await receiveTask.ConfigureAwait(false);
result = receiveTask.Result;
this.CheckCloseStatus(result);
endOfMessage = result.EndOfMessage;
receivedByteCount += result.Count;
if (receivedByteCount >= internalBuffer.Length && !result.EndOfMessage)
{
if (internalBuffer.Length >= this.maxBufferSize)
{
this.pendingException = FxTrace.Exception.AsError(new QuotaExceededException(SR.GetString(SR.MaxReceivedMessageSizeExceeded, this.maxBufferSize)));
return;
}
int newSize = (int)Math.Min(((double)internalBuffer.Length) * 2, this.maxBufferSize);
Fx.Assert(newSize > 0, "buffer size should be larger than zero.");
byte[] newBuffer = this.bufferManager.TakeBuffer(newSize);
Buffer.BlockCopy(internalBuffer, 0, newBuffer, 0, receivedByteCount);
this.bufferManager.ReturnBuffer(internalBuffer);
internalBuffer = newBuffer;
}
if (TD.WebSocketAsyncReadStopIsEnabled())
{
TD.WebSocketAsyncReadStop(
this.webSocket.GetHashCode(),
receivedByteCount,
TraceUtility.GetRemoteEndpointAddressPort(this.RemoteEndpointMessageProperty));
}
}
catch (AggregateException ex)
{
WebSocketHelper.ThrowCorrectException(ex, TimeSpan.MaxValue, WebSocketHelper.ReceiveOperation);
}
}
while (!endOfMessage && !this.closureReceived);
byte[] buffer = null;
bool success = false;
try
{
buffer = this.bufferManager.TakeBuffer(receivedByteCount);
Buffer.BlockCopy(internalBuffer, 0, buffer, 0, receivedByteCount);
Fx.Assert(result != null, "Result should not be null");
this.pendingMessage = this.PrepareMessage(result, buffer, receivedByteCount);
success = true;
}
finally
{
if (buffer != null && (!success || this.pendingMessage == null))
{
this.bufferManager.ReturnBuffer(buffer);
}
}
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
this.pendingException = WebSocketHelper.ConvertAndTraceException(ex, TimeSpan.MaxValue, WebSocketHelper.ReceiveOperation);
}
finally
{
if (internalBuffer != null)
{
this.bufferManager.ReturnBuffer(internalBuffer);
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability103",
Justification = "The exceptions are wrapped already.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability104",
Justification = "The exceptions are traced already.")]
public AsyncReceiveResult BeginWaitForMessage(TimeSpan timeout, Threading.WaitCallback callback, object state)
{
try
{
return this.BeginReceive(timeout, callback, state);
}
catch (TimeoutException ex)
{
this.pendingException = FxTrace.Exception.AsError(ex);
return AsyncReceiveResult.Completed;
}
}
public bool EndWaitForMessage()
{
try
{
Message message = this.EndReceive();
this.pendingMessage = message;
return true;
}
catch (TimeoutException ex)
{
if (TD.ReceiveTimeoutIsEnabled())
{
TD.ReceiveTimeout(ex.Message);
}
DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information);
return false;
}
}
public bool WaitForMessage(TimeSpan timeout)
{
try
{
Message message = this.Receive(timeout);
this.pendingMessage = message;
return true;
}
catch (TimeoutException exception)
{
if (TD.ReceiveTimeoutIsEnabled())
{
TD.ReceiveTimeout(exception.Message);
}
DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
return false;
}
}
internal void FinishUsingMessageStream(Exception ex)
{
//// The pattern of the task here is:
//// 1) Only one thread can get the stream and consume the stream. A new task will be created at the moment it takes the stream
//// 2) Only one another thread can enter the lock and wait on the task
//// 3) The cleanup on the stream will return the stream to message source. And the cleanup call is limited to be called only once.
if (ex != null && this.pendingException == null)
{
this.pendingException = ex;
}
this.streamWaitTask.SetResult(null);
}
internal void CheckCloseStatus(WebSocketReceiveResult result)
{
if (result.MessageType == WebSocketMessageType.Close)
{
if (TD.WebSocketCloseStatusReceivedIsEnabled())
{
TD.WebSocketCloseStatusReceived(
this.webSocket.GetHashCode(),
result.CloseStatus.ToString());
}
this.closureReceived = true;
this.closeDetails.InputCloseStatus = result.CloseStatus;
this.closeDetails.InputCloseStatusDescription = result.CloseStatusDescription;
}
}
async void StartNextReceiveAsync()
{
Fx.Assert(this.receiveTask == null || this.receiveTask.Task.IsCompleted, "this.receiveTask is not completed.");
this.receiveTask = new TaskCompletionSource<object>();
int currentState = Interlocked.CompareExchange(ref this.asyncReceiveState, AsyncReceiveState.Started, AsyncReceiveState.Finished);
Fx.Assert(currentState == AsyncReceiveState.Finished, "currentState is not AsyncReceiveState.Finished: " + currentState);
if (currentState != AsyncReceiveState.Finished)
{
throw FxTrace.Exception.AsError(new InvalidOperationException());
}
try
{
if (this.useStreaming)
{
if (this.streamWaitTask != null)
{
//// Wait until the previous stream message finished.
await this.streamWaitTask.Task.ConfigureAwait(false);
}
this.streamWaitTask = new TaskCompletionSource<object>();
}
if (this.pendingException == null)
{
if (!this.useStreaming)
{
await this.ReadBufferedMessageAsync().ConfigureAwait(false);
}
else
{
byte[] buffer = this.bufferManager.TakeBuffer(this.receiveBufferSize);
bool success = false;
try
{
if (TD.WebSocketAsyncReadStartIsEnabled())
{
TD.WebSocketAsyncReadStart(this.webSocket.GetHashCode());
}
try
{
Task<WebSocketReceiveResult> receiveTask = this.webSocket.ReceiveAsync(
new ArraySegment<byte>(buffer, 0, this.receiveBufferSize),
CancellationToken.None);
await receiveTask.ConfigureAwait(false);
WebSocketReceiveResult result = receiveTask.Result;
this.CheckCloseStatus(result);
this.pendingMessage = this.PrepareMessage(result, buffer, result.Count);
if (TD.WebSocketAsyncReadStopIsEnabled())
{
TD.WebSocketAsyncReadStop(
this.webSocket.GetHashCode(),
result.Count,
TraceUtility.GetRemoteEndpointAddressPort(this.remoteEndpointMessageProperty));
}
}
catch (AggregateException ex)
{
WebSocketHelper.ThrowCorrectException(ex, this.asyncReceiveTimeout, WebSocketHelper.ReceiveOperation);
}
success = true;
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
this.pendingException = WebSocketHelper.ConvertAndTraceException(ex, this.asyncReceiveTimeout, WebSocketHelper.ReceiveOperation);
}
finally
{
if (!success)
{
this.bufferManager.ReturnBuffer(buffer);
}
}
}
}
}
finally
{
if (Interlocked.CompareExchange(ref this.asyncReceiveState, AsyncReceiveState.Finished, AsyncReceiveState.Started) == AsyncReceiveState.Started)
{
this.receiveTask.SetResult(null);
}
}
}
void AddMessageProperties(MessageProperties messageProperties, WebSocketMessageType incomingMessageType)
{
Fx.Assert(messageProperties != null, "messageProperties should not be null.");
WebSocketMessageProperty messageProperty = new WebSocketMessageProperty(
this.context,
this.webSocket.SubProtocol,
incomingMessageType,
this.properties);
messageProperties.Add(WebSocketMessageProperty.Name, messageProperty);
if (this.remoteEndpointMessageProperty != null)
{
messageProperties.Add(RemoteEndpointMessageProperty.Name, this.remoteEndpointMessageProperty);
}
if (this.handshakeSecurityMessageProperty != null)
{
messageProperties.Security = (SecurityMessageProperty)this.handshakeSecurityMessageProperty.CreateCopy();
}
}
Message GetPendingMessage()
{
ThrowOnPendingException(ref this.pendingException);
if (this.pendingMessage != null)
{
Message pendingMessage = this.pendingMessage;
this.pendingMessage = null;
return pendingMessage;
}
return null;
}
Message PrepareMessage(WebSocketReceiveResult result, byte[] buffer, int count)
{
if (result.MessageType != WebSocketMessageType.Close)
{
Message message;
if (this.useStreaming)
{
TimeoutHelper readTimeoutHelper = new TimeoutHelper(this.defaultTimeouts.ReceiveTimeout);
message = this.encoder.ReadMessage(
new MaxMessageSizeStream(
new TimeoutStream(
new WebSocketStream(
this,
new ArraySegment<byte>(buffer, 0, count),
this.webSocket,
result.EndOfMessage,
this.bufferManager,
this.defaultTimeouts.CloseTimeout),
ref readTimeoutHelper),
this.maxReceivedMessageSize),
this.maxBufferSize);
}
else
{
ArraySegment<byte> bytes = new ArraySegment<byte>(buffer, 0, count);
message = this.encoder.ReadMessage(bytes, this.bufferManager);
}
if (message.Version.Addressing != AddressingVersion.None || !this.localAddress.IsAnonymous)
{
this.localAddress.ApplyTo(message);
}
if (message.Version.Addressing == AddressingVersion.None && message.Headers.Action == null)
{
if (result.MessageType == WebSocketMessageType.Binary)
{
message.Headers.Action = WebSocketTransportSettings.BinaryMessageReceivedAction;
}
else
{
// WebSocketMesssageType should always be binary or text at this moment. The layer below us will help protect this.
Fx.Assert(result.MessageType == WebSocketMessageType.Text, "result.MessageType must be WebSocketMessageType.Text.");
message.Headers.Action = WebSocketTransportSettings.TextMessageReceivedAction;
}
}
if (message != null)
{
this.AddMessageProperties(message.Properties, result.MessageType);
}
return message;
}
return null;
}
static class AsyncReceiveState
{
internal const int Started = 0;
internal const int Finished = 1;
internal const int Cancelled = 2;
}
}
class WebSocketStream : Stream
{
WebSocket webSocket;
WebSocketMessageSource messageSource;
TimeSpan closeTimeout;
ArraySegment<byte> initialReadBuffer;
bool endOfMessageReached = false;
bool isForRead;
bool endofMessageReceived;
WebSocketMessageType outgoingMessageType;
BufferManager bufferManager;
int messageSourceCleanState;
int endOfMessageWritten;
int readTimeout;
int writeTimeout;
public WebSocketStream(
WebSocketMessageSource messageSource,
ArraySegment<byte> initialBuffer,
WebSocket webSocket,
bool endofMessageReceived,
BufferManager bufferManager,
TimeSpan closeTimeout)
: this(webSocket, WebSocketDefaults.DefaultWebSocketMessageType, closeTimeout)
{
Fx.Assert(messageSource != null, "messageSource should not be null.");
this.messageSource = messageSource;
this.initialReadBuffer = initialBuffer;
this.isForRead = true;
this.endofMessageReceived = endofMessageReceived;
this.bufferManager = bufferManager;
this.messageSourceCleanState = WebSocketHelper.OperationNotStarted;
this.endOfMessageWritten = WebSocketHelper.OperationNotStarted;
}
public WebSocketStream(
WebSocket webSocket,
WebSocketMessageType outgoingMessageType,
TimeSpan closeTimeout)
{
Fx.Assert(webSocket != null, "webSocket should not be null.");
this.webSocket = webSocket;
this.isForRead = false;
this.outgoingMessageType = outgoingMessageType;
this.messageSourceCleanState = WebSocketHelper.OperationFinished;
this.closeTimeout = closeTimeout;
}
public override bool CanRead
{
get { return this.isForRead; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanTimeout
{
get
{
return true;
}
}
public override bool CanWrite
{
get { return !this.isForRead; }
}
public override long Length
{
get { throw FxTrace.Exception.AsError(new NotSupportedException(SR.GetString(SR.SeekNotSupported))); }
}
public override long Position
{
get
{
throw FxTrace.Exception.AsError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
}
set
{
throw FxTrace.Exception.AsError(new NotSupportedException(SR.GetString(SR.SeekNotSupported)));
}
}
public override int ReadTimeout
{
get
{
return this.readTimeout;
}
set
{
Fx.Assert(value >= 0, "ReadTimeout should not be negative.");
this.readTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return this.writeTimeout;
}
set
{
Fx.Assert(value >= 0, "WriteTimeout should not be negative.");
this.writeTimeout = value;
}
}
public override void Close()
{
TimeoutHelper helper = new TimeoutHelper(this.closeTimeout);
base.Close();
this.Cleanup(helper.RemainingTime());
}
public override void Flush()
{
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
Fx.Assert(this.messageSource != null, "messageSource should not be null in read case.");
if (this.ReadTimeout <= 0)
{
throw FxTrace.Exception.AsError(WebSocketHelper.GetTimeoutException(null, TimeoutHelper.FromMilliseconds(this.ReadTimeout), WebSocketHelper.ReceiveOperation));
}
TimeoutHelper helper = new TimeoutHelper(TimeoutHelper.FromMilliseconds(this.ReadTimeout));
if (this.endOfMessageReached)
{
return new CompletedAsyncResult<int>(0, callback, state);
}
if (this.initialReadBuffer.Count != 0)
{
int bytesRead = this.GetBytesFromInitialReadBuffer(buffer, offset, count);
return new CompletedAsyncResult<int>(bytesRead, callback, state);
}
if (this.endofMessageReceived)
{
this.endOfMessageReached = true;
return new CompletedAsyncResult<int>(0, callback, state);
}
if (TD.WebSocketAsyncReadStartIsEnabled())
{
TD.WebSocketAsyncReadStart(this.webSocket.GetHashCode());
}
IOThreadCancellationTokenSource cancellationTokenSource = new IOThreadCancellationTokenSource(helper.RemainingTime());
Task<int> task = this.webSocket.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count), cancellationTokenSource.Token).ContinueWith(t =>
{
cancellationTokenSource.Dispose();
WebSocketHelper.ThrowExceptionOnTaskFailure(t, TimeoutHelper.FromMilliseconds(this.ReadTimeout), WebSocketHelper.ReceiveOperation);
this.endOfMessageReached = t.Result.EndOfMessage;
int receivedBytes = t.Result.Count;
CheckResultAndEnsureNotCloseMessage(this.messageSource, t.Result);
if (this.endOfMessageReached)
{
this.Cleanup(helper.RemainingTime());
}
if (TD.WebSocketAsyncReadStopIsEnabled())
{
TD.WebSocketAsyncReadStop(
this.webSocket.GetHashCode(),
receivedBytes,
this.messageSource != null ? TraceUtility.GetRemoteEndpointAddressPort(this.messageSource.RemoteEndpointMessageProperty) : string.Empty);
}
return receivedBytes;
}, TaskContinuationOptions.None);
return task.AsAsyncResult<int>(callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
Task<int> task = (Task<int>)asyncResult;
WebSocketHelper.ThrowExceptionOnTaskFailure((Task)task, TimeoutHelper.FromMilliseconds(this.ReadTimeout), WebSocketHelper.ReceiveOperation);
return task.Result;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(FxCop.Category.ReliabilityBasic, "Reliability104",
Justification = "The exceptions will be traced and thrown by the handling method.")]
public override int Read(byte[] buffer, int offset, int count)
{
Fx.Assert(this.messageSource != null, "messageSource should not be null in read case.");
if (this.ReadTimeout <= 0)
{
throw FxTrace.Exception.AsError(WebSocketHelper.GetTimeoutException(null, TimeoutHelper.FromMilliseconds(this.ReadTimeout), WebSocketHelper.ReceiveOperation));
}
TimeoutHelper helper = new TimeoutHelper(TimeoutHelper.FromMilliseconds(this.ReadTimeout));
if (this.endOfMessageReached)
{
return 0;
}
if (this.initialReadBuffer.Count != 0)
{
return this.GetBytesFromInitialReadBuffer(buffer, offset, count);
}
int receivedBytes = 0;
if (this.endofMessageReceived)
{
this.endOfMessageReached = true;
}
else
{
if (TD.WebSocketAsyncReadStartIsEnabled())
{
TD.WebSocketAsyncReadStart(this.webSocket.GetHashCode());
}
Task<WebSocketReceiveResult> task = this.webSocket.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count), CancellationToken.None);
task.Wait(helper.RemainingTime(), WebSocketHelper.ThrowCorrectException, WebSocketHelper.ReceiveOperation);
if (task.Result.EndOfMessage)
{
this.endofMessageReceived = true;
this.endOfMessageReached = true;
}
receivedBytes = task.Result.Count;
CheckResultAndEnsureNotCloseMessage(this.messageSource, task.Result);
if (TD.WebSocketAsyncReadStopIsEnabled())
{
TD.WebSocketAsyncReadStop(
this.webSocket.GetHashCode(),
receivedBytes,
this.messageSource != null ? TraceUtility.GetRemoteEndpointAddressPort(this.messageSource.RemoteEndpointMessageProperty) : string.Empty);
}
}
if (this.endOfMessageReached)
{
this.Cleanup(helper.RemainingTime());
}
return receivedBytes;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void SetLength(long value)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void Write(byte[] buffer, int offset, int count)
{
if (this.endOfMessageWritten == WebSocketHelper.OperationFinished)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.WebSocketStreamWriteCalledAfterEOMSent)));
}
if (this.WriteTimeout <= 0)
{
throw FxTrace.Exception.AsError(WebSocketHelper.GetTimeoutException(null, TimeoutHelper.FromMilliseconds(this.WriteTimeout), WebSocketHelper.SendOperation));
}
if (TD.WebSocketAsyncWriteStartIsEnabled())
{
TD.WebSocketAsyncWriteStart(
this.webSocket.GetHashCode(),
count,
this.messageSource != null ? TraceUtility.GetRemoteEndpointAddressPort(this.messageSource.RemoteEndpointMessageProperty) : string.Empty);
}
Task task = this.webSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), this.outgoingMessageType, false, CancellationToken.None);
task.Wait(TimeoutHelper.FromMilliseconds(this.WriteTimeout), WebSocketHelper.ThrowCorrectException, WebSocketHelper.SendOperation);
if (TD.WebSocketAsyncWriteStopIsEnabled())
{
TD.WebSocketAsyncWriteStop(this.webSocket.GetHashCode());
}
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (this.endOfMessageWritten == WebSocketHelper.OperationFinished)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.GetString(SR.WebSocketStreamWriteCalledAfterEOMSent)));
}
if (this.WriteTimeout <= 0)
{
throw FxTrace.Exception.AsError(WebSocketHelper.GetTimeoutException(null, TimeoutHelper.FromMilliseconds(this.WriteTimeout), WebSocketHelper.SendOperation));
}
if (TD.WebSocketAsyncWriteStartIsEnabled())
{
TD.WebSocketAsyncWriteStart(
this.webSocket.GetHashCode(),
count,
this.messageSource != null ? TraceUtility.GetRemoteEndpointAddressPort(this.messageSource.RemoteEndpointMessageProperty) : string.Empty);
}
IOThreadCancellationTokenSource cancellationTokenSource = new IOThreadCancellationTokenSource(this.WriteTimeout);
Task task = this.webSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), this.outgoingMessageType, false, cancellationTokenSource.Token).ContinueWith(t =>
{
if (TD.WebSocketAsyncWriteStopIsEnabled())
{
TD.WebSocketAsyncWriteStop(this.webSocket.GetHashCode());
}
cancellationTokenSource.Dispose();
WebSocketHelper.ThrowExceptionOnTaskFailure(t, TimeoutHelper.FromMilliseconds(this.WriteTimeout), WebSocketHelper.SendOperation);
});
return task.AsAsyncResult(callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
Task task = (Task)asyncResult;
WebSocketHelper.ThrowExceptionOnTaskFailure(task, TimeoutHelper.FromMilliseconds(this.WriteTimeout), WebSocketHelper.SendOperation);
}
public void WriteEndOfMessage(TimeSpan timeout)
{
if (TD.WebSocketAsyncWriteStartIsEnabled())
{
TD.WebSocketAsyncWriteStart(
this.webSocket.GetHashCode(),
0,
this.messageSource != null ? TraceUtility.GetRemoteEndpointAddressPort(this.messageSource.RemoteEndpointMessageProperty) : string.Empty);
}
if (Interlocked.CompareExchange(ref this.endOfMessageWritten, WebSocketHelper.OperationFinished, WebSocketHelper.OperationNotStarted) == WebSocketHelper.OperationNotStarted)
{
Task task = this.webSocket.SendAsync(new ArraySegment<byte>(EmptyArray<byte>.Instance, 0, 0), this.outgoingMessageType, true, CancellationToken.None);
task.Wait(timeout, WebSocketHelper.ThrowCorrectException, WebSocketHelper.SendOperation);
}
if (TD.WebSocketAsyncWriteStopIsEnabled())
{
TD.WebSocketAsyncWriteStop(this.webSocket.GetHashCode());
}
}
public async void WriteEndOfMessageAsync(TimeSpan timeout, WaitCallback callback, object state)
{
if (TD.WebSocketAsyncWriteStartIsEnabled())
{
TD.WebSocketAsyncWriteStart(
this.webSocket.GetHashCode(),
0,
this.messageSource != null ? TraceUtility.GetRemoteEndpointAddressPort(this.messageSource.RemoteEndpointMessageProperty) : string.Empty);
}
using (IOThreadCancellationTokenSource cancellationTokenSource = new IOThreadCancellationTokenSource(timeout))
{
try
{
Task task = this.webSocket.SendAsync(new ArraySegment<byte>(EmptyArray<byte>.Instance, 0, 0), this.outgoingMessageType, true, cancellationTokenSource.Token);
// The callback here will only be TransportDuplexSessionChannel.OnWriteComplete. It's safe to call this callback without flowing
// security context here since there's no user code involved.
await task.SuppressContextFlow();
if (TD.WebSocketAsyncWriteStopIsEnabled())
{
TD.WebSocketAsyncWriteStop(this.webSocket.GetHashCode());
}
}
catch(AggregateException ex)
{
WebSocketHelper.ThrowCorrectException(ex, TimeoutHelper.FromMilliseconds(this.WriteTimeout), WebSocketHelper.SendOperation);
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
WebSocketHelper.ThrowCorrectException(ex);
}
finally
{
callback.Invoke(state);
}
}
}
static void CheckResultAndEnsureNotCloseMessage(WebSocketMessageSource messageSource, WebSocketReceiveResult result)
{
messageSource.CheckCloseStatus(result);
if (result.MessageType == WebSocketMessageType.Close)
{
throw FxTrace.Exception.AsError(new ProtocolException(SR.GetString(SR.WebSocketUnexpectedCloseMessageError)));
}
}
int GetBytesFromInitialReadBuffer(byte[] buffer, int offset, int count)
{
int bytesToCopy = this.initialReadBuffer.Count > count ? count : this.initialReadBuffer.Count;
Buffer.BlockCopy(this.initialReadBuffer.Array, this.initialReadBuffer.Offset, buffer, offset, bytesToCopy);
this.initialReadBuffer = new ArraySegment<byte>(this.initialReadBuffer.Array, this.initialReadBuffer.Offset + bytesToCopy, this.initialReadBuffer.Count - bytesToCopy);
return bytesToCopy;
}
void Cleanup(TimeSpan timeout)
{
if (this.isForRead)
{
if (Interlocked.CompareExchange(ref this.messageSourceCleanState, WebSocketHelper.OperationFinished, WebSocketHelper.OperationNotStarted) == WebSocketHelper.OperationNotStarted)
{
Exception pendingException = null;
try
{
if (!this.endofMessageReceived && (this.webSocket.State == WebSocketState.Open || this.webSocket.State == WebSocketState.CloseSent))
{
// Drain the reading stream
TimeoutHelper helper = new TimeoutHelper(timeout);
do
{
Task<WebSocketReceiveResult> receiveTask = this.webSocket.ReceiveAsync(new ArraySegment<byte>(this.initialReadBuffer.Array), CancellationToken.None);
receiveTask.Wait(helper.RemainingTime(), WebSocketHelper.ThrowCorrectException, WebSocketHelper.ReceiveOperation);
this.endofMessageReceived = receiveTask.Result.EndOfMessage;
}
while (!this.endofMessageReceived && (this.webSocket.State == WebSocketState.Open || this.webSocket.State == WebSocketState.CloseSent));
}
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
// Not throwing out this exception during stream cleanup. The exception
// will be thrown out when we are trying to receive the next message using the same
// WebSocket object.
pendingException = WebSocketHelper.ConvertAndTraceException(ex, timeout, WebSocketHelper.CloseOperation);
}
this.bufferManager.ReturnBuffer(this.initialReadBuffer.Array);
Fx.Assert(this.messageSource != null, "messageSource should not be null.");
this.messageSource.FinishUsingMessageStream(pendingException);
}
}
else
{
if (Interlocked.CompareExchange(ref this.endOfMessageWritten, WebSocketHelper.OperationFinished, WebSocketHelper.OperationNotStarted) == WebSocketHelper.OperationNotStarted)
{
this.WriteEndOfMessage(timeout);
}
}
}
}
class WebSocketCloseDetails : IWebSocketCloseDetails
{
WebSocketCloseStatus outputCloseStatus = WebSocketCloseStatus.NormalClosure;
string outputCloseStatusDescription;
WebSocketCloseStatus? inputCloseStatus;
string inputCloseStatusDescription;
public WebSocketCloseStatus? InputCloseStatus
{
get
{
return this.inputCloseStatus;
}
internal set
{
this.inputCloseStatus = value;
}
}
public string InputCloseStatusDescription
{
get
{
return this.inputCloseStatusDescription;
}
internal set
{
this.inputCloseStatusDescription = value;
}
}
internal WebSocketCloseStatus OutputCloseStatus
{
get
{
return this.outputCloseStatus;
}
}
internal string OutputCloseStatusDescription
{
get
{
return this.outputCloseStatusDescription;
}
}
public void SetOutputCloseStatus(WebSocketCloseStatus closeStatus, string closeStatusDescription)
{
this.outputCloseStatus = closeStatus;
this.outputCloseStatusDescription = closeStatusDescription;
}
}
}
}
| |
// 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.Collections.Generic;
using System.Text;
using WebsitePanel.Providers.Mail.SM3;
using Microsoft.Win32;
using SM3 = WebsitePanel.Providers.Mail.SM3;
namespace WebsitePanel.Providers.Mail
{
public class SmarterMail3 : SmarterMail2
{
static string[] sm3Settings = new string[] {
"description",
"disabled",
"moderator",
"password",
"requirepassword",
"whocanpost",
"prependsubject",
"maxmessagesize",
"maxrecipients",
"replytolist"
};
public SmarterMail3()
{
}
public override void CreateAccount(MailAccount mailbox)
{
try
{
svcUserAdmin users = new svcUserAdmin();
PrepareProxy(users);
GenericResult1 result = users.AddUser(AdminUsername, AdminPassword,
mailbox.Name,
mailbox.Password,
GetDomainName(mailbox.Name),
mailbox.FirstName,
mailbox.LastName,
false //domain admin is false
);
if (!result.Result)
throw new Exception(result.Message);
// set forwarding settings
result = users.UpdateUserForwardingInfo(AdminUsername, AdminPassword,
mailbox.Name, mailbox.DeleteOnForward,
(mailbox.ForwardingAddresses != null ? String.Join(", ", mailbox.ForwardingAddresses) : ""));
if (!result.Result)
throw new Exception(result.Message);
// set additional settings
result = users.SetRequestedUserSettings(AdminUsername, AdminPassword,
mailbox.Name,
new string[]
{
"isenabled=" + mailbox.Enabled.ToString(),
"maxsize=" + mailbox.MaxMailboxSize.ToString(),
"passwordlocked=" + mailbox.PasswordLocked.ToString(),
"replytoaddress=" + (mailbox.ReplyTo != null ? mailbox.ReplyTo : ""),
"signature=" + (mailbox.Signature != null ? mailbox.Signature : ""),
"spamforwardoption=none"
});
if (!result.Result)
throw new Exception(result.Message);
// set autoresponder settings
result = users.UpdateUserAutoResponseInfo(AdminUsername, AdminPassword,
mailbox.Name,
mailbox.ResponderEnabled,
(mailbox.ResponderSubject != null ? mailbox.ResponderSubject : ""),
(mailbox.ResponderMessage != null ? mailbox.ResponderMessage : ""));
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not create mailbox", ex);
}
}
public override void UpdateAccount(MailAccount mailbox)
{
try
{
//get original account
MailAccount account = GetAccount(mailbox.Name);
svcUserAdmin users = new svcUserAdmin();
PrepareProxy(users);
string strPassword = mailbox.Password;
//Don't change password. Get it from mail server.
if (!mailbox.ChangePassword)
{
strPassword = account.Password;
}
GenericResult1 result = users.UpdateUser(AdminUsername, AdminPassword,
mailbox.Name,
strPassword,
mailbox.FirstName,
mailbox.LastName,
account.IsDomainAdmin
);
if (!result.Result)
throw new Exception(result.Message);
// set forwarding settings
result = users.UpdateUserForwardingInfo(AdminUsername, AdminPassword,
mailbox.Name, mailbox.DeleteOnForward,
(mailbox.ForwardingAddresses != null ? String.Join(", ", mailbox.ForwardingAddresses) : ""));
if (!result.Result)
throw new Exception(result.Message);
// set additional settings
result = users.SetRequestedUserSettings(AdminUsername, AdminPassword,
mailbox.Name,
new string[]
{
"isenabled=" + mailbox.Enabled.ToString(),
"maxsize=" + mailbox.MaxMailboxSize.ToString(),
"passwordlocked=" + mailbox.PasswordLocked.ToString(),
"replytoaddress=" + (mailbox.ReplyTo != null ? mailbox.ReplyTo : ""),
"signature=" + (mailbox.Signature != null ? mailbox.Signature : ""),
"spamforwardoption=none"
});
if (!result.Result)
throw new Exception(result.Message);
// set autoresponder settings
result = users.UpdateUserAutoResponseInfo(AdminUsername, AdminPassword,
mailbox.Name,
mailbox.ResponderEnabled,
(mailbox.ResponderSubject != null ? mailbox.ResponderSubject : ""),
(mailbox.ResponderMessage != null ? mailbox.ResponderMessage : ""));
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Could not update mailbox", ex);
}
}
public override void AddDomainAlias(string domainName, string aliasName)
{
try
{
SM3.svcDomainAliasAdmin service = new SM3.svcDomainAliasAdmin();
PrepareProxy(service);
SM3.GenericResult result = service.AddDomainAliasWithoutMxCheck(
AdminUsername,
AdminPassword,
domainName,
aliasName
);
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Couldn't create domain alias.", ex);
}
}
public override void DeleteDomainAlias(string domainName, string aliasName)
{
try
{
SM3.svcDomainAliasAdmin service = new SM3.svcDomainAliasAdmin();
PrepareProxy(service);
SM3.GenericResult result = service.DeleteDomainAlias(
AdminUsername,
AdminPassword,
domainName,
aliasName
);
if (!result.Result)
throw new Exception(result.Message);
}
catch (Exception ex)
{
throw new Exception("Couldn't delete domain alias.", ex);
}
}
public override bool ListExists(string listName)
{
bool exists = false;
try
{
string domain = GetDomainName(listName);
string account = GetAccountName(listName);
SM3.svcMailListAdmin lists = new SM3.svcMailListAdmin();
PrepareProxy(lists);
SM3.MailingListResult result = lists.GetMailingListsByDomain(AdminUsername, AdminPassword, domain);
if (result.Result)
{
foreach (string member in result.listNames)
{
if (string.Compare(member, listName, true) == 0)
{
exists = true;
break;
}
}
}
}
catch (Exception ex)
{
throw new Exception("Couldn't obtain mail list.", ex);
}
return exists;
}
public override void CreateList(MailList list)
{
try
{
string domain = GetDomainName(list.Name);
string account = GetAccountName(list.Name);
SM3.svcMailListAdmin lists = new SM3.svcMailListAdmin();
PrepareProxy(lists);
SM3.GenericResult result = lists.AddList(AdminUsername, AdminPassword,
domain,
account,
list.ModeratorAddress,
list.Description
);
if (!result.Result)
throw new Exception(result.Message);
List<string> settings = new List<string>();
settings.Add(string.Concat("description=", list.Description));
settings.Add(string.Concat("disabled=", !list.Enabled));
settings.Add(string.Concat("moderator=", list.ModeratorAddress));
settings.Add(string.Concat("password=", list.Password));
settings.Add(string.Concat("requirepassword=", list.RequirePassword));
switch (list.PostingMode)
{
case PostingMode.AnyoneCanPost:
settings.Add("whocanpost=anyone");
break;
case PostingMode.MembersCanPost:
settings.Add("whocanpost=subscribersonly");
break;
case PostingMode.ModeratorCanPost:
settings.Add("whocanpost=moderator");
break;
}
settings.Add(string.Concat("prependsubject=", list.EnableSubjectPrefix));
settings.Add(string.Concat("maxmessagesize=", list.MaxMessageSize));
settings.Add(string.Concat("maxrecipients=", list.MaxRecipientsPerMessage));
switch (list.ReplyToMode)
{
case ReplyTo.RepliesToList:
settings.Add("replytolist=true");
break;
}
result = lists.SetRequestedListSettings(AdminUsername, AdminPassword,
domain,
account,
settings.ToArray()
);
if (!result.Result)
throw new Exception(result.Message);
if (list.Members.Length > 0)
{
result = lists.SetSubscriberList(AdminUsername, AdminPassword,
domain,
account,
list.Members
);
if (!result.Result)
throw new Exception(result.Message);
}
}
catch (Exception ex)
{
throw new Exception("Couldn't create mail list.", ex);
}
}
public override MailList GetList(string listName)
{
try
{
string domain = GetDomainName(listName);
string account = GetAccountName(listName);
SM3.svcMailListAdmin svcLists = new SM3.svcMailListAdmin();
PrepareProxy(svcLists);
SM3.SettingsRequestResult sResult = svcLists.GetRequestedListSettings(
AdminUsername,
AdminPassword,
domain,
account,
sm3Settings
);
if (!sResult.Result)
throw new Exception(sResult.Message);
SM3.SubscriberListResult mResult = svcLists.GetSubscriberList(
AdminUsername,
AdminPassword,
domain,
account
);
if (!mResult.Result)
throw new Exception(mResult.Message);
MailList list = new MailList();
list.Name = listName;
SetMailListSettings(list, sResult.settingValues);
SetMailListMembers(list, mResult.Subscribers);
return list;
}
catch (Exception ex)
{
throw new Exception("Couldn't obtain mail list.", ex);
}
}
public override MailList[] GetLists(string domainName)
{
try
{
SM3.svcMailListAdmin svcLists = new SM3.svcMailListAdmin();
PrepareProxy(svcLists);
SM3.MailingListResult mResult = svcLists.GetMailingListsByDomain(
AdminUsername,
AdminPassword,
domainName
);
if (!mResult.Result)
throw new Exception(mResult.Message);
List<MailList> mailLists = new List<MailList>();
foreach (string listName in mResult.listNames)
{
SM3.SettingsRequestResult sResult = svcLists.GetRequestedListSettings(
AdminUsername,
AdminPassword,
domainName,
listName,
sm3Settings
);
if (!sResult.Result)
throw new Exception(sResult.Message);
SM3.SubscriberListResult rResult = svcLists.GetSubscriberList(
AdminUsername,
AdminPassword,
domainName,
listName
);
if (!rResult.Result)
throw new Exception(rResult.Message);
MailList list = new MailList();
list.Name = string.Concat(listName, "@", domainName);
SetMailListSettings(list, sResult.settingValues);
SetMailListMembers(list, rResult.Subscribers);
mailLists.Add(list);
}
return mailLists.ToArray();
}
catch(Exception ex)
{
throw new Exception("Couldn't obtain domain mail lists.", ex);
}
}
public override void DeleteList(string listName)
{
try
{
SM3.svcMailListAdmin svcLists = new SM3.svcMailListAdmin();
PrepareProxy(svcLists);
string account = GetAccountName(listName);
string domain = GetDomainName(listName);
SM3.GenericResult gResult = svcLists.DeleteList(
AdminUsername,
AdminPassword,
domain,
listName
);
if (!gResult.Result)
throw new Exception(gResult.Message);
}
catch (Exception ex)
{
throw new Exception("Couldn't delete a mail list.", ex);
}
}
public override void UpdateList(MailList list)
{
try
{
string domain = GetDomainName(list.Name);
string account = GetAccountName(list.Name);
SM3.svcMailListAdmin lists = new SM3.svcMailListAdmin();
PrepareProxy(lists);
List<string> settings = new List<string>();
settings.Add(string.Concat("description=", list.Description));
settings.Add(string.Concat("disabled=", !list.Enabled));
settings.Add(string.Concat("moderator=", list.ModeratorAddress));
settings.Add(string.Concat("password=", list.Password));
settings.Add(string.Concat("requirepassword=", list.RequirePassword));
switch (list.PostingMode)
{
case PostingMode.AnyoneCanPost:
settings.Add("whocanpost=anyone");
break;
case PostingMode.MembersCanPost:
settings.Add("whocanpost=subscribersonly");
break;
case PostingMode.ModeratorCanPost:
settings.Add("whocanpost=moderator");
break;
}
settings.Add(string.Concat("prependsubject=", list.EnableSubjectPrefix));
settings.Add(string.Concat("maxmessagesize=", list.MaxMessageSize));
settings.Add(string.Concat("maxrecipients=", list.MaxRecipientsPerMessage));
switch (list.ReplyToMode)
{
case ReplyTo.RepliesToList:
settings.Add("replytolist=true");
break;
case ReplyTo.RepliesToSender:
settings.Add("replytolist=false");
break;
}
SM3.GenericResult result = lists.SetRequestedListSettings(AdminUsername, AdminPassword,
domain,
account,
settings.ToArray()
);
if (!result.Result)
throw new Exception(result.Message);
if (list.Members.Length > 0)
{
result = lists.SetSubscriberList(AdminUsername, AdminPassword,
domain,
account,
list.Members
);
if (!result.Result)
throw new Exception(result.Message);
}
}
catch (Exception ex)
{
throw new Exception("Couldn't update mail list.", ex);
}
}
protected void SetMailListSettings(MailList list, string[] smSettings)
{
foreach (string setting in smSettings)
{
string[] bunch = setting.Split(new char[] { '=' });
switch (bunch[0])
{
case "description":
list.Description = bunch[1];
break;
case "disabled":
list.Enabled = !Convert.ToBoolean(bunch[1]);
break;
case "moderator":
list.ModeratorAddress = bunch[1];
list.Moderated = !string.IsNullOrEmpty(bunch[1]);
break;
case "password":
list.Password = bunch[1];
break;
case "requirepassword":
list.RequirePassword = Convert.ToBoolean(bunch[1]);
break;
case "whocanpost":
if (string.Compare(bunch[1], "anyone", true) == 0)
list.PostingMode = PostingMode.AnyoneCanPost;
else if (string.Compare(bunch[1], "moderatoronly", true) == 0)
list.PostingMode = PostingMode.ModeratorCanPost;
else
list.PostingMode = PostingMode.MembersCanPost;
break;
case "prependsubject":
list.EnableSubjectPrefix = Convert.ToBoolean(bunch[1]);
break;
case "maxmessagesize":
list.MaxMessageSize = Convert.ToInt32(bunch[1]);
break;
case "maxrecipients":
list.MaxRecipientsPerMessage = Convert.ToInt32(bunch[1]);
break;
case "replytolist":
if (string.Compare(bunch[1], "true", true) == 0)
list.ReplyToMode = string.Compare(bunch[1], "true", true) == 0 ? ReplyTo.RepliesToList : ReplyTo.RepliesToSender;
break;
}
}
}
protected void SetMailListMembers(MailList list, string[] subscribers)
{
List<string> members = new List<string>();
foreach (string subscriber in subscribers)
members.Add(subscriber);
list.Members = members.ToArray();
}
public override bool IsInstalled()
{
string productName = null;
string productVersion = null;
RegistryKey HKLM = Registry.LocalMachine;
RegistryKey key = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
String[] names = null;
if (key != null)
{
names = key.GetSubKeyNames();
foreach (string s in names)
{
RegistryKey subkey = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + s);
if (subkey != null)
if (!String.IsNullOrEmpty((string)subkey.GetValue("DisplayName")))
{
productName = (string)subkey.GetValue("DisplayName");
}
if (productName != null)
if (productName.Equals("SmarterMail"))
{
if (subkey != null) productVersion = (string)subkey.GetValue("DisplayVersion");
break;
}
}
if (!String.IsNullOrEmpty(productVersion))
{
string[] split = productVersion.Split(new char[] { '.' });
return split[0].Equals("3") | split[0].Equals("4");
}
}
else
{
key = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
if (key == null)
{
return false;
}
names = key.GetSubKeyNames();
foreach (string s in names)
{
RegistryKey subkey = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" + s);
if (subkey != null)
if (!String.IsNullOrEmpty((string)subkey.GetValue("DisplayName")))
{
productName = (string)subkey.GetValue("DisplayName");
}
if (productName != null)
if (productName.Equals("SmarterMail"))
{
if (subkey != null) productVersion = (string)subkey.GetValue("DisplayVersion");
break;
}
}
if (!String.IsNullOrEmpty(productVersion))
{
string[] split = productVersion.Split(new[] { '.' });
return split[0].Equals("3") | split[0].Equals("4");
}
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
/// <summary>Provides support for implementing asynchronous operations on Streams.</summary>
internal sealed class StreamAsyncHelper
{
private SemaphoreSlim _asyncActiveSemaphore;
private Task _activeReadWriteTask;
private readonly Stream _stream;
internal StreamAsyncHelper(Stream stream)
{
Debug.Assert(stream != null);
_stream = stream;
}
private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
// Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
internal IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (!_stream.CanRead)
{
throw __Error.GetReadNotSupported();
}
return BeginReadWrite(true, buffer, offset, count, callback, state);
}
internal IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
if (!_stream.CanWrite)
{
throw __Error.GetWriteNotSupported();
}
return BeginReadWrite(false, buffer, offset, count, callback, state);
}
private IAsyncResult BeginReadWrite(bool isRead, byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
// To avoid a race with a stream's position pointer & generating race
// conditions with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we block the calling thread until
// the active one completes.
SemaphoreSlim sem = EnsureAsyncActiveSemaphoreInitialized();
sem.Wait();
Debug.Assert(_activeReadWriteTask == null);
// Create the task to asynchronously run the read or write. Even though Task implements IAsyncResult,
// we wrap it in a special IAsyncResult object that stores all of the state for the operation
// and that we can pass around as a state parameter to all of our delegates. Even though this
// is an allocation, this allows us to avoid any closures or non-statically cached delegates
// for both the Task and its continuation, saving more allocations.
var asyncResult = new StreamReadWriteAsyncResult(_stream, buffer, offset, count, callback, state);
Task t;
if (isRead)
{
t = new Task<int>(obj =>
{
var ar = (StreamReadWriteAsyncResult)obj;
return ar._stream.Read(ar._buffer, ar._offset, ar._count);
}, asyncResult, CancellationToken.None, TaskCreationOptions.DenyChildAttach);
}
else
{
t = new Task(obj =>
{
var ar = (StreamReadWriteAsyncResult)obj;
ar._stream.Write(ar._buffer, ar._offset, ar._count);
}, asyncResult, CancellationToken.None, TaskCreationOptions.DenyChildAttach);
}
asyncResult._task = t; // this doesn't happen in the async result's ctor because the Task needs to reference the AR, and vice versa
if (callback != null)
{
t.ContinueWith((_, obj) =>
{
var ar = (StreamReadWriteAsyncResult)obj;
ar._callback(ar);
}, asyncResult, CancellationToken.None, TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
_activeReadWriteTask = t;
t.Start(TaskScheduler.Default);
return asyncResult;
}
internal int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
var ar = asyncResult as StreamReadWriteAsyncResult;
var task = _activeReadWriteTask;
if (task == null || ar == null)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (task != ar._task)
{
throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
Task<int> readTask = task as Task<int>;
if (readTask == null)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
try
{
return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception
}
finally
{
_activeReadWriteTask = null;
Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
}
internal void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
Contract.EndContractBlock();
var ar = asyncResult as StreamReadWriteAsyncResult;
var writeTask = _activeReadWriteTask;
if (writeTask == null || ar == null)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask != ar._task)
{
throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask is Task<int>)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
}
finally
{
_activeReadWriteTask = null;
Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
}
private sealed class StreamReadWriteAsyncResult : IAsyncResult
{
internal readonly Stream _stream;
internal readonly byte[] _buffer;
internal readonly int _offset;
internal readonly int _count;
internal readonly AsyncCallback _callback;
internal readonly object _state;
internal Task _task;
internal StreamReadWriteAsyncResult(Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
_stream = stream;
_buffer = buffer;
_offset = offset;
_count = count;
_callback = callback;
_state = state;
}
object IAsyncResult.AsyncState { get { return _state; } } // return caller-provided state, not that from the task
bool IAsyncResult.CompletedSynchronously { get { return false; } } // we always complete asynchronously
bool IAsyncResult.IsCompleted { get { return _task.IsCompleted; } }
WaitHandle IAsyncResult.AsyncWaitHandle { get { return ((IAsyncResult)_task).AsyncWaitHandle; } }
}
}
}
| |
// 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: This class will encapsulate an uint and
** provide an Object representation of it.
**
**
===========================================================*/
namespace System {
using System.Globalization;
using System;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
// * Wrapper for unsigned 32 bit integers.
[Serializable]
[CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
[System.Runtime.InteropServices.ComVisible(true)]
public struct UInt32 : IComparable, IFormattable, IConvertible
, IComparable<UInt32>, IEquatable<UInt32>
{
private uint m_value;
public const uint MaxValue = (uint)0xffffffff;
public const uint MinValue = 0U;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt32, this method throws an ArgumentException.
//
public int CompareTo(Object value) {
if (value == null) {
return 1;
}
if (value is UInt32) {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
uint i = (uint)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeUInt32"));
}
public int CompareTo(UInt32 value) {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(Object obj) {
if (!(obj is UInt32)) {
return false;
}
return m_value == ((UInt32)obj).m_value;
}
[System.Runtime.Versioning.NonVersionable]
public bool Equals(UInt32 obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode() {
return ((int) m_value);
}
// The base 10 representation of the number with no extra padding.
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static uint Parse(String s) {
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(String s, NumberStyles style) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt32(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(String s, IFormatProvider provider) {
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static uint Parse(String s, NumberStyles style, IFormatProvider provider) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static bool TryParse(String s, out UInt32 result) {
return Number.TryParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt32 result) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode() {
return TypeCode.UInt32;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
return Convert.ToBoolean(m_value);
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
return Convert.ToChar(m_value);
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider) {
return Convert.ToSByte(m_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return Convert.ToByte(m_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
return Convert.ToInt16(m_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider) {
return Convert.ToUInt16(m_value);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider) {
return Convert.ToInt32(m_value);
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider) {
return m_value;
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider) {
return Convert.ToInt64(m_value);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider) {
return Convert.ToUInt64(m_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
return Convert.ToSingle(m_value);
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
return Convert.ToDouble(m_value);
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider) {
return Convert.ToDecimal(m_value);
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "UInt32", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AttributeSource = Lucene.Net.Util.AttributeSource;
using BytesRef = Lucene.Net.Util.BytesRef;
using FilteredTermsEnum = Lucene.Net.Index.FilteredTermsEnum;
using NumericUtils = Lucene.Net.Util.NumericUtils;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// <para>A <see cref="Query"/> that matches numeric values within a
/// specified range. To use this, you must first index the
/// numeric values using <see cref="Int32Field"/>,
/// <see cref="SingleField"/>, <see cref="Int64Field"/> or <see cref="DoubleField"/> (expert:
/// <see cref="Analysis.NumericTokenStream"/>). If your terms are instead textual,
/// you should use <see cref="TermRangeQuery"/>.
/// <see cref="NumericRangeFilter"/> is the filter equivalent of this
/// query.</para>
///
/// <para>You create a new <see cref="NumericRangeQuery{T}"/> with the static
/// factory methods, eg:
///
/// <code>
/// Query q = NumericRangeQuery.NewFloatRange("weight", 0.03f, 0.10f, true, true);
/// </code>
///
/// matches all documents whose <see cref="float"/> valued "weight" field
/// ranges from 0.03 to 0.10, inclusive.</para>
///
/// <para>The performance of <see cref="NumericRangeQuery{T}"/> is much better
/// than the corresponding <see cref="TermRangeQuery"/> because the
/// number of terms that must be searched is usually far
/// fewer, thanks to trie indexing, described below.</para>
///
/// <para>You can optionally specify a <a
/// href="#precisionStepDesc"><see cref="precisionStep"/></a>
/// when creating this query. This is necessary if you've
/// changed this configuration from its default (4) during
/// indexing. Lower values consume more disk space but speed
/// up searching. Suitable values are between <b>1</b> and
/// <b>8</b>. A good starting point to test is <b>4</b>,
/// which is the default value for all <c>Numeric*</c>
/// classes. See <a href="#precisionStepDesc">below</a> for
/// details.</para>
///
/// <para>This query defaults to
/// <see cref="MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT"/>.
/// With precision steps of <=4, this query can be run with
/// one of the <see cref="BooleanQuery"/> rewrite methods without changing
/// <see cref="BooleanQuery"/>'s default max clause count.</para>
///
/// <para/><h3>How it works</h3>
///
/// <para>See the publication about <a target="_blank" href="http://www.panfmp.org">panFMP</a>,
/// where this algorithm was described (referred to as <c>TrieRangeQuery</c>):
/// </para>
/// <blockquote><strong>Schindler, U, Diepenbroek, M</strong>, 2008.
/// <em>Generic XML-based Framework for Metadata Portals.</em>
/// Computers & Geosciences 34 (12), 1947-1955.
/// <a href="http://dx.doi.org/10.1016/j.cageo.2008.02.023"
/// target="_blank">doi:10.1016/j.cageo.2008.02.023</a></blockquote>
///
/// <para><em>A quote from this paper:</em> Because Apache Lucene is a full-text
/// search engine and not a conventional database, it cannot handle numerical ranges
/// (e.g., field value is inside user defined bounds, even dates are numerical values).
/// We have developed an extension to Apache Lucene that stores
/// the numerical values in a special string-encoded format with variable precision
/// (all numerical values like <see cref="double"/>s, <see cref="long"/>s, <see cref="float"/>s, and <see cref="int"/>s are converted to
/// lexicographic sortable string representations and stored with different precisions
/// (for a more detailed description of how the values are stored,
/// see <see cref="NumericUtils"/>). A range is then divided recursively into multiple intervals for searching:
/// The center of the range is searched only with the lowest possible precision in the <em>trie</em>,
/// while the boundaries are matched more exactly. This reduces the number of terms dramatically.</para>
///
/// <para>For the variant that stores long values in 8 different precisions (each reduced by 8 bits) that
/// uses a lowest precision of 1 byte, the index contains only a maximum of 256 distinct values in the
/// lowest precision. Overall, a range could consist of a theoretical maximum of
/// <code>7*255*2 + 255 = 3825</code> distinct terms (when there is a term for every distinct value of an
/// 8-byte-number in the index and the range covers almost all of them; a maximum of 255 distinct values is used
/// because it would always be possible to reduce the full 256 values to one term with degraded precision).
/// In practice, we have seen up to 300 terms in most cases (index with 500,000 metadata records
/// and a uniform value distribution).</para>
///
/// <a name="precisionStepDesc"><h3>Precision Step</h3></a>
/// <para/>You can choose any <see cref="precisionStep"/> when encoding values.
/// Lower step values mean more precisions and so more terms in index (and index gets larger). The number
/// of indexed terms per value is (those are generated by <see cref="Analysis.NumericTokenStream"/>):
/// <para>
///   indexedTermsPerValue = <b>ceil</b><big>(</big>bitsPerValue / precisionStep<big>)</big>
/// </para>
/// As the lower precision terms are shared by many values, the additional terms only
/// slightly grow the term dictionary (approx. 7% for <c>precisionStep=4</c>), but have a larger
/// impact on the postings (the postings file will have more entries, as every document is linked to
/// <c>indexedTermsPerValue</c> terms instead of one). The formula to estimate the growth
/// of the term dictionary in comparison to one term per value:
/// <para>
/// <!-- the formula in the alt attribute was transformed from latex to PNG with http://1.618034.com/latex.php (with 110 dpi): -->
///   <img src="doc-files/nrq-formula-1.png" alt="\mathrm{termDictOverhead} = \sum\limits_{i=0}^{\mathrm{indexedTermsPerValue}-1} \frac{1}{2^{\mathrm{precisionStep}\cdot i}}" />
/// </para>
/// <para>On the other hand, if the <see cref="precisionStep"/> is smaller, the maximum number of terms to match reduces,
/// which optimizes query speed. The formula to calculate the maximum number of terms that will be visited while
/// executing the query is:
/// </para>
/// <para>
/// <!-- the formula in the alt attribute was transformed from latex to PNG with http://1.618034.com/latex.php (with 110 dpi): -->
///   <img src="doc-files/nrq-formula-2.png" alt="\mathrm{maxQueryTerms} = \left[ \left( \mathrm{indexedTermsPerValue} - 1 \right) \cdot \left(2^\mathrm{precisionStep} - 1 \right) \cdot 2 \right] + \left( 2^\mathrm{precisionStep} - 1 \right)" />
/// </para>
/// <para>For longs stored using a precision step of 4, <c>maxQueryTerms = 15*15*2 + 15 = 465</c>, and for a precision
/// step of 2, <c>maxQueryTerms = 31*3*2 + 3 = 189</c>. But the faster search speed is reduced by more seeking
/// in the term enum of the index. Because of this, the ideal <see cref="precisionStep"/> value can only
/// be found out by testing. <b>Important:</b> You can index with a lower precision step value and test search speed
/// using a multiple of the original step value.</para>
///
/// <para>Good values for <see cref="precisionStep"/> are depending on usage and data type:</para>
/// <list type="bullet">
/// <item><description>The default for all data types is <b>4</b>, which is used, when no <code>precisionStep</code> is given.</description></item>
/// <item><description>Ideal value in most cases for <em>64 bit</em> data types <em>(long, double)</em> is <b>6</b> or <b>8</b>.</description></item>
/// <item><description>Ideal value in most cases for <em>32 bit</em> data types <em>(int, float)</em> is <b>4</b>.</description></item>
/// <item><description>For low cardinality fields larger precision steps are good. If the cardinality is < 100, it is
/// fair to use <see cref="int.MaxValue"/> (see below).</description></item>
/// <item><description>Steps <b>>=64</b> for <em>long/double</em> and <b>>=32</b> for <em>int/float</em> produces one token
/// per value in the index and querying is as slow as a conventional <see cref="TermRangeQuery"/>. But it can be used
/// to produce fields, that are solely used for sorting (in this case simply use <see cref="int.MaxValue"/> as
/// <see cref="precisionStep"/>). Using <see cref="Int32Field"/>,
/// <see cref="Int64Field"/>, <see cref="SingleField"/> or <see cref="DoubleField"/> for sorting
/// is ideal, because building the field cache is much faster than with text-only numbers.
/// These fields have one term per value and therefore also work with term enumeration for building distinct lists
/// (e.g. facets / preselected values to search for).
/// Sorting is also possible with range query optimized fields using one of the above <see cref="precisionStep"/>s.</description></item>
/// </list>
///
/// <para>Comparisons of the different types of RangeQueries on an index with about 500,000 docs showed
/// that <see cref="TermRangeQuery"/> in boolean rewrite mode (with raised <see cref="BooleanQuery"/> clause count)
/// took about 30-40 secs to complete, <see cref="TermRangeQuery"/> in constant score filter rewrite mode took 5 secs
/// and executing this class took <100ms to complete (on an Opteron64 machine, Java 1.5, 8 bit
/// precision step). This query type was developed for a geographic portal, where the performance for
/// e.g. bounding boxes or exact date/time stamps is important.</para>
///
/// @since 2.9
/// </summary>
public sealed class NumericRangeQuery<T> : MultiTermQuery
where T : struct, IComparable<T> // best equiv constraint for java's number class
{
internal NumericRangeQuery(string field, int precisionStep, NumericType dataType, T? min, T? max, bool minInclusive, bool maxInclusive)
: base(field)
{
if (precisionStep < 1)
{
throw new ArgumentException("precisionStep must be >=1");
}
this.precisionStep = precisionStep;
this.dataType = dataType;
this.min = min;
this.max = max;
this.minInclusive = minInclusive;
this.maxInclusive = maxInclusive;
}
// LUCENENET NOTE: Static methods were moved into the NumericRangeQuery class
protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
{
// very strange: java.lang.Number itself is not Comparable, but all subclasses used here are
if (min.HasValue && max.HasValue && (min.Value).CompareTo(max.Value) > 0)
{
return TermsEnum.EMPTY;
}
return new NumericRangeTermsEnum(this, terms.GetEnumerator());
}
/// <summary>
/// Returns <c>true</c> if the lower endpoint is inclusive </summary>
public bool IncludesMin => minInclusive;
/// <summary>
/// Returns <c>true</c> if the upper endpoint is inclusive </summary>
public bool IncludesMax => maxInclusive;
/// <summary>
/// Returns the lower value of this range query </summary>
public T? Min => min;
/// <summary>
/// Returns the upper value of this range query </summary>
public T? Max => max;
/// <summary>
/// Returns the precision step. </summary>
public int PrecisionStep => precisionStep;
public override string ToString(string field)
{
StringBuilder sb = new StringBuilder();
if (!Field.Equals(field, StringComparison.Ordinal))
{
sb.Append(Field).Append(':');
}
return sb.Append(minInclusive ? '[' : '{').Append((min == null) ? "*" : min.ToString()).Append(" TO ").Append((max == null) ? "*" : max.ToString()).Append(maxInclusive ? ']' : '}').Append(ToStringUtils.Boost(Boost)).ToString();
}
public override bool Equals(object o)
{
if (o == this)
{
return true;
}
if (!base.Equals(o))
{
return false;
}
if (o is NumericRangeQuery<T>)
{
var q = (NumericRangeQuery<T>)o;
return ((q.min == null ? min == null : q.min.Equals(min)) && (q.max == null ? max == null : q.max.Equals(max)) && minInclusive == q.minInclusive && maxInclusive == q.maxInclusive && precisionStep == q.precisionStep);
}
return false;
}
public override int GetHashCode()
{
int hash = base.GetHashCode();
hash += precisionStep ^ 0x64365465;
if (min != null)
{
hash += min.GetHashCode() ^ 0x14fa55fb;
}
if (max != null)
{
hash += max.GetHashCode() ^ 0x733fa5fe;
}
return hash + (Convert.ToBoolean(minInclusive).GetHashCode() ^ 0x14fa55fb) + (Convert.ToBoolean(maxInclusive).GetHashCode() ^ 0x733fa5fe);
}
// members (package private, to be also fast accessible by NumericRangeTermEnum)
internal readonly int precisionStep;
internal readonly NumericType dataType;
internal readonly T? min, max;
internal readonly bool minInclusive, maxInclusive;
// used to handle float/double infinity correcty
/// <summary>
/// NOTE: This was LONG_NEGATIVE_INFINITY in Lucene
/// </summary>
internal static readonly long INT64_NEGATIVE_INFINITY = NumericUtils.DoubleToSortableInt64(double.NegativeInfinity);
/// <summary>
/// NOTE: This was LONG_NEGATIVE_INFINITY in Lucene
/// </summary>
internal static readonly long INT64_POSITIVE_INFINITY = NumericUtils.DoubleToSortableInt64(double.PositiveInfinity);
/// <summary>
/// NOTE: This was INT_NEGATIVE_INFINITY in Lucene
/// </summary>
internal static readonly int INT32_NEGATIVE_INFINITY = NumericUtils.SingleToSortableInt32(float.NegativeInfinity);
/// <summary>
/// NOTE: This was INT_POSITIVE_INFINITY in Lucene
/// </summary>
internal static readonly int INT32_POSITIVE_INFINITY = NumericUtils.SingleToSortableInt32(float.PositiveInfinity);
/// <summary>
/// Subclass of <see cref="FilteredTermsEnum"/> for enumerating all terms that match the
/// sub-ranges for trie range queries, using flex API.
/// <para/>
/// WARNING: this term enumeration is not guaranteed to be always ordered by
/// <see cref="Index.Term.CompareTo(Index.Term)"/>.
/// The ordering depends on how <see cref="NumericUtils.SplitInt64Range(NumericUtils.Int64RangeBuilder, int, long, long)"/> and
/// <see cref="NumericUtils.SplitInt32Range(NumericUtils.Int32RangeBuilder, int, int, int)"/> generates the sub-ranges. For
/// <see cref="MultiTermQuery"/> ordering is not relevant.
/// </summary>
private sealed class NumericRangeTermsEnum : FilteredTermsEnum
{
private readonly NumericRangeQuery<T> outerInstance;
internal BytesRef currentLowerBound, currentUpperBound;
internal readonly Queue<BytesRef> rangeBounds = new Queue<BytesRef>();
internal readonly IComparer<BytesRef> termComp;
internal NumericRangeTermsEnum(NumericRangeQuery<T> outerInstance, TermsEnum tenum)
: base(tenum)
{
this.outerInstance = outerInstance;
switch (this.outerInstance.dataType)
{
case NumericType.INT64:
case NumericType.DOUBLE:
{
// lower
long minBound;
if (this.outerInstance.dataType == NumericType.INT64)
{
minBound = (this.outerInstance.min == null) ? long.MinValue : Convert.ToInt64(this.outerInstance.min.Value, CultureInfo.InvariantCulture);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(this.outerInstance.dataType == NumericType.DOUBLE);
minBound = (this.outerInstance.min == null) ? INT64_NEGATIVE_INFINITY : NumericUtils.DoubleToSortableInt64(Convert.ToDouble(this.outerInstance.min.Value, CultureInfo.InvariantCulture));
}
if (!this.outerInstance.minInclusive && this.outerInstance.min != null)
{
if (minBound == long.MaxValue)
{
break;
}
minBound++;
}
// upper
long maxBound;
if (this.outerInstance.dataType == NumericType.INT64)
{
maxBound = (this.outerInstance.max == null) ? long.MaxValue : Convert.ToInt64(this.outerInstance.max, CultureInfo.InvariantCulture);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(this.outerInstance.dataType == NumericType.DOUBLE);
maxBound = (this.outerInstance.max == null) ? INT64_POSITIVE_INFINITY : NumericUtils.DoubleToSortableInt64(Convert.ToDouble(this.outerInstance.max, CultureInfo.InvariantCulture));
}
if (!this.outerInstance.maxInclusive && this.outerInstance.max != null)
{
if (maxBound == long.MinValue)
{
break;
}
maxBound--;
}
NumericUtils.SplitInt64Range(new Int64RangeBuilderAnonymousInnerClassHelper(this), this.outerInstance.precisionStep, minBound, maxBound);
break;
}
case NumericType.INT32:
case NumericType.SINGLE:
{
// lower
int minBound;
if (this.outerInstance.dataType == NumericType.INT32)
{
minBound = (this.outerInstance.min == null) ? int.MinValue : Convert.ToInt32(this.outerInstance.min, CultureInfo.InvariantCulture);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(this.outerInstance.dataType == NumericType.SINGLE);
minBound = (this.outerInstance.min == null) ? INT32_NEGATIVE_INFINITY : NumericUtils.SingleToSortableInt32(Convert.ToSingle(this.outerInstance.min, CultureInfo.InvariantCulture));
}
if (!this.outerInstance.minInclusive && this.outerInstance.min != null)
{
if (minBound == int.MaxValue)
{
break;
}
minBound++;
}
// upper
int maxBound;
if (this.outerInstance.dataType == NumericType.INT32)
{
maxBound = (this.outerInstance.max == null) ? int.MaxValue : Convert.ToInt32(this.outerInstance.max, CultureInfo.InvariantCulture);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(this.outerInstance.dataType == NumericType.SINGLE);
maxBound = (this.outerInstance.max == null) ? INT32_POSITIVE_INFINITY : NumericUtils.SingleToSortableInt32(Convert.ToSingle(this.outerInstance.max, CultureInfo.InvariantCulture));
}
if (!this.outerInstance.maxInclusive && this.outerInstance.max != null)
{
if (maxBound == int.MinValue)
{
break;
}
maxBound--;
}
NumericUtils.SplitInt32Range(new Int32RangeBuilderAnonymousInnerClassHelper(this), this.outerInstance.precisionStep, minBound, maxBound);
break;
}
default:
// should never happen
throw new ArgumentException("Invalid NumericType");
}
termComp = Comparer;
}
private class Int64RangeBuilderAnonymousInnerClassHelper : NumericUtils.Int64RangeBuilder
{
private readonly NumericRangeTermsEnum outerInstance;
public Int64RangeBuilderAnonymousInnerClassHelper(NumericRangeTermsEnum outerInstance)
{
this.outerInstance = outerInstance;
}
public override sealed void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded)
{
outerInstance.rangeBounds.Enqueue(minPrefixCoded);
outerInstance.rangeBounds.Enqueue(maxPrefixCoded);
}
}
private class Int32RangeBuilderAnonymousInnerClassHelper : NumericUtils.Int32RangeBuilder
{
private readonly NumericRangeTermsEnum outerInstance;
public Int32RangeBuilderAnonymousInnerClassHelper(NumericRangeTermsEnum outerInstance)
{
this.outerInstance = outerInstance;
}
public override sealed void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded)
{
outerInstance.rangeBounds.Enqueue(minPrefixCoded);
outerInstance.rangeBounds.Enqueue(maxPrefixCoded);
}
}
private void NextRange()
{
if (Debugging.AssertsEnabled) Debugging.Assert(rangeBounds.Count % 2 == 0);
currentLowerBound = rangeBounds.Dequeue();
if (Debugging.AssertsEnabled) Debugging.Assert(currentUpperBound == null || termComp.Compare(currentUpperBound, currentLowerBound) <= 0, "The current upper bound must be <= the new lower bound");
currentUpperBound = rangeBounds.Dequeue();
}
protected override sealed BytesRef NextSeekTerm(BytesRef term)
{
while (rangeBounds.Count >= 2)
{
NextRange();
// if the new upper bound is before the term parameter, the sub-range is never a hit
if (term != null && termComp.Compare(term, currentUpperBound) > 0)
{
continue;
}
// never seek backwards, so use current term if lower bound is smaller
return (term != null && termComp.Compare(term, currentLowerBound) > 0) ? term : currentLowerBound;
}
// no more sub-range enums available
if (Debugging.AssertsEnabled) Debugging.Assert(rangeBounds.Count == 0);
currentLowerBound = currentUpperBound = null;
return null;
}
protected override sealed AcceptStatus Accept(BytesRef term)
{
while (currentUpperBound == null || termComp.Compare(term, currentUpperBound) > 0)
{
if (rangeBounds.Count == 0)
{
return AcceptStatus.END;
}
// peek next sub-range, only seek if the current term is smaller than next lower bound
if (termComp.Compare(term, rangeBounds.Peek()) < 0)
{
return AcceptStatus.NO_AND_SEEK;
}
// step forward to next range without seeking, as next lower range bound is less or equal current term
NextRange();
}
return AcceptStatus.YES;
}
}
}
/// <summary>
/// LUCENENET specific class to provide access to static factory metods of <see cref="NumericRangeQuery{T}"/>
/// without referring to its genereic closing type.
/// </summary>
public static class NumericRangeQuery
{
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="long"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newLongRange() in Lucene
/// </summary>
public static NumericRangeQuery<long> NewInt64Range(string field, int precisionStep, long? min, long? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<long>(field, precisionStep, NumericType.INT64, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="long"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newLongRange() in Lucene
/// </summary>
public static NumericRangeQuery<long> NewInt64Range(string field, long? min, long? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<long>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.INT64, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="int"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newIntRange() in Lucene
/// </summary>
public static NumericRangeQuery<int> NewInt32Range(string field, int precisionStep, int? min, int? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<int>(field, precisionStep, NumericType.INT32, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="int"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newIntRange() in Lucene
/// </summary>
public static NumericRangeQuery<int> NewInt32Range(string field, int? min, int? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<int>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.INT32, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="double"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="double.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Double.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// </summary>
public static NumericRangeQuery<double> NewDoubleRange(string field, int precisionStep, double? min, double? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<double>(field, precisionStep, NumericType.DOUBLE, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="double"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="double.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Double.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// </summary>
public static NumericRangeQuery<double> NewDoubleRange(string field, double? min, double? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<double>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.DOUBLE, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="float"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="float.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Single.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newFloatRange() in Lucene
/// </summary>
public static NumericRangeQuery<float> NewSingleRange(string field, int precisionStep, float? min, float? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<float>(field, precisionStep, NumericType.SINGLE, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="float"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="float.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Single.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newFloatRange() in Lucene
/// </summary>
public static NumericRangeQuery<float> NewSingleRange(string field, float? min, float? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<float>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.SINGLE, min, max, minInclusive, maxInclusive);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal sealed class OpenSslX509ChainProcessor : IChainPal
{
// Constructed (0x20) | Sequence (0x10) => 0x30.
private const uint ConstructedSequenceTagId = 0x30;
public void Dispose()
{
}
public bool? Verify(X509VerificationFlags flags, out Exception exception)
{
exception = null;
bool isEndEntity = true;
foreach (X509ChainElement element in ChainElements)
{
if (HasUnsuppressedError(flags, element, isEndEntity))
{
return false;
}
isEndEntity = false;
}
return true;
}
private static bool HasUnsuppressedError(X509VerificationFlags flags, X509ChainElement element, bool isEndEntity)
{
foreach (X509ChainStatus status in element.ChainElementStatus)
{
if (status.Status == X509ChainStatusFlags.NoError)
{
return false;
}
Debug.Assert(
(status.Status & (status.Status - 1)) == 0,
"Only one bit is set in status.Status");
// The Windows certificate store API only checks the time error for a "peer trust" certificate,
// but we don't have a concept for that in Unix. If we did, we'd need to do that logic that here.
// Note also that that logic is skipped if CERT_CHAIN_POLICY_IGNORE_PEER_TRUST_FLAG is set.
X509VerificationFlags? suppressionFlag;
if (status.Status == X509ChainStatusFlags.RevocationStatusUnknown)
{
if (isEndEntity)
{
suppressionFlag = X509VerificationFlags.IgnoreEndRevocationUnknown;
}
else if (IsSelfSigned(element.Certificate))
{
suppressionFlag = X509VerificationFlags.IgnoreRootRevocationUnknown;
}
else
{
suppressionFlag = X509VerificationFlags.IgnoreCertificateAuthorityRevocationUnknown;
}
}
else
{
suppressionFlag = GetSuppressionFlag(status.Status);
}
// If an error was found, and we do NOT have the suppression flag for it enabled,
// we have an unsuppressed error, so return true. (If there's no suppression for a given code,
// we (by definition) don't have that flag set.
if (!suppressionFlag.HasValue ||
(flags & suppressionFlag) == 0)
{
return true;
}
}
return false;
}
public X509ChainElement[] ChainElements { get; private set; }
public X509ChainStatus[] ChainStatus { get; private set; }
public SafeX509ChainHandle SafeHandle
{
get { return null; }
}
public static IChainPal BuildChain(
X509Certificate2 leaf,
HashSet<X509Certificate2> candidates,
HashSet<X509Certificate2> downloaded,
HashSet<X509Certificate2> systemTrusted,
OidCollection applicationPolicy,
OidCollection certificatePolicy,
X509RevocationMode revocationMode,
X509RevocationFlag revocationFlag,
DateTime verificationTime,
ref TimeSpan remainingDownloadTime)
{
X509ChainElement[] elements;
List<X509ChainStatus> overallStatus = new List<X509ChainStatus>();
WorkingChain workingChain = new WorkingChain();
Interop.Crypto.X509StoreVerifyCallback workingCallback = workingChain.VerifyCallback;
// An X509_STORE is more comparable to Cryptography.X509Certificate2Collection than to
// Cryptography.X509Store. So read this with OpenSSL eyes, not CAPI/CNG eyes.
//
// (If you need to think of it as an X509Store, it's a volatile memory store)
using (SafeX509StoreHandle store = Interop.Crypto.X509StoreCreate())
using (SafeX509StoreCtxHandle storeCtx = Interop.Crypto.X509StoreCtxCreate())
{
Interop.Crypto.CheckValidOpenSslHandle(store);
Interop.Crypto.CheckValidOpenSslHandle(storeCtx);
bool lookupCrl = revocationMode != X509RevocationMode.NoCheck;
foreach (X509Certificate2 cert in candidates)
{
OpenSslX509CertificateReader pal = (OpenSslX509CertificateReader)cert.Pal;
if (!Interop.Crypto.X509StoreAddCert(store, pal.SafeHandle))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
if (lookupCrl)
{
CrlCache.AddCrlForCertificate(
cert,
store,
revocationMode,
verificationTime,
ref remainingDownloadTime);
// If we only wanted the end-entity certificate CRL then don't look up
// any more of them.
lookupCrl = revocationFlag != X509RevocationFlag.EndCertificateOnly;
}
}
if (revocationMode != X509RevocationMode.NoCheck)
{
if (!Interop.Crypto.X509StoreSetRevocationFlag(store, revocationFlag))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
}
SafeX509Handle leafHandle = ((OpenSslX509CertificateReader)leaf.Pal).SafeHandle;
if (!Interop.Crypto.X509StoreCtxInit(storeCtx, store, leafHandle))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
Interop.Crypto.X509StoreCtxSetVerifyCallback(storeCtx, workingCallback);
Interop.Crypto.SetX509ChainVerifyTime(storeCtx, verificationTime);
int verify = Interop.Crypto.X509VerifyCert(storeCtx);
if (verify < 0)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
// Because our callback tells OpenSSL that every problem is ignorable, it should tell us that the
// chain is just fine (unless it returned a negative code for an exception)
Debug.Assert(verify == 1, "verify == 1");
using (SafeX509StackHandle chainStack = Interop.Crypto.X509StoreCtxGetChain(storeCtx))
{
int chainSize = Interop.Crypto.GetX509StackFieldCount(chainStack);
elements = new X509ChainElement[chainSize];
int maybeRootDepth = chainSize - 1;
// The leaf cert is 0, up to (maybe) the root at chainSize - 1
for (int i = 0; i < chainSize; i++)
{
List<X509ChainStatus> status = new List<X509ChainStatus>();
List<Interop.Crypto.X509VerifyStatusCode> elementErrors =
i < workingChain.Errors.Count ? workingChain.Errors[i] : null;
if (elementErrors != null)
{
AddElementStatus(elementErrors, status, overallStatus);
}
IntPtr elementCertPtr = Interop.Crypto.GetX509StackField(chainStack, i);
if (elementCertPtr == IntPtr.Zero)
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
// Duplicate the certificate handle
X509Certificate2 elementCert = new X509Certificate2(elementCertPtr);
// If the last cert is self signed then it's the root cert, do any extra checks.
if (i == maybeRootDepth && IsSelfSigned(elementCert))
{
// If the root certificate was downloaded or the system
// doesn't trust it, it's untrusted.
if (downloaded.Contains(elementCert) ||
!systemTrusted.Contains(elementCert))
{
AddElementStatus(
Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_UNTRUSTED,
status,
overallStatus);
}
}
elements[i] = new X509ChainElement(elementCert, status.ToArray(), "");
}
}
}
GC.KeepAlive(workingCallback);
if ((certificatePolicy != null && certificatePolicy.Count > 0) ||
(applicationPolicy != null && applicationPolicy.Count > 0))
{
List<X509Certificate2> certsToRead = new List<X509Certificate2>();
foreach (X509ChainElement element in elements)
{
certsToRead.Add(element.Certificate);
}
CertificatePolicyChain policyChain = new CertificatePolicyChain(certsToRead);
bool failsPolicyChecks = false;
if (certificatePolicy != null)
{
if (!policyChain.MatchesCertificatePolicies(certificatePolicy))
{
failsPolicyChecks = true;
}
}
if (applicationPolicy != null)
{
if (!policyChain.MatchesApplicationPolicies(applicationPolicy))
{
failsPolicyChecks = true;
}
}
if (failsPolicyChecks)
{
X509ChainElement leafElement = elements[0];
X509ChainStatus chainStatus = new X509ChainStatus
{
Status = X509ChainStatusFlags.NotValidForUsage,
StatusInformation = SR.Chain_NoPolicyMatch,
};
var elementStatus = new List<X509ChainStatus>(leafElement.ChainElementStatus.Length + 1);
elementStatus.AddRange(leafElement.ChainElementStatus);
AddUniqueStatus(elementStatus, ref chainStatus);
AddUniqueStatus(overallStatus, ref chainStatus);
elements[0] = new X509ChainElement(
leafElement.Certificate,
elementStatus.ToArray(),
leafElement.Information);
}
}
return new OpenSslX509ChainProcessor
{
ChainStatus = overallStatus.ToArray(),
ChainElements = elements,
};
}
private static void AddElementStatus(
List<Interop.Crypto.X509VerifyStatusCode> errorCodes,
List<X509ChainStatus> elementStatus,
List<X509ChainStatus> overallStatus)
{
foreach (var errorCode in errorCodes)
{
AddElementStatus(errorCode, elementStatus, overallStatus);
}
}
private static void AddElementStatus(
Interop.Crypto.X509VerifyStatusCode errorCode,
List<X509ChainStatus> elementStatus,
List<X509ChainStatus> overallStatus)
{
X509ChainStatusFlags statusFlag = MapVerifyErrorToChainStatus(errorCode);
Debug.Assert(
(statusFlag & (statusFlag - 1)) == 0,
"Status flag has more than one bit set",
"More than one bit is set in status '{0}' for error code '{1}'",
statusFlag,
errorCode);
foreach (X509ChainStatus currentStatus in elementStatus)
{
if ((currentStatus.Status & statusFlag) != 0)
{
return;
}
}
X509ChainStatus chainStatus = new X509ChainStatus
{
Status = statusFlag,
StatusInformation = Interop.Crypto.GetX509VerifyCertErrorString(errorCode),
};
elementStatus.Add(chainStatus);
AddUniqueStatus(overallStatus, ref chainStatus);
}
private static void AddUniqueStatus(IList<X509ChainStatus> list, ref X509ChainStatus status)
{
X509ChainStatusFlags statusCode = status.Status;
for (int i = 0; i < list.Count; i++)
{
if (list[i].Status == statusCode)
{
return;
}
}
list.Add(status);
}
private static X509VerificationFlags? GetSuppressionFlag(X509ChainStatusFlags status)
{
switch (status)
{
case X509ChainStatusFlags.UntrustedRoot:
case X509ChainStatusFlags.PartialChain:
return X509VerificationFlags.AllowUnknownCertificateAuthority;
case X509ChainStatusFlags.NotValidForUsage:
case X509ChainStatusFlags.CtlNotValidForUsage:
return X509VerificationFlags.IgnoreWrongUsage;
case X509ChainStatusFlags.NotTimeValid:
return X509VerificationFlags.IgnoreNotTimeValid;
case X509ChainStatusFlags.CtlNotTimeValid:
return X509VerificationFlags.IgnoreCtlNotTimeValid;
case X509ChainStatusFlags.InvalidNameConstraints:
case X509ChainStatusFlags.HasNotSupportedNameConstraint:
case X509ChainStatusFlags.HasNotDefinedNameConstraint:
case X509ChainStatusFlags.HasNotPermittedNameConstraint:
case X509ChainStatusFlags.HasExcludedNameConstraint:
return X509VerificationFlags.IgnoreInvalidName;
case X509ChainStatusFlags.InvalidPolicyConstraints:
case X509ChainStatusFlags.NoIssuanceChainPolicy:
return X509VerificationFlags.IgnoreInvalidPolicy;
case X509ChainStatusFlags.InvalidBasicConstraints:
return X509VerificationFlags.IgnoreInvalidBasicConstraints;
case X509ChainStatusFlags.HasNotSupportedCriticalExtension:
// This field would be mapped in by AllFlags, but we don't have a name for it currently.
return (X509VerificationFlags)0x00002000;
case X509ChainStatusFlags.NotTimeNested:
return X509VerificationFlags.IgnoreNotTimeNested;
}
return null;
}
private static X509ChainStatusFlags MapVerifyErrorToChainStatus(Interop.Crypto.X509VerifyStatusCode code)
{
switch (code)
{
case Interop.Crypto.X509VerifyStatusCode.X509_V_OK:
return X509ChainStatusFlags.NoError;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_NOT_YET_VALID:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_HAS_EXPIRED:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
return X509ChainStatusFlags.NotTimeValid;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REVOKED:
return X509ChainStatusFlags.Revoked;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_SIGNATURE_FAILURE:
return X509ChainStatusFlags.NotSignatureValid;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_UNTRUSTED:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
return X509ChainStatusFlags.UntrustedRoot;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_HAS_EXPIRED:
return X509ChainStatusFlags.OfflineRevocation;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_NOT_YET_VALID:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_SIGNATURE_FAILURE:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CRL_SIGN:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION:
return X509ChainStatusFlags.RevocationStatusUnknown;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_EXTENSION:
return X509ChainStatusFlags.InvalidExtension;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
return X509ChainStatusFlags.PartialChain;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_PURPOSE:
return X509ChainStatusFlags.NotValidForUsage;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_CA:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_NON_CA:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_PATH_LENGTH_EXCEEDED:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE:
return X509ChainStatusFlags.InvalidBasicConstraints;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_INVALID_POLICY_EXTENSION:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_NO_EXPLICIT_POLICY:
return X509ChainStatusFlags.InvalidPolicyConstraints;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REJECTED:
return X509ChainStatusFlags.ExplicitDistrust;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION:
return X509ChainStatusFlags.HasNotSupportedCriticalExtension;
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_CHAIN_TOO_LONG:
throw new CryptographicException();
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_OUT_OF_MEM:
throw new OutOfMemoryException();
default:
Debug.Fail("Unrecognized X509VerifyStatusCode:" + code);
throw new CryptographicException();
}
}
internal static HashSet<X509Certificate2> FindCandidates(
X509Certificate2 leaf,
X509Certificate2Collection extraStore,
HashSet<X509Certificate2> downloaded,
HashSet<X509Certificate2> systemTrusted,
ref TimeSpan remainingDownloadTime)
{
var candidates = new HashSet<X509Certificate2>();
var toProcess = new Queue<X509Certificate2>();
toProcess.Enqueue(leaf);
using (var systemRootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
using (var systemIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine))
using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
using (var userIntermediateStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser))
{
systemRootStore.Open(OpenFlags.ReadOnly);
systemIntermediateStore.Open(OpenFlags.ReadOnly);
userRootStore.Open(OpenFlags.ReadOnly);
userIntermediateStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection systemRootCerts = systemRootStore.Certificates;
X509Certificate2Collection systemIntermediateCerts = systemIntermediateStore.Certificates;
X509Certificate2Collection userRootCerts = userRootStore.Certificates;
X509Certificate2Collection userIntermediateCerts = userIntermediateStore.Certificates;
// fill the system trusted collection
foreach (X509Certificate2 userRootCert in userRootCerts)
{
if (!systemTrusted.Add(userRootCert))
{
// If we have already (effectively) added another instance of this certificate,
// then this one provides no value. A Disposed cert won't harm the matching logic.
userRootCert.Dispose();
}
}
foreach (X509Certificate2 systemRootCert in systemRootCerts)
{
if (!systemTrusted.Add(systemRootCert))
{
// If we have already (effectively) added another instance of this certificate,
// (for example, because another copy of it was in the user store)
// then this one provides no value. A Disposed cert won't harm the matching logic.
systemRootCert.Dispose();
}
}
X509Certificate2Collection[] storesToCheck =
{
extraStore,
userIntermediateCerts,
systemIntermediateCerts,
userRootCerts,
systemRootCerts,
};
while (toProcess.Count > 0)
{
X509Certificate2 current = toProcess.Dequeue();
candidates.Add(current);
HashSet<X509Certificate2> results = FindIssuer(
current,
storesToCheck,
downloaded,
ref remainingDownloadTime);
if (results != null)
{
foreach (X509Certificate2 result in results)
{
if (!candidates.Contains(result))
{
toProcess.Enqueue(result);
}
}
}
}
// Avoid sending unused certs into the finalizer queue by doing only a ref check
var candidatesByReference = new HashSet<X509Certificate2>(
candidates,
ReferenceEqualityComparer<X509Certificate2>.Instance);
// Certificates come from 5 sources:
// 1) extraStore.
// These are cert objects that are provided by the user, we shouldn't dispose them.
// 2) the machine root store
// These certs are moving on to the "was I a system trust?" test, and we shouldn't dispose them.
// 3) the user root store
// These certs are moving on to the "was I a system trust?" test, and we shouldn't dispose them.
// 4) the machine intermediate store
// These certs were either path candidates, or not. If they were, don't dispose them. Otherwise do.
// 5) the user intermediate store
// These certs were either path candidates, or not. If they were, don't dispose them. Otherwise do.
DisposeUnreferenced(candidatesByReference, systemIntermediateCerts);
DisposeUnreferenced(candidatesByReference, userIntermediateCerts);
}
return candidates;
}
private static void DisposeUnreferenced(
ISet<X509Certificate2> referencedSet,
X509Certificate2Collection storeCerts)
{
foreach (X509Certificate2 cert in storeCerts)
{
if (!referencedSet.Contains(cert))
{
cert.Dispose();
}
}
}
private static HashSet<X509Certificate2> FindIssuer(
X509Certificate2 cert,
X509Certificate2Collection[] stores,
HashSet<X509Certificate2> downloadedCerts,
ref TimeSpan remainingDownloadTime)
{
if (IsSelfSigned(cert))
{
// It's a root cert, we won't make any progress.
return null;
}
SafeX509Handle certHandle = ((OpenSslX509CertificateReader)cert.Pal).SafeHandle;
foreach (X509Certificate2Collection store in stores)
{
HashSet<X509Certificate2> fromStore = null;
foreach (X509Certificate2 candidate in store)
{
var certPal = (OpenSslX509CertificateReader)candidate.Pal;
if (certPal == null)
{
continue;
}
SafeX509Handle candidateHandle = certPal.SafeHandle;
int issuerError = Interop.Crypto.X509CheckIssued(candidateHandle, certHandle);
if (issuerError == 0)
{
if (fromStore == null)
{
fromStore = new HashSet<X509Certificate2>();
}
fromStore.Add(candidate);
}
}
if (fromStore != null)
{
return fromStore;
}
}
byte[] authorityInformationAccess = null;
foreach (X509Extension extension in cert.Extensions)
{
if (StringComparer.Ordinal.Equals(extension.Oid.Value, Oids.AuthorityInformationAccess))
{
// If there's an Authority Information Access extension, it might be used for
// looking up additional certificates for the chain.
authorityInformationAccess = extension.RawData;
break;
}
}
if (authorityInformationAccess != null)
{
X509Certificate2 downloaded = DownloadCertificate(
authorityInformationAccess,
ref remainingDownloadTime);
if (downloaded != null)
{
downloadedCerts.Add(downloaded);
return new HashSet<X509Certificate2>() { downloaded };
}
}
return null;
}
private static bool IsSelfSigned(X509Certificate2 cert)
{
return StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer);
}
private static X509Certificate2 DownloadCertificate(
byte[] authorityInformationAccess,
ref TimeSpan remainingDownloadTime)
{
// Don't do any work if we're over limit.
if (remainingDownloadTime <= TimeSpan.Zero)
{
return null;
}
string uri = FindHttpAiaRecord(authorityInformationAccess, Oids.CertificateAuthorityIssuers);
if (uri == null)
{
return null;
}
return CertificateAssetDownloader.DownloadCertificate(uri, ref remainingDownloadTime);
}
internal static string FindHttpAiaRecord(byte[] authorityInformationAccess, string recordTypeOid)
{
DerSequenceReader reader = new DerSequenceReader(authorityInformationAccess);
while (reader.HasData)
{
DerSequenceReader innerReader = reader.ReadSequence();
// If the sequence's first element is a sequence, unwrap it.
if (innerReader.PeekTag() == ConstructedSequenceTagId)
{
innerReader = innerReader.ReadSequence();
}
Oid oid = innerReader.ReadOid();
if (StringComparer.Ordinal.Equals(oid.Value, recordTypeOid))
{
string uri = innerReader.ReadIA5String();
Uri parsedUri;
if (!Uri.TryCreate(uri, UriKind.Absolute, out parsedUri))
{
continue;
}
if (!StringComparer.Ordinal.Equals(parsedUri.Scheme, "http"))
{
continue;
}
return uri;
}
}
return null;
}
private class WorkingChain
{
internal readonly List<List<Interop.Crypto.X509VerifyStatusCode>> Errors =
new List<List<Interop.Crypto.X509VerifyStatusCode>>();
internal int VerifyCallback(int ok, IntPtr ctx)
{
if (ok < 0)
{
return ok;
}
try
{
using (var storeCtx = new SafeX509StoreCtxHandle(ctx, ownsHandle: false))
{
Interop.Crypto.X509VerifyStatusCode errorCode = Interop.Crypto.X509StoreCtxGetError(storeCtx);
int errorDepth = Interop.Crypto.X509StoreCtxGetErrorDepth(storeCtx);
// We don't report "OK" as an error.
// For compatibility with Windows / .NET Framework, do not report X509_V_CRL_NOT_YET_VALID.
if (errorCode != Interop.Crypto.X509VerifyStatusCode.X509_V_OK &&
errorCode != Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CRL_NOT_YET_VALID)
{
while (Errors.Count <= errorDepth)
{
Errors.Add(null);
}
if (Errors[errorDepth] == null)
{
Errors[errorDepth] = new List<Interop.Crypto.X509VerifyStatusCode>();
}
Errors[errorDepth].Add(errorCode);
}
}
return 1;
}
catch
{
return -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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace System.Globalization
{
internal partial class CultureData
{
// ICU constants
const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value
const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name
const string ICU_COLLATION_KEYWORD = "@collation=";
/// <summary>
/// This method uses the sRealName field (which is initialized by the constructor before this is called) to
/// initialize the rest of the state of CultureData based on the underlying OS globalization library.
/// </summary>
private unsafe bool InitCultureData()
{
Debug.Assert(_sRealName != null);
Debug.Assert(!GlobalizationMode.Invariant);
string realNameBuffer = _sRealName;
// Basic validation
if (realNameBuffer.Contains('@'))
{
return false; // don't allow ICU variants to come in directly
}
// Replace _ (alternate sort) with @collation= for ICU
ReadOnlySpan<char> alternateSortName = default;
int index = realNameBuffer.IndexOf('_');
if (index > 0)
{
if (index >= (realNameBuffer.Length - 1) // must have characters after _
|| realNameBuffer.IndexOf('_', index + 1) >= 0) // only one _ allowed
{
return false; // fail
}
alternateSortName = realNameBuffer.AsSpan(index + 1);
realNameBuffer = string.Concat(realNameBuffer.AsSpan(0, index), ICU_COLLATION_KEYWORD, alternateSortName);
}
// Get the locale name from ICU
if (!GetLocaleName(realNameBuffer, out _sWindowsName))
{
return false; // fail
}
// Replace the ICU collation keyword with an _
Debug.Assert(_sWindowsName != null);
index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal);
if (index >= 0)
{
_sName = string.Concat(_sWindowsName.AsSpan(0, index), "_", alternateSortName);
}
else
{
_sName = _sWindowsName;
}
_sRealName = _sName;
_iLanguage = LCID;
if (_iLanguage == 0)
{
_iLanguage = CultureInfo.LOCALE_CUSTOM_UNSPECIFIED;
}
_bNeutral = TwoLetterISOCountryName.Length == 0;
_sSpecificCulture = _bNeutral ? LocaleData.GetSpecificCultureName(_sRealName) : _sRealName;
// Remove the sort from sName unless custom culture
if (index > 0 && !_bNeutral && !IsCustomCultureId(_iLanguage))
{
_sName = _sWindowsName.Substring(0, index);
}
return true;
}
internal static unsafe bool GetLocaleName(string localeName, out string? windowsName)
{
// Get the locale name from ICU
char* buffer = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
if (!Interop.Globalization.GetLocaleName(localeName, buffer, ICU_ULOC_FULLNAME_CAPACITY))
{
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = new string(buffer); // the name passed to subsequent ICU calls
return true;
}
internal static unsafe bool GetDefaultLocaleName(out string? windowsName)
{
// Get the default (system) locale name from ICU
char* buffer = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
if (!Interop.Globalization.GetDefaultLocaleName(buffer, ICU_ULOC_FULLNAME_CAPACITY))
{
windowsName = null;
return false; // fail
}
// Success - use the locale name returned which may be different than realNameBuffer (casing)
windowsName = new string(buffer); // the name passed to subsequent ICU calls
return true;
}
private string GetLocaleInfo(LocaleStringData type)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
return GetLocaleInfo(_sWindowsName, type);
}
// For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
// "windows" name, which can be specific for downlevel (< windows 7) os's.
private unsafe string GetLocaleInfo(string localeName, LocaleStringData type)
{
Debug.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
switch (type)
{
case LocaleStringData.NegativeInfinitySymbol:
// not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign
return GetLocaleInfo(localeName, LocaleStringData.NegativeSign) +
GetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol);
}
char* buffer = stackalloc char[ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY];
bool result = Interop.Globalization.GetLocaleInfoString(localeName, (uint)type, buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
if (!result)
{
// Failed, just use empty string
Debug.Fail("[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
return string.Empty;
}
return new string(buffer);
}
private int GetLocaleInfo(LocaleNumberData type)
{
Debug.Assert(!GlobalizationMode.Invariant);
Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
switch (type)
{
case LocaleNumberData.CalendarType:
// returning 0 will cause the first supported calendar to be returned, which is the preferred calendar
return 0;
}
int value = 0;
bool result = Interop.Globalization.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value);
if (!result)
{
// Failed, just use 0
Debug.Fail("[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
}
return value;
}
private int[] GetLocaleInfo(LocaleGroupingData type)
{
Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
int primaryGroupingSize = 0;
int secondaryGroupingSize = 0;
bool result = Interop.Globalization.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
if (!result)
{
Debug.Fail("[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
}
if (secondaryGroupingSize == 0)
{
return new int[] { primaryGroupingSize };
}
return new int[] { primaryGroupingSize, secondaryGroupingSize };
}
private string GetTimeFormatString() => GetTimeFormatString(shortFormat: false);
private unsafe string GetTimeFormatString(bool shortFormat)
{
Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
char* buffer = stackalloc char[ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY];
bool result = Interop.Globalization.GetLocaleTimeFormat(_sWindowsName, shortFormat, buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
if (!result)
{
// Failed, just use empty string
Debug.Fail("[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
return string.Empty;
}
var span = new ReadOnlySpan<char>(buffer, ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
return ConvertIcuTimeFormatString(span.Slice(0, span.IndexOf('\0')));
}
private int GetFirstDayOfWeek() => GetLocaleInfo(LocaleNumberData.FirstDayOfWeek);
private string[] GetTimeFormats()
{
string format = GetTimeFormatString(false);
return new string[] { format };
}
private string[] GetShortTimeFormats()
{
string format = GetTimeFormatString(true);
return new string[] { format };
}
private static CultureData? GetCultureDataFromRegionName(string? regionName)
{
// no support to lookup by region name, other than the hard-coded list in CultureData
return null;
}
private static string GetLanguageDisplayName(string cultureName)
{
return new CultureInfo(cultureName)._cultureData.GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
}
private static string? GetRegionDisplayName(string? isoCountryCode)
{
// use the fallback which is to return NativeName
return null;
}
private static CultureInfo GetUserDefaultCulture()
{
return CultureInfo.GetUserDefaultCulture();
}
private static string ConvertIcuTimeFormatString(ReadOnlySpan<char> icuFormatString)
{
Debug.Assert(icuFormatString.Length < ICU_ULOC_FULLNAME_CAPACITY);
Span<char> result = stackalloc char[ICU_ULOC_FULLNAME_CAPACITY];
bool amPmAdded = false;
int resultPos = 0;
for (int i = 0; i < icuFormatString.Length; i++)
{
switch (icuFormatString[i])
{
case '\'':
result[resultPos++] = icuFormatString[i++];
while (i < icuFormatString.Length)
{
char current = icuFormatString[i++];
result[resultPos++] = current;
if (current == '\'')
{
break;
}
}
break;
case ':':
case '.':
case 'H':
case 'h':
case 'm':
case 's':
result[resultPos++] = icuFormatString[i];
break;
case ' ':
case '\u00A0':
// Convert nonbreaking spaces into regular spaces
result[resultPos++] = ' ';
break;
case 'a': // AM/PM
if (!amPmAdded)
{
amPmAdded = true;
result[resultPos++] = 't';
result[resultPos++] = 't';
}
break;
}
}
return result.Slice(0, resultPos).ToString();
}
private static string? LCIDToLocaleName(int culture)
{
Debug.Assert(!GlobalizationMode.Invariant);
return LocaleData.LCIDToLocaleName(culture);
}
private static int LocaleNameToLCID(string cultureName)
{
Debug.Assert(!GlobalizationMode.Invariant);
int lcid = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.Lcid);
return lcid == -1 ? CultureInfo.LOCALE_CUSTOM_UNSPECIFIED : lcid;
}
private static int GetAnsiCodePage(string cultureName)
{
int ansiCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.AnsiCodePage);
return ansiCodePage == -1 ? CultureData.Invariant.ANSICodePage : ansiCodePage;
}
private static int GetOemCodePage(string cultureName)
{
int oemCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.OemCodePage);
return oemCodePage == -1 ? CultureData.Invariant.OEMCodePage : oemCodePage;
}
private static int GetMacCodePage(string cultureName)
{
int macCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.MacCodePage);
return macCodePage == -1 ? CultureData.Invariant.MacCodePage : macCodePage;
}
private static int GetEbcdicCodePage(string cultureName)
{
int ebcdicCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.EbcdicCodePage);
return ebcdicCodePage == -1 ? CultureData.Invariant.EBCDICCodePage : ebcdicCodePage;
}
private static int GetGeoId(string cultureName)
{
int geoId = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.GeoId);
return geoId == -1 ? CultureData.Invariant.GeoId : geoId;
}
private static int GetDigitSubstitution(string cultureName)
{
int digitSubstitution = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.DigitSubstitution);
return digitSubstitution == -1 ? (int) DigitShapes.None : digitSubstitution;
}
private static string GetThreeLetterWindowsLanguageName(string cultureName)
{
return LocaleData.GetThreeLetterWindowsLanguageName(cultureName) ?? "ZZZ" /* default lang name */;
}
private static CultureInfo[] EnumCultures(CultureTypes types)
{
Debug.Assert(!GlobalizationMode.Invariant);
if ((types & (CultureTypes.NeutralCultures | CultureTypes.SpecificCultures)) == 0)
{
return Array.Empty<CultureInfo>();
}
int bufferLength = Interop.Globalization.GetLocales(null, 0);
if (bufferLength <= 0)
{
return Array.Empty<CultureInfo>();
}
char [] chars = new char[bufferLength];
bufferLength = Interop.Globalization.GetLocales(chars, bufferLength);
if (bufferLength <= 0)
{
return Array.Empty<CultureInfo>();
}
bool enumNeutrals = (types & CultureTypes.NeutralCultures) != 0;
bool enumSpecificss = (types & CultureTypes.SpecificCultures) != 0;
List<CultureInfo> list = new List<CultureInfo>();
if (enumNeutrals)
{
list.Add(CultureInfo.InvariantCulture);
}
int index = 0;
while (index < bufferLength)
{
int length = (int) chars[index++];
if (index + length <= bufferLength)
{
CultureInfo ci = CultureInfo.GetCultureInfo(new string(chars, index, length));
if ((enumNeutrals && ci.IsNeutralCulture) || (enumSpecificss && !ci.IsNeutralCulture))
{
list.Add(ci);
}
}
index += length;
}
return list.ToArray();
}
private static string GetConsoleFallbackName(string cultureName)
{
return LocaleData.GetConsoleUICulture(cultureName);
}
internal bool IsFramework => false;
internal bool IsWin32Installed => false;
internal bool IsReplacementCulture => false;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.